<?php

namespace App\Http\Controllers;

use App\Models\AlertMailRule;
use App\Models\Line;
use App\Models\ProductionQuantity;
use Illuminate\Http\Request;
use Telegram\Bot\Laravel\Facades\Telegram;
use Telegram\Bot\Api;
use Illuminate\Support\Facades\Http;
use Illuminate\Console\Scheduling\Schedule;
use Carbon\Carbon;
use Illuminate\Console\View\Components\Alert;

class TelegramController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }


    public function sendMessage(Request $request)
    {

        $webhookUrl = env('TEAM_URL');

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

        $ruleExists = AlertMailRule::where('module', 'ProductionQuantities')
        ->where('rule_name', 'ProductionMail')
        ->where('schedule_type', 'Daily')
        ->first();

        if (!$ruleExists) {
            return response()->json([
                'status' => 'Skipped',
                'message' => 'No matching alert rule found for ProductionQuantities → ProductionMail → Daily.'
            ]);
        }

        $plantName = 1;

        $lines = Line::where('plant_id', $plantName)->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 ?? ''
            ];
        }


        $table = "| Line Name | Total Production Count |\n";
        $table .= "|------------|------------------------|\n";

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

        //     $table .= "| {$line} | {$count} |\n";
        // }

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

        $message = [
            "text" => $messageText
        ];

        $response = Http::post($webhookUrl, $message);

        // if ($response->successful()) {
        //     return response()->json(['status' => 'Message sent to Teams!']);
        // }

        return response()->json([
            'status' => $response->successful() ? 'Message sent to Teams!' : 'Failed to send message to Teams',
            'plant' => $plantName,
            'start_time' => $start->format('Y-m-d H:i:s'),
            'end_time' => $end->format('Y-m-d H:i:s'),
            'lines' => $tableData,
            'teams_message_preview' => $messageText,
        ]);

        //return response()->json(['error' => 'Failed to send message'], 500);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
