<?php

namespace App\Console\Commands;

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

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 => '.$e->getMessage());
        }

        try {
            $this->_domainVerifications();
        } catch(\Exception $e) {
            echo $e->getMessage();
            \Log::error('relayzo:maintenance => '.$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);
        }

    }
}
