<?php

namespace App\Http\Controllers;

use App\Models\AttendanceRequest;
use App\Models\Attendance;
use App\Models\Employee;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class AttendanceRequestController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $query = Employee::query();
        if (!$user->hasRole('Admin')) {
            $subordinateIds = $user->employee ? $user->employee->subordinates->pluck('id') : collect([]);
            $query->whereIn('id', $subordinateIds);
        }
        $employees = $query->get();

        return view('attendance_requests.index', compact('employees'));
    }

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

    public function getData(Request $request)
    {
        $user = Auth::user();
        $query = AttendanceRequest::select('attendance_requests.*')->with('employee:id,name');

        // Mandatory Scoping for non-admins
        if (!$user->hasRole('Admin')) {
            $subordinateIds = $user->employee ? $user->employee->subordinates->pluck('id') : collect([]);
            $allowedIds = $subordinateIds->push($user->employee_id);
            $query->whereIn('employee_id', $allowedIds);
        }

        if ($request->has('mine')) {
            $query->where('employee_id', $user->employee_id);
        } elseif ($request->has('team')) {
            if ($user->hasRole('Admin')) {
                // Admin sees all pending requests except their own
                $query->where('employee_id', '!=', $user->employee_id)->where('status', 'pending');
            } else {
                // Manager sees their subordinates' pending requests
                $subordinateIds = $user->employee ? $user->employee->subordinates->pluck('id') : collect([]);
                $query->whereIn('employee_id', $subordinateIds)->where('status', 'pending');
            }
        }

        // Advanced Filters
        $query->when($request->start_date, function ($q) use ($request) {
            return $q->where('date', '>=', $request->start_date);
        })
        ->when($request->end_date, function ($q) use ($request) {
            return $q->where('date', '<=', $request->end_date);
        })
        ->when($request->employee_id, function ($q) use ($request) {
            return $q->where('employee_id', $request->employee_id);
        });

        return DataTables::of($query)
            ->addColumn('employee', function ($req) {
                return $req->employee->name ?? 'Unknown';
            })
            ->editColumn('status', function ($req) {
                $status = ucfirst($req->status);
                $badgeClass = 'bg-light-warning text-warning border-warning';
                if ($req->status == 'approved') $badgeClass = 'bg-light-success text-success border-success';
                if ($req->status == 'rejected') $badgeClass = 'bg-light-danger text-danger border-danger';
                
                return '<span class="badge ' . $badgeClass . ' border px-2 py-1" style="font-weight: 600;">' . $status . '</span>';
            })
            ->addColumn('action', function ($req) {
                if ($req->status == 'pending' && Auth::user()->employee_id != $req->employee_id && Auth::user()->canAccess('attendance.manage_requests')) {
                    return '<div class="d-flex gap-1 justify-content-center">
                            <button class="btn-crm-approve approve-request" data-id="' . $req->id . '" title="Approve"><i class="fas fa-check"></i></button>
                            <button class="btn-crm-reject reject-request" data-id="' . $req->id . '" title="Reject"><i class="fas fa-times"></i></button>
                            </div>';
                }
                
                $status = ucfirst($req->status);
                $badgeClass = 'bg-light-warning text-warning border-warning';
                if ($req->status == 'approved') $badgeClass = 'bg-light-success text-success border-success';
                if ($req->status == 'rejected') $badgeClass = 'bg-light-danger text-danger border-danger';
                
                return '<span class="badge ' . $badgeClass . ' border px-2 py-1" style="font-weight: 600;">' . $status . '</span>';
            })
            ->rawColumns(['status', 'action'])
            ->make(true);
    }

    public function store(Request $request)
    {
        $request->validate([
            'date' => 'required|date',
            'punch_in' => 'required',
            'punch_out' => 'required',
            'reason' => 'required',
        ]);

        AttendanceRequest::create([
            'employee_id' => Auth::user()->employee_id,
            'date' => $request->date,
            'punch_in' => $request->punch_in,
            'punch_out' => $request->punch_out,
            'reason' => $request->reason,
            'status' => 'pending',
        ]);

        if ($request->ajax()) {
            return response()->json(['success' => 'Attendance request submitted successfully.']);
        }

        return redirect()->route('attendance-requests.index')->with('success', 'Attendance request submitted successfully.');
    }

    public function approve(Request $request, $id)
    {
        $req = AttendanceRequest::findOrFail($id);
        
        // Authorization: Admin or Manager
        if (!Auth::user()->hasRole('Admin') && $req->employee->manager_id != Auth::user()->employee_id) {
            return response()->json(['error' => 'Unauthorized.'], 403);
        }

        $req->update([
            'status' => 'approved',
            'action_by' => Auth::user()->employee_id,
            'remarks' => $request->remarks
        ]);

        // Sync with Attendance table
        Attendance::updateOrCreate(
            ['employee_id' => $req->employee_id, 'date' => $req->date],
            ['punch_in' => $req->date . ' ' . $req->punch_in, 'punch_out' => $req->date . ' ' . $req->punch_out]
        );

        return response()->json(['success' => 'Request approved and attendance updated.']);
    }

    public function reject(Request $request, $id)
    {
        $req = AttendanceRequest::findOrFail($id);

        // Authorization: Admin or Manager
        if (!Auth::user()->hasRole('Admin') && $req->employee->manager_id != Auth::user()->employee_id) {
            return response()->json(['error' => 'Unauthorized.'], 403);
        }

        $req->update([
            'status' => 'rejected',
            'action_by' => Auth::user()->employee_id,
            'remarks' => $request->remarks
        ]);

        return response()->json(['success' => 'Request rejected.']);
    }
}
