<?php

namespace App\Console\Commands;

use App\Models\AlertMailRule;
use App\Models\Line;
use App\Models\Plant;
use App\Models\ProductionQuantity;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

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

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // $webhookUrl1 = env('TEAM_URL_RANSAR_I');

        // $webhookUrl2 = env('TEAM_URL_RANSAR_II');

        $webhookUrls = [
            'Ransar Industries-I' => env('TEAM_URL_RANSAR_I'),
            'Ransar Industries-II' => env('TEAM_URL_RANSAR_II'),
        ];

        $start = Carbon::yesterday()->setHour(8)->setMinute(0)->setSecond(0);
        $end = Carbon::today()->setHour(7)->setMinute(59)->setSecond(59);

        foreach ($webhookUrls as $plantName => $webhookUrl)
        {

            $plant = Plant::where('name', $plantName)->first();
            $plantNa = $plant ? $plant->name : $plantName;

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

            $tableData = [];
            foreach ($lines as $line) {
                $count = ProductionQuantity::where('line_id', $line->id)
                    ->whereBetween('created_at', [$start, $end])
                    ->count();

                $tableData[] = [
                    'line_name' => $line->name ?? '',
                    'production_count' => $count ?? 0
                ];
            }

            $table = "| Line Name | Total Production Count |\n";
            $table .= "|------------|------------------------|\n";
            foreach ($tableData as $row) {
                $table .= "| {$row['line_name']} | {$row['production_count']} |\n";
            }

            $messageText = "**Daily Production Report - {$plantNa}**  \n"
                . "From: {$start->format('Y-m-d H:i:s')}  \n"
                . "To: {$end->format('Y-m-d H:i:s')}  \n\n"
                . $table;

            // Send message to Teams
            $response = Http::post($webhookUrl, ['text' => $messageText]);

            if ($response->successful()) {
                $this->info("Message sent successfully for {$plantNa}");
            } else {
                $this->error("Failed to send message for {$plantNa}");
            }
        }
    }
}
