<?php

namespace App\Filament\Employee\Widgets;

use App\Models\Attendance;
use App\Models\EarlyLeaveRequest;
use Carbon\Carbon;
use Filament\Widgets\Widget;

class MyEarlyLeaveRecommendationWidget extends Widget
{
    protected static string $view = 'filament.employee.widgets.my-early-leave-recommendation-widget';

    protected int|string|array $columnSpan = 'full';

    protected static ?int $sort = 1;

    public ?Attendance $attendance = null;
    public ?string $workEndTime = null;
    public ?int $earlyMinutes = null;
    public bool $hasEarlyLeaveRequest = false;

    public function mount(): void
    {
        $user = auth()->user();
        $company = $user->company;
        $today = Carbon::today();

        if (!$company || !$company->work_end_time) {
            return;
        }

        // Get today's attendance
        $attendance = Attendance::where('user_id', $user->id)
            ->whereDate('date', $today)
            ->whereNotNull('check_in_time')
            ->whereNotNull('check_out_time')
            ->first();

        if (!$attendance) {
            return;
        }

        // Check if user already has early leave request
        $hasEarlyLeaveRequest = EarlyLeaveRequest::where('user_id', $user->id)
            ->where('request_date', $today->toDateString())
            ->whereIn('status', ['pending', 'approved', 'used'])
            ->exists();

        if ($hasEarlyLeaveRequest) {
            return;
        }

        // Calculate if checkout is early
        $checkoutTime = Carbon::parse($attendance->check_out_time);
        $endTime = Carbon::parse($company->work_end_time->format('H:i'));

        $checkoutMinutes = $checkoutTime->hour * 60 + $checkoutTime->minute;
        $endMinutes = $endTime->hour * 60 + $endTime->minute;

        $earlyMinutes = $endMinutes - $checkoutMinutes;

        // Only show if checkout is more than 5 minutes early
        if ($earlyMinutes > 5) {
            $this->attendance = $attendance;
            $this->workEndTime = $company->work_end_time->format('H:i');
            $this->earlyMinutes = $earlyMinutes;
        }
    }

    public function shouldShow(): bool
    {
        return $this->attendance !== null && $this->earlyMinutes !== null && $this->earlyMinutes > 5;
    }

    public function getEarlyTimeFormatted(): string
    {
        if (!$this->earlyMinutes) {
            return '';
        }

        $hours = floor($this->earlyMinutes / 60);
        $minutes = $this->earlyMinutes % 60;

        if ($hours > 0) {
            return "{$hours} jam {$minutes} menit";
        }
        return "{$minutes} menit";
    }
}
