<?php

namespace App\Http\Controllers;

use App\Models\AttendanceLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AttendanceController extends Controller
{
    public function index(Request $request): View
    {
        $month = $request->query('month', now()->format('Y-m'));
        $pin = $request->query('pin');

        [$year, $monthNumber] = array_pad(explode('-', $month), 2, null);
        $monthNumber = $monthNumber ?: now()->format('m');
        $year = $year ?: now()->format('Y');

        $startOfMonth = Carbon::createFromDate((int) $year, (int) $monthNumber, 1)->startOfDay();
        $endOfMonth = (clone $startOfMonth)->endOfMonth()->endOfDay();
        $daysInMonth = (int) $startOfMonth->daysInMonth;

        $query = AttendanceLog::query()
            ->with('employee')
            ->whereBetween('logged_at', [$startOfMonth, $endOfMonth]);

        if ($pin) {
            $query->where('pin', 'like', '%' . $pin . '%');
        }

        $logs = $query->orderBy('pin')
            ->orderBy('logged_at')
            ->get();

        $users = [];
        foreach ($logs as $log) {
            $pinKey = (string) $log->pin;
            if (! isset($users[$pinKey])) {
                $users[$pinKey] = [
                    'pin' => $log->pin,
                    'name' => $log->employee?->name ?? $log->employee_name ?? '-',
                    'days' => array_fill(1, $daysInMonth, [
                        'in' => false,
                        'out' => false,
                        'in_times' => [],
                        'out_times' => [],
                    ]),
                    'total_in' => 0,
                    'total_out' => 0,
                ];
            }

            $day = (int) $log->logged_at->format('j');
            if ($log->status === '0' || $log->status === 0) {
                if (! $users[$pinKey]['days'][$day]['in']) {
                    $users[$pinKey]['days'][$day]['in'] = true;
                    $users[$pinKey]['total_in']++;
                }
                $users[$pinKey]['days'][$day]['in_times'][] = $log->logged_at->format('H:i');
            }

            if ($log->status === '1' || $log->status === 1) {
                if (! $users[$pinKey]['days'][$day]['out']) {
                    $users[$pinKey]['days'][$day]['out'] = true;
                    $users[$pinKey]['total_out']++;
                }
                $users[$pinKey]['days'][$day]['out_times'][] = $log->logged_at->format('H:i');
            }
        }

        foreach ($users as $pinKey => $user) {
            for ($day = 1; $day <= $daysInMonth; $day++) {
                if (! empty($users[$pinKey]['days'][$day]['in_times'])) {
                    $users[$pinKey]['days'][$day]['in_times'] = [min($users[$pinKey]['days'][$day]['in_times'])];
                }
                if (! empty($users[$pinKey]['days'][$day]['out_times'])) {
                    $users[$pinKey]['days'][$day]['out_times'] = [max($users[$pinKey]['days'][$day]['out_times'])];
                }
            }
        }

        return view('attendance.index', [
            'users' => array_values($users),
            'month' => $startOfMonth->format('Y-m'),
            'daysInMonth' => $daysInMonth,
            'pin' => $pin,
        ]);
    }
}
