<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Helper\Helper;
use App\Models\GlobalBounce;

class Maintenance extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'relayzo:maintenance';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Maintain Application';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Check if update is available
        try {
            $this->_checkUpdateAvailable();
        } catch(\Exception $e) {
            //echo $e->getMessage();
            //\Log::error('relayzo:maintenance 1 => '.$e->getMessage());
        }

        // Verify domains set by auto_verify
        try {
            $this->_domainVerifications();
        } catch(\Exception $e) {
            //echo $e->getMessage();
            //\Log::error('relayzo:maintenance 2 => '.$e->getMessage());
        }

        // Check DNSLB Lookups
        try {
            Helper::checkIPsDomainsLookup();
        } catch(\Exception $e) {
            //echo $e->getMessage();
            //\Log::error('relayzo:maintenance 3 => '.$e->getMessage());
        }

        /**
        * Verify License to App work smoothly
        * WARNING!!! Avoid to make any changes in it.
        */
        try {
          $this->verify();
        } catch(\Exception $e) {
          //echo $e->getMessage();
          //\Log::error('relayzo:maintenance 4 => '.$e->getMessage());
        }

        // Delete Soft bounces
        try {
          $this->_softBouncesClear();
        } catch(\Exception $e) {
          //echo $e->getMessage();
          //\Log::error('relayzo:maintenance 4 => '.$e->getMessage());
        }
    
    }

    private function _checkUpdateAvailable()
    {
        $settings = \DB::table('settings')->whereId(config('custom.app_id'))->select('current_version')->first();
        $available_version = Helper::getUrl(config('custom.version_live_url'));

        if($available_version > $settings->current_version) {
          // save notification
          $notification = [
            'name' => __('app.update_available_msg'),
            'type' => 'update',
            'attributes' => null,
            'app_id' => config('custom.app_id'),
            'user_id' => config('custom.superadmin')
          ];
          \App\Models\Notification::create($notification);
        }
    }

    /**
    * Verify sending domains keys dkim, dmarc, spf, tracking
    */
    private function _domainVerifications()
    {
        $sending_domains = \App\Models\SendingDomain::whereIsActive(true)
            ->whereAutoVerification(true)
            ->get();

        foreach($sending_domains as $sending_domain) {
          Helper::verifyDKIM($sending_domain);

          // 2 sec delay to get dns entries angain
          sleep(2);
          // Verify SPF
          Helper::verifySPF($sending_domain);

          // 2 sec delay to get dns entries angain
          sleep(2);
          // Verify SPF
          Helper::verifyDMARC($sending_domain);
        }

        // Tracking Domains Verification
        $tracking_domains = \App\Models\TrackingDomain::whereIsActive(true)
            ->whereAutoVerification(true)
            ->get();

        foreach($tracking_domains as $tracking_domain) {
          Helper::verifyTracking($tracking_domain);
        }

    }

    // get soft bounes and delete
    private function _softBouncesClear()
    {
        $soft_bounces = GlobalBounce::whereType('Soft')->get();
        foreach($soft_bounces as $bounce) {
           \App\Models\Contact::whereEmail($bounce->email)->update([
              'is_bounced' => false
            ]);
           GlobalBounce::where('id', $bounce->id)->delete();
        }
    }

    /**
    * Verify License to App work smoothly
    * WARNING!!! Avoid to make any changes in it.
    */
    private function verify()
    {
        $settings = \DB::table('settings')->whereId(config('custom.app_id'))->select('license_key', 'server_ip', 'app_url', 'from_email')->first();
        $data = [
          'is_auto_verify' => true,
          'license_key' => $settings->license_key,
          'server_ip' => $settings->server_ip,
          'domain' =>  $settings->app_url,
          'email' => $settings->from_email
        ];

        try {
          $result = json_decode(Helper::verifyLicense($data), true);

          if(!empty($result['message']) && ($result['message'] == 'Invalid License Key' || $result['message'] == 'License is Already Using')) {
             \DB::table('settings')->whereId(config('custom.app_id'))->update(['license_key' => null]);
          }
        } catch(\Exception $e) {
            //echo $e->getMessage();
          // \Log::error('relayzo:maintenance 5 => '.$e->getMessage());
        }
    }
}
