<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Services\AttendanceService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AttendanceApprovalController extends Controller
{
    public function __construct(protected AttendanceService $attendanceService) {}

    /**
     * Display pending attendance approvals for manager.
     */
    public function index(Request $request)
    {
        $user = $request->user();

        // Check if user is a manager
        if (! $user->isManager()) {
            abort(403, 'You are not authorized to access this page.');
        }

        $pendingApprovals = $this->attendanceService->getManagerPendingApprovals($user);

        return Inertia::render('Manager/Pages/Attendance/Approvals', [
            'approvals' => $pendingApprovals,
        ]);
    }

    /**
     * Approve attendance anomaly.
     */
    public function approve(Request $request, Attendance $attendance)
    {
        $user = $request->user();

        $success = $this->attendanceService->approveByManager($attendance, $user, true);

        if (! $success) {
            return back()->with('error', 'Unable to approve attendance.');
        }

        return back()->with('success', 'Attendance approved successfully.');
    }

    /**
     * Reject attendance anomaly.
     */
    public function reject(Request $request, Attendance $attendance)
    {
        $validated = $request->validate([
            'reason' => 'required|string|max:500',
        ]);

        $user = $request->user();

        $success = $this->attendanceService->approveByManager($attendance, $user, false, $validated['reason']);

        if (! $success) {
            return back()->with('error', 'Unable to reject attendance.');
        }

        return back()->with('success', 'Attendance rejected successfully.');
    }
}
