<?php

namespace App\Http\Controllers;

use App\Models\CheckPointTime;
use App\Models\GuardName;
use App\Models\GuardPatrolEntry;
use App\Models\Plant;
use Carbon\Carbon;
use Illuminate\Http\Request;

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

    public function get_guardDay_hourlyData(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw   = env('API_AUTH_PW');
        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser . ':' . $expectedPw;

        if ("Bearer " . $expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!'
            ], 403);
        }

        $plantName       = $request->header('plant-name');
        $dateHeader      = $request->header('date');             // required: format Y-m-d
        $guardIdHeader   = $request->header('guard-name');       // required: guard_name_id
        $timeHeader      = $request->header('time-range');       // required: "08:00 - 10:00"

        if (!$plantName || !$dateHeader || !$guardIdHeader || !$timeHeader) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Missing one or more headers: plant-name, date, guard-name, time-range'
            ], 404);
        }

        $plant = Plant::where('name', $plantName)->first();
        if (!$plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant '{$plantName}' not found!"
            ], 404);
        }

        $selectedPlant = $plant->id;
        //$selectedDate = $dateHeader;
        $selectedDate = Carbon::createFromFormat('d-m-Y', $dateHeader)->format('Y-m-d');
        // $selectedGuardId = $guardIdHeader;
        $guard = GuardName::where('name', $guardIdHeader)->first();

        if (!$guard) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Guard '{$guardIdHeader}' not found!"
            ], 404);
        }

        $selectedGuardId = $guard->id;

        [$startTime, $endTime] = explode(' - ', $timeHeader);
        // $startFormatted = Carbon::parse("{$selectedDate} {$startTime}");
        // $endFormatted = Carbon::parse("{$selectedDate} {$endTime}");

        // $startDateTime = $startFormatted->format('H:i:s');
        // $endDateTime = $endFormatted->format('H:i:s');
        try
        {
            [$startTime, $endTime] = explode(' - ', $timeHeader);
            $startDateTime = Carbon::parse("{$selectedDate} {$startTime}");
            $endDateTime   = Carbon::parse("{$selectedDate} {$endTime}");
        }
        catch (\Exception $e) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid time-range format. Use HH:MM:SS - HH:MM:SS"
            ], 400);
        }

        $patrols = GuardPatrolEntry::where('plant_id', $selectedPlant)
            ->where('guard_name_id', $selectedGuardId)
            ->whereBetween('patrol_time', [$startDateTime, $endDateTime])
            ->orderBy('patrol_time')
            ->get();

        if ($patrols->count() < 2) {
            return response()->json([
                'status_code' => 'SUCCESS',
                'labels' => [],
                'datasets' => []
            ]);
        }

        $checkPointTimes = CheckPointTime::where('plant_id', $selectedPlant)
            ->orderBy('sequence_number')
            ->get(['sequence_number', 'min_cushioning', 'max_cushioning', 'check_point1_id', 'check_point2_id']);

        $expectedSequence = [];
        foreach ($checkPointTimes as $row) {
            $expectedSequence[] = $row->check_point1_id;
        }
        if ($checkPointTimes->isNotEmpty()) {
            $expectedSequence[] = $checkPointTimes->last()->check_point2_id;
        }

        $intervals = [];
        $labels = [];
        $currentSeqIndex = 0;

        for ($i = 0; $i < $patrols->count() - 1; $i++) {
            $current = Carbon::parse($patrols[$i]->patrol_time);
            $next = Carbon::parse($patrols[$i + 1]->patrol_time);
            $interval = round($next->floatDiffInRealSeconds($current, true) / 60, 2);

            $intervals[] = $interval;
            $labels[] = "Seq " . ($i + 1);
        }

        return response()->json([
            'status_code' => 'SUCCESS',
            'labels' => $labels,
            'datasets' => [
                [
                    'label' => 'Interval (minutes)',
                    'data' => array_map(fn($val) => $val ?: "", $intervals),
                ]
            ]
        ]);
    }


    /**
     * 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)
    {
        //
    }
}
