<?php

namespace App\Console\Commands;

use App\Mail\ImportTransitMail;
use App\Models\AlertMailRule;
use App\Models\EmployeeMaster;
use App\Models\ImportTransit;
use App\Models\Plant;
use Filament\Facades\Filament;
use Illuminate\Console\Command;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ImportTransitReportExport;

class SendImportTransit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send-import-transit {schedule_type} {plant}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {

        $scheduleType = $this->argument('schedule_type');
        $plantId = (int) $this->argument('plant');

        $mailRules = AlertMailRule::where('module', 'ImportTransit')
            ->where('rule_name', 'ImportTransitMail')
            ->where('schedule_type', $scheduleType)
            ->where('plant', $plantId)
            ->get();

        $plants = ($plantId == 0)
            ? Plant::all()
            : Plant::where('id', $plantId)->get();

        $plantCodes = $plants->pluck('name', 'id');

        if ($plants->isEmpty()) {
            $this->error('No valid plant(s) found.');

            return;
        }

        $tableData = ImportTransit::where('status', '!=', 'Delivered')->orderByRaw("
            CASE
                WHEN cri_rfq_number ~ '[0-9]+'
                THEN CAST(regexp_replace(cri_rfq_number, '[^0-9]', '', 'g') AS INTEGER)
                ELSE NULL
            END NULLS LAST
        ")->get();


        if ($tableData->isEmpty()) {
            $this->info('No pending Import Transit records found. Mail skipped.');
            return;
        }

        if (strtolower($scheduleType) == 'daily')
        {
            foreach ($mailRules as $rule) {

            $mailSubject = 'Daily Import Transit Report';

            $fileName = 'reports/pending_import_shipment_' . now()->format('Ymd_His') . '.xlsx';

            Excel::store(
                new ImportTransitReportExport($tableData),
                $fileName,
                'local'
            );

            $updatedBy = $tableData->last()?->updated_by;

            $employee = EmployeeMaster::where('code', $updatedBy)
                ->select('name', 'mobile_number')
                ->first();

            $employeeName = $employee?->name;
            $mobileNumber = $employee?->mobile_number;

            $mail = new ImportTransitMail(
                $scheduleType,
                $tableData,
                $mailSubject,
                $fileName,
                $employeeName,
                $mobileNumber,
            );

            $toEmails = collect(explode(',', $rule->email))
                ->map(fn ($e) => trim($e))
                ->filter()
                ->unique()
                ->values()
                ->toArray();

            $ccEmails = collect(explode(',', $rule->cc_emails))
                ->map(fn ($e) => trim($e))
                ->filter()
                ->unique()
                ->values()
                ->toArray();

            if (empty($toEmails)) {
                $this->warn("Skipping rule {$rule->id} — no To emails.");
                continue;
            }

            \Mail::to($toEmails)
                ->cc($ccEmails)
                ->send($mail);

            $this->info("Mail sent → Rule {$rule->id} | To: " . implode(', ', $toEmails));

            }
        }
    }
}
