<?php

namespace App\Console\Commands;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send email alert';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $now=Carbon::now();
        $this->info($now->toDateTimeString() . '| checking for error ...');

        $html = '<h3 style="color: red">Deywuro Alert!!!</h3><hr />';
        $html .= '<b><u>Date</u>: '.$now->toDateTimeString().'</b><br /><br />';
        $html .= 'Hello Team, this is an automated email alert sent from Deywuro. <br />
            Some error(s) occurred on the SMS Platform, find below more details about the error(s)<br /><br />';
        $html .= '<table style="width: 100%" border="1" cellspacing="1" cellpadding="1">';
        $html .= '<tr style="background-color:#ccc;"><th>Date</th><th>Source</th><th>Error Message</th></tr>';

        $data = DB::select('select * from `error_alert` order by `date` DESC');

        foreach ($data as $record) {
            //check stop service flag
            if(!ServiceTools::can_run_service()) {
                $this->info('Service Stopped By User!');
                exit(1);
            }
            $html .= '<tr><td>'.$record->date.'</td><td>'.$record->file.'</td><td>'.$record->errorMsg.'</td></tr>';
        }
        DB::delete('delete from `error_alert`');

        $html .= '</table>';

        if(count($data)>0) {
            $this->info($now->toDateTimeString() . '| '.count($data).' Error(s) found ...');
            Mail::send('emails.alert', ['html'=>$html], function ($m) {
                $m_email = 'support@npontu.com';
                $m->from($m_email, 'Deywuro Alert');
                $m->to('appengineer@npontu.com', 'Dev Team');
                $m->cc('support@npontu.com', 'Support Team');
                $m->subject('Deywuro - Error Alert!!');
            });
        } else {
            $this->info($now->toDateTimeString() . '| No error found ...');
        }
    }
}
