<?php

namespace App\Console\Commands;

use App\Mail\ProductionMail;
use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\ProductionPlan;
use App\Models\ProductionQuantity;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

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

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // ini_set('max_execution_time', 0); // disable limit
        // set_time_limit(0);

        $scheduleType = $this->argument('schedule_type');
        $plantId = (int) $this->argument('plant'); // cast to int for safety

        // Fetch mail rules based on schedule type
        $mailRules = \App\Models\AlertMailRule::where('module', 'ProductionQuantities')
            ->where('rule_name', 'ProductionMail')
            ->where('schedule_type', $scheduleType)
            ->where('plant', $plantId)
            ->get();

        $emails = $mailRules->pluck('email')->unique()->toArray();

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

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

            return;
        }

        // $startDate = now()->setTime(8, 0, 0);
        // $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
        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);
        }

        $PlanstartDate = now()->subDay()->setTime(8, 0, 0);
        $planendDate = now()->setTime(7, 59, 0);

        $tableData = [];
        $no = 1;

        // .

        // foreach ($plants as $plant) {
        //     $lines = Line::where('plant_id', $plant->id)->get();

        //     foreach ($lines as $line) {

        //             $month = $startDate->month;
        //             $year  = $startDate->year;

        //             $workingDays = ProductionPlan::where('plant_id', $plantId)
        //                 ->whereMonth('created_at', $month)
        //                 ->whereYear('created_at', $year)
        //                 ->value('working_days') ?? 0;

        //             $totalTargetQuantity = 0;

        //             $monthlyPlan  = ProductionPlan::where('plant_id', $plantId)
        //                 ->where('line_id', $line->id)
        //                 ->whereMonth('created_at', $month)
        //                 ->whereYear('created_at', $year)
        //                 ->sum('plan_quantity');  //  / $workingDays

        //             $dailyTarget = $workingDays > 0
        //                 ? $monthlyPlan / $workingDays
        //                 : 0;

        //             $dailyTarget = round($dailyTarget, 2);

        //             // $totalTargetQuantity = round($totalTargetQuantity, 2);

        //             $monthStart = $startDate->copy()->startOfMonth();
        //             $completedDays = $monthStart->diffInDays($startDate);

        //             $expectedTillYesterday = $dailyTarget * $completedDays;

        //         if (strtolower($line->type) == 'fg line') {
        //             $productionQuantity = \App\Models\QualityValidation::where('plant_id', $plant->id)
        //                 ->where('line_id', $line->id)
        //                 ->whereBetween('created_at', [$startDate, $endDate])
        //                 ->count();
        //         } else {
        //             $productionQuantity = ProductionQuantity::where('plant_id', $plant->id)
        //                 ->where('line_id', $line->id)
        //                 ->whereBetween('created_at', [$startDate, $endDate])
        //                 ->count();
        //         }

        //         $previousRemaining = max(0, $expectedTillYesterday - $productionQuantity);

        //         $totalTargetQuantity = round($dailyTarget + $previousRemaining, 2);

        //         $tableData[] = [
        //             'no' => $no++,
        //             'plant' => $plant->name,
        //             'line' => $line->name,
        //             'type' => $line->type,
        //             'targetQuantity' => $totalTargetQuantity,
        //             'productionQuantity' => $productionQuantity,
        //         ];
        //     }
        // }


        //..New Logic

        foreach ($plants as $plant) {

            $lines = Line::where('plant_id', $plant->id)->get();

            foreach ($lines as $line) {

                $month = $startDate->month;
                $year  = $startDate->year;

                $workingDays = ProductionPlan::where('plant_id', $plant->id)
                    ->where('line_id', $line->id)
                    ->whereMonth('created_at', $month)
                    ->whereYear('created_at', $year)
                    ->value('working_days') ?? 0;

                $monthlyPlan = ProductionPlan::where('plant_id', $plant->id)
                    ->where('line_id', $line->id)
                    ->whereMonth('created_at', $month)
                    ->whereYear('created_at', $year)
                    ->sum('plan_quantity');

                $dailyTarget = $workingDays > 0 ? $monthlyPlan / $workingDays : 0;

                $dailyTarget = round($dailyTarget, 2);

                $leaveDatesString = ProductionPlan::where('plant_id', $plant->id)
                    ->where('line_id', $line->id)
                    ->whereMonth('created_at', $month)
                    ->whereYear('created_at', $year)
                    ->value('leave_dates');

                $leaveDates = $leaveDatesString ? explode(',', $leaveDatesString) : [];

                $monthStart = $startDate->copy()->startOfMonth();
                $yesterday  = $startDate->copy()->subDay();

                $completedDays = 0;
                $currentDate = $monthStart->copy();

                while ($currentDate->lte($yesterday)) {

                    if (!in_array($currentDate->format('Y-m-d'), $leaveDates)) {
                        $completedDays++;
                    }

                    $currentDate->addDay();
                }

                $expectedTillYesterday = $dailyTarget * $completedDays;

                if (strtolower($line->type) == 'fg line') {

                    $producedTillYesterday = \App\Models\QualityValidation::where('plant_id', $plant->id)
                        ->where('line_id', $line->id)
                        ->whereMonth('created_at', $month)
                        ->whereYear('created_at', $year)
                        ->where('created_at', '<', $startDate)
                        ->count();

                } else {

                    $producedTillYesterday = ProductionQuantity::where('plant_id', $plant->id)
                        ->where('line_id', $line->id)
                        ->whereMonth('created_at', $month)
                        ->whereYear('created_at', $year)
                        ->where('created_at', '<', $startDate)
                        ->count();
                }

                $previousRemaining = max(0, $expectedTillYesterday - $producedTillYesterday);

                $totalTargetQuantity = round($dailyTarget + $previousRemaining, 2);

                $itemIds = ProductionPlan::where('plant_id', $plant->id)
                    ->where('line_id', $line->id)
                    ->whereMonth('created_at', $month)
                    ->whereYear('created_at', $year)
                    ->distinct()
                    ->pluck('item_id');

                $totalHourlyQuantity = Item::whereIn('id', $itemIds)
                    ->sum('hourly_quantity');

                $capacityQuan = $totalHourlyQuantity * 22.5;

                if (strtolower($line->type) == 'fg line') {

                    $productionQuantity = \App\Models\QualityValidation::where('plant_id', $plant->id)
                        ->where('line_id', $line->id)
                        ->whereBetween('created_at', [$startDate, $endDate])
                        ->count();

                } else {

                    $productionQuantity = ProductionQuantity::where('plant_id', $plant->id)
                        ->where('line_id', $line->id)
                        ->whereBetween('created_at', [$startDate, $endDate])
                        ->count();
                }

                if ($capacityQuan > 0) {
                    $efficiency = ($productionQuantity / $capacityQuan) * 100;
                } else {
                    $efficiency = 0;
                }

                $efficiency = round($efficiency, 2);

                $tableData[] = [
                    'no' => $no++,
                    'plant' => $plant->name,
                    'type' => $line->type,
                    'line' => $line->name,
                    'capacityQuantity' => floor($capacityQuan),
                    'targetQuantity' => floor($totalTargetQuantity),
                    'productionQuantity' => $productionQuantity,
                    'efficiency' => $efficiency . '%',
                ];
            }
        }

        // $service = new \App\Services\ProductionTargetService();

        // $year  = $startDate->year;
        // $month = $startDate->month;

        // [$records, $dates] = $service->generate(
        //     $plantId,
        //     $year,
        //     $month,
        // );

        $mail = new ProductionMail($scheduleType, $tableData);

        // $mail = new ProductionMail($scheduleType,$tableData,$records,$dates);

        $contentVars = $mail->content()->with;

        $this->info($contentVars['greeting'] ?? 'Production Report');
        $this->table(
            ['No', 'Plant', 'Line', 'Type', 'Capacity Quantity', 'Target Quantity', 'Production Quantity'],
            $tableData
        );
        $this->info($contentVars['wishes'] ?? '');

        // Send mails
        // if (! empty($emails)) {
        //     foreach ($emails as $email) {
        //         Mail::to($email)->send(new ProductionMail($scheduleType, $tableData));
        //     }
        //     $this->info('Production report sent to '.count($emails).' recipient(s).');
        // } else {
        //     $this->warn('No recipients found for ProductionMailAlert.');
        // }
        foreach ($mailRules as $rule)
        {
            $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 ID {$rule->id} — no valid To emails found.");

                continue;
            }

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

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