<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Models\Department;
use App\Models\Leave;
use App\Models\Training;
use App\Models\PerformanceEvaluation;
use App\Models\DisciplineRecord;
use App\Models\Announcement;
use App\Models\Attendance;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function __construct() { $this->middleware('auth'); }

    public function index()
    {
        $user = auth()->user();
        if ($user->isPresident() || $user->isSuperAdmin()) return $this->executiveDashboard();
        if ($user->isHrAdmin())  return $this->hrDashboard();
        if ($user->isDeptHead()) return $this->deptHeadDashboard();
        return $this->employeeDashboard();
    }

    private function executiveDashboard()
    {
        $total_employees     = Employee::where('status','active')->count();
        $total_departments   = Department::where('is_active',true)->count();
        $pending_leaves      = Leave::whereIn('status',['pending','dept_approved','hr_approved'])->count();
        $discipline_open     = DisciplineRecord::where('status','open')->count();
        $leaves_this_month   = Leave::whereMonth('created_at',now()->month)->whereYear('created_at',now()->year)->count();
        $trainings_scheduled = Training::whereIn('status',['scheduled','ongoing'])->count();
        $evaluations_pending = PerformanceEvaluation::where('status','submitted')->count();
        $monthly_payroll_usd = Employee::where('status','active')->sum('salary_usd');

        $dept_headcount = Department::withCount(['employees as active_count'=>fn($q)=>$q->where('status','active')])->having('active_count','>',0)->orderByDesc('active_count')->get();
        $pending_approvals = Leave::where('status','hr_approved')->with(['employee.user','employee.department','leaveType'])->latest()->take(5)->get();
        $announcements = Announcement::where('is_published',true)->where('publish_date','<=',today())->latest('publish_date')->take(6)->get();

        $leave_trend = collect();
        for ($i=5;$i>=0;$i--) {
            $m = now()->subMonths($i);
            $leave_trend->push(['month'=>$m->format('M'),'count'=>Leave::whereYear('created_at',$m->year)->whereMonth('created_at',$m->month)->count(),'approved'=>Leave::whereYear('created_at',$m->year)->whereMonth('created_at',$m->month)->where('status','approved')->count()]);
        }
        $employment_types = Employee::where('status','active')->groupBy('employment_type')->selectRaw('employment_type,count(*) as count')->pluck('count','employment_type');

        return view('dashboard.executive',compact('total_employees','total_departments','pending_leaves','monthly_payroll_usd','discipline_open','leaves_this_month','trainings_scheduled','evaluations_pending','dept_headcount','pending_approvals','announcements','leave_trend','employment_types'));
    }

    private function hrDashboard()
    {
        $total_employees     = Employee::where('status','active')->count();
        $pending_leaves      = Leave::where('status','dept_approved')->count();
        $discipline_open     = DisciplineRecord::where('status','open')->count();
        $evaluations_pending = PerformanceEvaluation::where('status','submitted')->count();
        $pending_approvals   = Leave::where('status','dept_approved')->with(['employee.user','leaveType'])->latest()->take(6)->get();
        $new_employees       = Employee::whereMonth('date_of_employment',now()->month)->whereYear('date_of_employment',now()->year)->with(['user','department'])->latest('date_of_employment')->get();
        $dept_summary        = Department::withCount(['employees as active_count'=>fn($q)=>$q->where('status','active'),'employees as on_leave_count'=>fn($q)=>$q->where('status','on_leave')])->where('is_active',true)->get();
        return view('dashboard.hr',compact('total_employees','pending_leaves','discipline_open','evaluations_pending','pending_approvals','new_employees','dept_summary'));
    }

    private function deptHeadDashboard()
    {
        $deptId = auth()->user()->getDepartmentIdAttribute();
        $total_employees   = Employee::where('department_id',$deptId)->where('status','active')->count();
        $pending_leaves    = Leave::where('status','pending')->whereHas('employee',fn($q)=>$q->where('department_id',$deptId))->count();
        $discipline_open   = DisciplineRecord::where('status','open')->whereHas('employee',fn($q)=>$q->where('department_id',$deptId))->count();
        $evaluations_pending=0;
        $pending_approvals = Leave::where('status','pending')->whereHas('employee',fn($q)=>$q->where('department_id',$deptId))->with(['employee.user','leaveType'])->latest()->take(5)->get();
        $new_employees     = collect();
        $dept_summary      = collect();
        return view('dashboard.hr',compact('total_employees','pending_leaves','discipline_open','evaluations_pending','pending_approvals','new_employees','dept_summary'));
    }

    private function employeeDashboard()
    {
        $user = auth()->user();
        $employee = $user->employee;
        if (!$employee) return view('dashboard.employee',['setup_required'=>true]);

        $pending_leaves    = Leave::where('employee_id',$employee->id)->whereIn('status',['pending','dept_approved','hr_approved'])->count();
        $discipline_active = DisciplineRecord::where('employee_id',$employee->id)->where('status','open')->count();
        $attendance_summary = [
            'present' =>Attendance::where('employee_id',$employee->id)->whereYear('date',now()->year)->whereMonth('date',now()->month)->where('status','present')->count(),
            'absent'  =>Attendance::where('employee_id',$employee->id)->whereYear('date',now()->year)->whereMonth('date',now()->month)->where('status','absent')->count(),
            'late'    =>Attendance::where('employee_id',$employee->id)->whereYear('date',now()->year)->whereMonth('date',now()->month)->where('status','late')->count(),
            'on_leave'=>Attendance::where('employee_id',$employee->id)->whereYear('date',now()->year)->whereMonth('date',now()->month)->where('status','on_leave')->count(),
        ];
        $leave_balances      = $employee->leaveBalances()->with('leaveType')->get();
        $latest_evaluation   = PerformanceEvaluation::where('employee_id',$employee->id)->with('period')->latest()->first();
        $upcoming_trainings  = Training::whereIn('status',['scheduled','ongoing'])->latest('start_date')->take(4)->get();
        $recent_leaves       = Leave::where('employee_id',$employee->id)->with('leaveType')->latest()->take(5)->get();

        return view('dashboard.employee',compact('employee','pending_leaves','discipline_active','attendance_summary','leave_balances','latest_evaluation','upcoming_trainings','recent_leaves'));
    }
}
