<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class SendEmailCommand extends Command
{
    protected $signature = 'job:send_mail';
    protected $description = 'setiap ada data di table batch email, akan dikirim';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $datas = DB::select("SELECT * FROM batch_emails WHERE f_execute in(0,3) AND subject is not null AND to_emails is not null AND COALESCE(body_type,'') != '' AND COALESCE(body,'') != '' ORDER BY id ASC");
        if ($datas) {
            foreach ($datas as $key => $data) {

                // tandai sedang di proses
                DB::table('batch_emails')
                    ->where('id', $data->id)
                    ->update(['f_execute' => 1]);

                $logkey = Carbon::now()->format('YmdHisv') . str_replace('-', '', Str::uuid()->toString());
                Log::channel('job_send_mail')->info(' ::key' . $logkey . ' => =======================start');

                try {
                    $subject = $data->subject;
                    $emails = json_decode($data->to_emails ?? '[]', true);
                    $cc = json_decode($data->cc_emails ?? '[]', true);
                    $attach = json_decode($data->attachment ?? '[]', true);

                    $callback = function ($message) use ($subject, $attach, $emails, $cc) {
                        $message->to($emails)
                            ->subject($subject);

                        if (!empty($cc)) {
                            $message->cc($cc);
                        }

                        if (!empty($attach)) {
                            foreach ($attach as $file) {
                                if (file_exists($file)) {
                                    $message->attach($file);
                                }
                            }
                        }
                    };

                    //tentukan type body nya
                    if ($data->body_type == 'html') {
                        Mail::html($data->body, $callback);
                    } else {
                        Mail::raw($data->body, $callback);
                    }

                    Log::channel('job_send_mail')->info(' ::key' . $logkey . ' => Email berhasil dikirim.');
                    DB::table('batch_emails')->where('id', $data->id)->delete();
                } catch (\Exception $e) {
                    DB::table('batch_emails')->where('id', $data->id)->update(['f_execute' => 3]);
                    Log::channel('job_send_mail')->info(' ::key' . $logkey . ' => Gagal mengirim email: ' . $e->getMessage());
                    Log::channel('job_send_mail')->info(' ::key' . $logkey . ' => Gagal mengirim email: ' . $e->getTraceAsString());
                }
                Log::channel('job_send_mail')->info(' ::key' . $logkey . ' => =======================end');
            }

            //untuk kebutuhan apabila mau cek apakah job selama ini jalan?
            $updated = DB::table('t_cron_jobs')
                ->where(DB::raw('TRIM(name)'), $this->signature)
                ->update([
                    'counting' => DB::raw('counting + 1'),
                    'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
                ]);

            if (!$updated) {
                DB::table('t_cron_jobs')->insert([
                    'name'          => $this->signature,
                    'description'   => $this->description,
                    'counting'      => 1
                ]);
            }
        }
    }
}
