<?php

namespace App\Http\Controllers;

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

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

    public function get_guardDay_countData(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');
        $filterHeader    = $request->header('filter-name');

        if (empty($plantName) || empty($filterHeader)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Missing required headers: plant-name, or filter-name"
            ], 404);
        }

        $validFilters = ['Today', 'Yesterday', 'This Week', 'This Month'];
        if (!in_array($filterHeader, $validFilters)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid filter-name value! Accepted values are: " . implode(', ', $validFilters)
            ], 404);
        }

        // $selectedPlant = $plant->id;
        // $activeFilter = strtolower(trim($filterHeader));

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

        $selectedPlant = $plant->id;
        $activeFilter  = strtolower(trim($filterHeader));

        // Set date range based on filter
        switch ($activeFilter) {
            case 'yesterday':
                $startDate = now()->subDay()->startOfDay();
                $endDate   = now()->subDay()->endOfDay();
                break;
            case 'this week':
                $startDate = now()->startOfWeek();
                $endDate   = now()->endOfWeek();
                break;
            case 'this month':
                $startDate = now()->startOfMonth();
                $endDate   = now()->endOfMonth();
                break;
            default: // today
                $startDate = now()->startOfDay();
                $endDate   = now()->endOfDay();
                break;
        }

        // Get all unique guard names for this plant
        $uniqueGuardNames = GuardPatrolEntry::join('guard_names', 'guard_patrol_entries.guard_name_id', '=', 'guard_names.id')
            ->where('guard_patrol_entries.plant_id', $selectedPlant)
            ->select('guard_names.id', 'guard_names.name')
            ->groupBy('guard_names.id', 'guard_names.name')
            ->orderBy('guard_names.name')
            ->pluck('name')
            ->toArray();

        // Get all patrol entries within the date range, grouped by guard name
        $guardPatrols = GuardPatrolEntry::join('guard_names', 'guard_patrol_entries.guard_name_id', '=', 'guard_names.id')
            ->where('guard_patrol_entries.plant_id', $selectedPlant)
            ->whereBetween('guard_patrol_entries.patrol_time', [$startDate, $endDate])
            ->select('guard_names.id', 'guard_names.name', 'guard_patrol_entries.patrol_time')
            ->orderBy('guard_names.name')
            ->orderBy('guard_patrol_entries.patrol_time')
            ->get()
            ->groupBy('name');

        $guardTimeSums = [];

        foreach ($guardPatrols as $guardName => $patrols) {
            $totalSeconds = 0;
            $prevTime = null;

            foreach ($patrols as $patrol) {
                $currentTime = Carbon::parse($patrol->patrol_time);
                if ($prevTime) {
                    $totalSeconds += abs($currentTime->diffInSeconds($prevTime));
                }
                $prevTime = $currentTime;
            }

            $guardTimeSums[$guardName] = [
                'minutes' => round($totalSeconds / 60),
                'hours'   => round($totalSeconds / 3600, 1),
            ];
        }

        // Prepare chart data
        $chartData = [];
        foreach ($uniqueGuardNames as $guardName) {
            if (in_array($activeFilter, ['today', 'yesterday'])) {
                $chartData[] = $guardTimeSums[$guardName]['minutes'] ?? 0;
            } else {
                $chartData[] = $guardTimeSums[$guardName]['hours'] ?? 0;
            }
        }

        // $chartData = array_map(function ($value) {
        //     return ($value == 0 || is_null($value)) ? null : $value;
        // }, $chartData);

        $chartData = array_map(function ($value) {
            return ($value == 0 || is_null($value)) ? "" : $value;
        }, $chartData);

        return response()->json([
            'status_code' => 'SUCCESS',
            'labels' => array_values($uniqueGuardNames),
            'datasets' => [
                [
                    'label' => match ($activeFilter) {
                        'yesterday'   => "Patrols by Guard (Yesterday) Minutes",
                        'this week'   => "Patrols by Guard (This Week) Hours",
                        'this month'  => "Patrols by Guard (This Month) Hours",
                        default       => "Patrols by Guard (Today) Minutes",
                    },
                    'data' => $chartData,
                ],
            ],
        ]);
    }

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