<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\AttendanceRecord;
use App\Models\LeaveRequest;
use App\Models\SalaryAdvance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class EmployeeController extends Controller
{
    public function dashboard()
    {
        $user = Auth::user();
        $profile = $user->employeeProfile;

        $pendingLeaves = $user->leaveRequests()->where('status', 'PENDING')->get();
        $latestPayroll = $user->payrollRecords()->latest()->first();
        $todayAttendance = $user->attendanceRecords()->whereDate('date', today())->first();
        $recentReviews = $user->performanceReviews()->latest()->take(3)->get();

        return view('employee.dashboard', compact('user', 'profile', 'pendingLeaves', 'latestPayroll', 'todayAttendance', 'recentReviews'));
    }

    public function leaves()
    {
        $user = Auth::user();
        $leaves = $user->leaveRequests()->latest()->get();

        return view('employee.leaves.index', compact('leaves'));
    }

    public function requestLeave(Request $request)
    {
        $request->validate([
            'leave_type' => 'required',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'reason' => 'nullable|string',
        ]);

        $start = \Carbon\Carbon::parse($request->start_date);
        $end = \Carbon\Carbon::parse($request->end_date);
        $days = $start->diffInDays($end) + 1;

        $leave = new LeaveRequest([
            'leave_type' => $request->leave_type,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'total_days' => $days,
            'reason' => $request->reason,
            'status' => 'PENDING',
        ]);

        Auth::user()->leaveRequests()->save($leave);

        return redirect()->route('employee.leaves.index')->with('success', 'تم تقديم طلب الإجازة بنجاح.');
    }

    public function payroll()
    {
        $user = Auth::user();
        $payrolls = $user->payrollRecords()->latest()->get();

        return view('employee.payroll.index', compact('payrolls'));
    }

    // Attendance Self-Service
    public function attendance()
    {
        $user = Auth::user();
        $records = $user->attendanceRecords()->latest('date')->paginate(30);
        $todayRecord = $user->attendanceRecords()->whereDate('date', today())->first();

        // Single query instead of 3 separate COUNT queries
        $monthlyCounts = $user->attendanceRecords()
            ->whereMonth('date', now()->month)
            ->selectRaw('status, COUNT(*) as count')
            ->groupBy('status')
            ->pluck('count', 'status');

        $stats = [
            'present' => $monthlyCounts->get('PRESENT', 0),
            'absent' => $monthlyCounts->get('ABSENT', 0),
            'late' => $monthlyCounts->get('LATE', 0),
            'working_days' => now()->day,
        ];

        return view('employee.attendance.index', compact('records', 'todayRecord', 'stats'));
    }

    public function clockIn(Request $request)
    {
        $employee = Auth::user()->employee;
        if (! $employee) {
            return back()->with('error', 'لا يوجد ملف موظف مرتبط بهذا المستخدم.');
        }

        $existing = AttendanceRecord::where('employee_id', $employee->id)->whereDate('date', today())->first();
        if ($existing) {
            return back()->with('error', 'تم تسجيل الحضور مسبقاً اليوم.');
        }
        AttendanceRecord::create([
            'employee_id' => $employee->id,
            'date' => today(),
            'check_in' => now(),
            'status' => now()->hour > 9 ? 'LATE' : 'PRESENT',
        ]);

        return back()->with('success', 'تم تسجيل الحضور بنجاح.');
    }

    public function clockOut(Request $request)
    {
        $employee = Auth::user()->employee;
        if (! $employee) {
            return back()->with('error', 'لا يوجد ملف موظف مرتبط بهذا المستخدم.');
        }

        $record = AttendanceRecord::where('employee_id', $employee->id)->whereDate('date', today())->first();
        if (! $record || $record->check_out) {
            return back()->with('error', 'لا يمكن تسجيل الانصراف.');
        }
        $record->update(['check_out' => now()]);

        return back()->with('success', 'تم تسجيل الانصراف بنجاح.');
    }

    // Performance
    public function performance()
    {
        $user = Auth::user();
        $reviews = $user->performanceReviews()->with('reviewer')->latest('created_at')->paginate(10);
        $metrics = $user->performanceMetrics()->latest()->take(10)->get();

        return view('employee.performance.index', compact('reviews', 'metrics'));
    }

    // Training
    public function training()
    {
        $user = Auth::user();
        $records = $user->trainingRecords()->latest('start_date')->paginate(15);

        return view('employee.training.index', compact('records'));
    }

    // Salary Advance
    public function salaryAdvances()
    {
        $user = Auth::user();
        $advances = $user->salaryAdvances()->latest()->paginate(15);

        return view('employee.salary-advances.index', compact('advances'));
    }

    public function requestAdvance(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:100',
            'reason' => 'required|string|max:500',
        ]);

        $employee = Auth::user()->employee;
        if (! $employee) {
            return back()->with('error', 'لا يوجد ملف موظف مرتبط بهذا المستخدم.');
        }

        SalaryAdvance::create([
            'employee_id' => $employee->id,
            'requested_by' => Auth::id(),
            'amount' => $request->amount,
            'reason' => $request->reason,
            'status' => 'PENDING',
            'requested_at' => now(),
        ]);

        return back()->with('success', 'تم تقديم طلب السلفة بنجاح.');
    }
}
