<?php

namespace App\Filament\Widgets;

use App\Models\GuardPatrolEntry;
use Carbon\Carbon;
use DB;
use Filament\Widgets\ChartWidget;
use Filament\Support\RawJs;

class GuardPatrolDayChart extends ChartWidget
{
    protected static ?string $heading = 'GuardPatrolDayChart';

     protected static ?string $maxHeight = '350px';

    protected int|string|array $columnSpan = 12;

     protected $listeners = ['patrolEntryChart'];

    protected function getData(): array
    {
        $selectedPlant = session('selected_plant');
        $activeFilter = $this->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;
        }

        $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();

        //dd($uniqueGuardNames);

        $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] = $totalSeconds / 60;
            //$guardTimeSums[$guardName] = round($totalSeconds / 60);
                $guardTimeSums[$guardName] = [
                'minutes' => round($totalSeconds / 60),
                'hours'   => round($totalSeconds / 3600, 1),
            ];

        }

        $chartData = [];
        foreach ($uniqueGuardNames as $guardName)
        {
            if ($activeFilter === 'today') {
                $chartData[] = $guardTimeSums[$guardName]['minutes'] ?? 0;
            }
            elseif ($activeFilter === '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);

         return [
        '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,
                ],
            ],
        ];

    }

    protected function getType(): string
    {
        return 'bar';
    }

    protected function getFilters(): ?array
    {
        return [
            'today' => 'Today',
            'yesterday' => 'Yesterday',
            'this_week'=> 'This Week',
            'this_month'=> 'This Month',
        ];
    }

    protected function getOptions(): array
    {
        return [
            'scales' => [
                'y' => [
                    'beginAtZero' => true, //Start Y-axis from 0
                    'ticks' => [
                        'stepSize' => 5,
                    ],
                ],
            ],
            'plugins' => [
                'datalabels' => [
                    'anchor' => 'start',
                    'align' => 'start',
                    'offset' => -15,
                    'color' => '#000',
                    'font' => [
                        'weight' => 'bold',
                    ],
                    'formatter' => RawJs::make('function(value) {
                        return value;
                    }'),
                ],
            ],
        ];
    }

}
