<?php

namespace App\Console\Commands;

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

class SendErrorLogEmailCommand extends Command
{
    protected $signature = 'job:send_system_errors';
    protected $description = 'error yang terekam di apps dikirim ke email';

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

    public function handle()
    {
        //get data system error
        $system_errors = DB::table('system_errors')
            ->whereRaw("COALESCE(TRIM(message),'') != ''")
            ->orderBy('id', 'asc')
            ->limit(10)
            ->get();

        //get data logs yg levelnya ERROR
        $logs = DB::table('system_logs')
            ->where('send_mail', 0)
            ->whereRaw("TRIM(status_code) = '500'")
            ->orderBy('id', 'asc')
            ->limit(10)
            ->get();

        if ($system_errors->isEmpty() and $logs->isEmpty()) {
            return;
        }

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

        // Simpan list ID yang diproses
        $system_error_ids = $system_errors->pluck('id')->toArray();
        $log_ids = $logs->pluck('id')->toArray();

        // Buat isi file txt
        $content = "";
        foreach ($system_errors as $log) {
            $content .= "SOURCE : table system_errors\n";
            $content .= "ID: {$log->id}\n";
            $content .= "Type: {$log->type}\n";
            $content .= "Created At: {$log->created_at}\n";
            $content .= "Message: {$log->message}\n";
            $content .= "File: {$log->file}\n";
            $content .= "Line: {$log->line}\n";
            $content .= "Trace: {$log->trace}\n";
            $content .= str_repeat("=", 50) . "\n\n";
        }

        foreach ($logs as $log) {
            $content .= "SOURCE : table system_logs\n";
            $content .= "ID: {$log->id}\n";
            $content .= "Type: {$log->log_key}\n";
            $content .= "Created At: {$log->created_at}\n";
            $content .= "Message: {$log->message}\n";
            $content .= "File: {unknown}\n";
            $content .= "Line: {unknown}\n";
            $content .= "Trace: {unknown}\n";
            $content .= str_repeat("=", 50) . "\n\n";
        }

        // Simpan ke storage
        $fileName = 'system_errors_' . now()->format('Ymd_His') . '.txt';
        Storage::disk('local')->put($fileName, $content);
        $filePath = storage_path('app/' . $fileName);

        try {
            // Kirim email
            // Ambil value dari parameter_globals
            $parameterGlobal = \DB::table('m_parameter_globals')
                ->where('key', 'error_email_notify')
                ->first();

            if ($parameterGlobal && $parameterGlobal->value) {
                // Pisahkan dengan koma & trim spasi
                $emails = array_map('trim', explode(',', $parameterGlobal->value));

                Mail::raw(
                    stripcslashes($parameterGlobal->value_2),
                    function ($message) use ($filePath, $emails) {
                        $message->to($emails)
                            ->subject('System Errors - ' . now()->format('Y-m-d H:i'))
                            ->attach($filePath);
                    }
                );

                // Hapus data yang sudah diproses
                DB::table('system_errors')
                    ->whereIn('id', $system_error_ids)
                    ->delete();

                // Update data yang sudah diproses
                DB::table('system_logs')
                    ->whereIn('id', $log_ids)
                    ->update(['send_mail' => 1]);

                Log::channel('job_send_system_errors')->info(' ::key' . $logkey . ' => Email berhasil dikirim.');
            } else {
                Log::channel('job_send_system_errors')->info(' ::key' . $logkey . ' => Email penerima notifikasi tidak ditemukan di parameter_globals');
            }
        } catch (\Exception $e) {
            Log::channel('job_send_system_errors')->info(' ::key' . $logkey . ' => Gagal mengirim email: ' . $e->getMessage());
            Log::channel('job_send_system_errors')->info(' ::key' . $logkey . ' => Gagal mengirim email: ' . $e->getTraceAsString());
        }
        Log::channel('job_send_system_errors')->info(' ::key' . $logkey . ' => =======================end');

        // Hapus file biar gak numpuk
        Storage::disk('local')->delete($fileName);

        //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' => now()
            ]);

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