<?php

namespace App\Console\Commands;

use App\Mail\ImportTransitMail;
use App\Models\AlertMailRule;
use App\Models\ImportTransit;
use App\Models\Plant;
use Illuminate\Console\Command;

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;
        }

        // $todayRecordExists = ImportTransit::whereDate('created_at', now()->toDateString())->first();

        // if (!$todayRecordExists) {
        //     $this->info('No records created today. Mail not sent.');
        //     return;
        // }

        $tableData = ImportTransit::select([
                'cri_rfq_number',
                'mail_received_date',
                'pricol_ref_number',
                'requester',
                'shipper',
                'shipper_location',
                'shipper_invoice',
                'shipper_invoice_date',
                'customs_agent_name',
                'eta_date',
                'status',
                'delivery_location',
                'etd_date',
                'mode',
                'inco_terms',
                'port_of_loading',
                'port_of_discharge',
                'delivery_city',
                'packages',
                'type_of_package',
                'gross_weight',
                'volume',
                'bill_number',
                'bill_received_date',
                'vessel_number',
            ])
            ->where('status', '!=', 'Delivered')
            ->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';

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

            $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)
                );
            }

        }
    }
}
