<?php

namespace App\Console\Commands;

use App\CronJobStat;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check for hanged job(s)';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //start
        $now = Carbon::now();
        $three_min_ago=Carbon::now()->subMinutes(3)->copy();
        $one_hour_ago=Carbon::now()->subMinute(59)->copy();
        $this->info($now->toDateTimeString() . '| checking for hanged job(s) ...');

        $data = CronJobStat::where([
            ['name', '<>', 'DLR_QUERY'],
            ['name', '<>', 'EMAIL_QUERY'],
            ['last_run', '<', $three_min_ago->toDateTimeString()]
        ])->get();



        $html = '<h3 style="color: red">MTN MESSENGER Alert!!!</h3><hr />';
        $html .= '<b><u>Date</u>: '.$now->toDateTimeString().'</b><br /><br />';
        $html .= 'Hello Team, this is an automated email alert sent from MTN MESSENGER. <br />
            The scheduled tasks (cronjob) below have not been running for the past 3min<br /><br />';
        $html .= '<table style="width: 100%" border="1" cellspacing="1" cellpadding="1">';
        $html .= '<tr style="background-color:#ccc;"><th>Last Run</th><th>Status</th><th>Source</th><th>Description</th></tr>';

        foreach ($data as $record) {
            $html .= '<tr><td>'.$record->last_run.'</td><td>'.$record->status.'</td><td>'.$record->name.'</td><td>'.$record->description.'</td></tr>';
        }


        $html .= '</table>';

        if($data->count()>0) {
            $this->info($now->toDateTimeString() . '| '.count($data).' hanged Job(s) found ...');
            /*
            Mail::send('emails.alert', ['html'=>$html], function ($m) {
                $m_email = 'support@npontu.com';
                $m->from($m_email, 'MESSENGER Alert');
                $m->to('appengineer@npontu.com', 'Dev Team');
                $m->cc('npontualph@gmail.com', 'Alphonse Malan');
                $m->subject('MTN MESSENGER - Emergency!!');
            });
            */
        }
    }
}
