<?php

namespace App\Http\Controllers;

use App\Models\LeaveRequest;
use App\Models\LeaveType;
use App\Models\Attendance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class LeaveRequestController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();
        $query = LeaveRequest::with(['user', 'leaveType']);

        if (!$user->hasRole('Admin')) {
            $query->where('user_id', $user->id);
        }

        $leaveRequests = $query->orderBy('created_at', 'desc')->paginate(10);
        
        if (request()->wantsJson()) {
            return response()->json($leaveRequests);
        }
        
        return view('leaves.requests.index', compact('leaveRequests'));
    }

    public function create()
    {
        return view('leaves.requests.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'reason' => 'required|string',
            'is_half_day' => 'boolean',
        ]);

        $leaveRequest = LeaveRequest::create([
            'user_id' => Auth::id(),
            'start_date' => $validated['start_date'],
            'end_date' => $validated['end_date'],
            'reason' => $validated['reason'],
            'is_half_day' => $validated['is_half_day'] ?? false,
            'status' => 'pending',
        ]);
        
        if (request()->wantsJson()) {
            return response()->json($leaveRequest, 201);
        }
        
        return redirect()->route('leaves.requests.index')->with('success', 'Leave request submitted successfully.');
    }

    public function update(Request $request, LeaveRequest $leaveRequest)
    {
        // Check if this is a status update or just an edit
        if ($request->has('status')) {
            return $this->updateStatus($request, $leaveRequest);
        }
        
        // Regular update logic if needed (e.g. employee editing pending request)
        // For now, redirect back
        return back();
    }

    public function updateStatus(Request $request, LeaveRequest $leaveRequest)
    {
        if (!Auth::user()->hasRole('Admin')) {
             if ($request->wantsJson()) {
                 return response()->json(['message' => 'Unauthorized'], 403);
             }
             abort(403);
        }

        $validated = $request->validate([
            'status' => 'required|in:approved,rejected',
            'leave_type_id' => 'required_if:status,approved|exists:leave_types,id',
            'admin_comment' => 'nullable|string',
        ]);

        DB::transaction(function () use ($leaveRequest, $validated) {
            $leaveRequest->status = $validated['status'];
            $leaveRequest->admin_comment = $validated['admin_comment'] ?? null;
            
            if ($validated['status'] === 'approved') {
                $leaveRequest->leave_type_id = $validated['leave_type_id'];
                
                $leaveType = LeaveType::find($validated['leave_type_id']);
                
                // If it is a fully paid leave (0 deduction), it consumes the quota
                if ($leaveType->deduction_percentage == 0) {
                    $staffProfile = $leaveRequest->user->staffProfile;
                    if ($staffProfile) {
                        $days = $leaveRequest->is_half_day ? 0.5 : 
                                Attendance::getWorkingDaysBetween($leaveRequest->start_date, $leaveRequest->end_date);
                        
                        $staffProfile->used_paid_leaves += $days;
                        $staffProfile->save();
                    }
                }
            }
            
            $leaveRequest->save();
        });
        
        if ($request->wantsJson()) {
            return response()->json($leaveRequest->load('leaveType'));
        }
        
        return redirect()->route('leaves.requests.index')->with('success', 'Leave request updated successfully.');
    }
}
