<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Services\BusinessSettingService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AttendanceController extends Controller
{
    use AuthorizesRequests;

    public function __construct(protected BusinessSettingService $businessSettingService) {}

    public function index(Request $request)
    {
        $this->authorize('viewAny', Attendance::class);

        return redirect()->route('admin.attendance.index');
    }

    public function show(Attendance $attendance)
    {
        $this->authorize('view', $attendance);

        $attendance->load(['user.employeeProfile.departmentRel']);

        return Inertia::render('Admin/Attendance/Show', [
            'attendance' => $attendance,
        ]);
    }

    public function updateStatus(Request $request, Attendance $attendance)
    {
        $this->authorize('update', $attendance);

        $validated = $request->validate([
            'status' => 'required|in:approved,rejected,pending',
        ]);

        $attendance->update([
            'status' => $validated['status'],
            'approved_by' => auth()->id(),
        ]);

        return back()->with('success', __('Attendance status updated successfully.'));
    }

    public function settings()
    {
        $this->authorize('viewAny', Attendance::class);

        return Inertia::render('Admin/Attendance/Settings', [
            'settings' => $this->businessSettingService->getSettings([
                'manual_entry_enabled',
                'auto_approve_attendance',
                'monthly_attendance_goal',
                'shift_start_time',
                'shift_end_time',
            ]),
        ]);
    }

    public function updateSettings(Request $request)
    {
        $this->authorize('update', Attendance::class);

        $validated = $request->validate([
            'manual_entry_enabled' => 'nullable|boolean',
            'auto_approve_attendance' => 'nullable|boolean',
            'monthly_attendance_goal' => 'nullable|integer|min:1|max:744', // 744 hours = 31 days * 24 hours
            'shift_start_time' => 'nullable|date_format:H:i',
            'shift_end_time' => 'nullable|date_format:H:i|after:shift_start_time',
        ]);

        // Keep legacy key in sync for compatibility
        $values = $validated;
        if (isset($validated['manual_entry_enabled'])) {
            $values['manual_attendance_enabled'] = $validated['manual_entry_enabled'];
        }

        $this->businessSettingService->updateSettings($values);

        return back()->with('success', __('Attendance settings updated successfully.'));
    }
}
