<?php

namespace App\Console\Commands;

use App\Mail\VehicleEntryMail;
use App\Models\AlertMailRule;
use App\Models\Plant;
use App\Models\VehicleEntry;
use Illuminate\Console\Command;
use Mail;

class SendVehicleReport extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:vehicle-report {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', 'VehicleReport')
            ->where('rule_name', 'VehicleReportMail')
            ->where('schedule_type', $scheduleType)
            ->get();

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

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

        if (strtolower($scheduleType) == 'daily') {
            $startDate = now()->subDay()->setTime(8, 0, 0);
            $endDate = now()->setTime(8, 0, 0);
        } else {
            $startDate = now()->setTime(8, 0, 0);
            $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
        }

        foreach ($plants as $plant) {

            $vehicleEntries = VehicleEntry::select([
                'vehicle_number',
                'boom_opened',
                'entry_time',
                'exit_time',
                'duration',
                'type',
            ])
            ->where('plant_id', $plant->id)
            ->whereBetween('entry_time', [$startDate, $endDate])
            ->get();

            if ($vehicleEntries->isEmpty()) {
                $this->warn("No records for {$plant->name}");
                continue;
            }

            $tableData = [];
            $no = 1;

            foreach ($vehicleEntries as $vehicleEntry) {
                $tableData[] = [
                    'no' => $no++,
                    'plant' => $plant->name,
                    'vehicleNumber' => strtoupper($vehicleEntry->vehicle_number),
                    'entryTime' => $vehicleEntry->entry_time,
                    'exitTime' => $vehicleEntry->exit_time,
                    'duration' => $vehicleEntry->duration,
                    'type' => $vehicleEntry->type,
                    'boom' => $vehicleEntry->boom_opened,
                ];
            }

            if ($plantId == 0) {
                $rule = $mailRules->first();
            } else {
                $rule = $mailRules->where('plant', $plant->id)->first();
            }

            if (!$rule) {
                $this->warn("No mail rule for {$plant->name}");
                continue;
            }

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

            $mail = new VehicleEntryMail(
                $scheduleType,
                $tableData,
                'Daily Vehicle Transit Report'
            );

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

            $this->info("Mail sent for {$plant->name}");
        }

    }


}
