<?php

namespace App\Console\Commands;

use App\CronJobStat;
use App\EmailLog;
use App\Log;
use App\Tools\CustomSmppClient;
use App\Tools\EmailAlert;
use App\Tools\ServiceTools;
use App\Tools\SMPP;
use App\Tools\SmppAddress;
use App\Tools\SmppException;
use App\Tools\SocketTransport;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Query Email to Update Status';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private function check_for_stop_flag() {
        //check stop service flag
        if(!ServiceTools::can_run_service()) {
            $this->info('Service Stopped By User!');
            exit(1);
        }
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $cron = CronJobStat::where('name', 'EMAIL_QUERY')->firstOrFail();
        $cron->update([
            'last_run'=>Carbon::now(),
            'status' => 'RUNNING',
            'child_process'=> 1
        ]);

        //SETUP
        $this->info(Carbon::now()->toDateTimeString() . '| Starting query email status ...');

        $domain = env('MAILGUN_DOMAIN', 'mail.deywuro.com');
        $request_url = "https://api.mailgun.net/v3/$domain/events?";
        $data = array(
            'begin' => Carbon::today()->subDays(3)->toRfc822String(),
            'ascending' => 'yes',
            'limit' => '100'
        );
        $request_url .= http_build_query($data);
        $api_key = env('MAILGUN_API_KEY', 'key-c2db007fa3f8bb651ad1ffd4bde9d914');

        $records = [];
//        $this->info(Carbon::now()->toDateTimeString() . '| Fetching data from email server ...');

        while(true) {
            $this->check_for_stop_flag();
            if(empty($request_url)) break;
            $cURL = curl_init();
            curl_setopt($cURL, CURLOPT_URL, $request_url);
            curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($cURL, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($cURL, CURLOPT_USERPWD, "api:$api_key");
            curl_setopt($cURL, CURLOPT_HTTPHEADER, array("auth=PLAIN"));
            $result=curl_exec($cURL);
            curl_close($cURL);

            $array = json_decode(trim($result), TRUE);

            $request_url = (isset($array['paging']) && isset($array['paging']['next'])) ? $array['paging']['next']: '';
            if(empty($array['items'])) {
                break;
            }
            foreach ($array['items'] as $item) {
                if(isset($item['event']) && !empty($item['event'])) {
                    $records[] = [
                        'status' => $item['event'],
                        'id' => $item['message']['headers']['message-id'],
                        'timestamp' =>Carbon::createFromTimestamp($item['timestamp'])->toDateTimeString()
                    ];
                }
            }
        }

        //update table
//        $this->info(Carbon::now()->toDateTimeString() . '| Updating Email Status ...');

        foreach ($records as $record) {
            $email_log = EmailLog::where('msgid', $record['id'])->first();
            if(empty($email_log)) continue;
            $email_log->status = strtoupper($record['status']);
            $date1 = Carbon::parse($record['timestamp']);
            if(empty($email_log->delivery_date) || $email_log->delivery_date->lt($date1)) {
                $email_log->delivery_date = $date1;
                $email_log->save();
            }
        }

        $cron = CronJobStat::where('name', 'EMAIL_QUERY')->firstOrFail();
        $cron->update([
            'last_run'=>Carbon::now(),
            'status' => 'DONE',
            'child_process'=> 0
        ]);
        $this->info(Carbon::now()->toDateTimeString() . '| Task Complete');
    }
}
