<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PerformanceEvaluation;
use App\Models\EvaluationPeriod;
use App\Models\EvaluationCriteria;
use App\Models\EvaluationScore;
use App\Models\Employee;
use Illuminate\Support\Facades\DB;

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

    public function index(Request $request)
    {
        $user  = auth()->user();
        $query = PerformanceEvaluation::with(['employee.user','employee.department','period','evaluator']);

        // Role scoping
        if ($user->isEmployee()) {
            // Employees see only their own evaluations
            if ($emp = $user->employee) {
                $query->where('employee_id', $emp->id);
            } else {
                $query->whereRaw('1=0'); // no employee record → show nothing
            }
        } elseif ($user->isDeptHead()) {
            // Dept heads see evaluations for their department
            $query->whereHas('employee', fn($q) => $q->where('department_id', $user->department_id));
        }
        // HR / Admin / President see all

        if ($request->period_id) $query->where('period_id', $request->period_id);
        if ($request->status)    $query->where('status', $request->status);
        if ($request->rating)    $query->where('rating', $request->rating);

        $evaluations = $query->latest()->paginate(15)->withQueryString();

        // Summary counts (scoped to what the user can see)
        $countBase = PerformanceEvaluation::when($user->isEmployee() && $user->employee,
                fn($q) => $q->where('employee_id', $user->employee->id))
            ->when($user->isDeptHead(),
                fn($q) => $q->whereHas('employee', fn($e) => $e->where('department_id', $user->department_id)));

        $total     = (clone $countBase)->count();
        $pending   = (clone $countBase)->where('status', 'submitted')->count();
        $completed = (clone $countBase)->where('status', 'completed')->count();
        $avg_score = (clone $countBase)->whereNotNull('weighted_score')->avg('weighted_score');

        $periods  = EvaluationPeriod::orderByDesc('start_date')->get();

        return view('performance.index', compact('evaluations','total','pending','completed','avg_score','periods'));
    }

    public function create()
    {
        abort_if(auth()->user()->isEmployee(), 403);
        $employees = Employee::with('user')->where('status','active')->get();
        $periods   = EvaluationPeriod::where('status','active')->get();
        $criteria  = EvaluationCriteria::where('is_active',true)->orderBy('category')->get();
        return view('performance.create', compact('employees','periods','criteria'));
    }

    public function store(Request $request)
    {
        abort_if(auth()->user()->isEmployee(), 403);
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'period_id'   => 'required|exists:evaluation_periods,id',
            'scores'      => 'required|array',
        ]);

        DB::transaction(function () use ($request) {
            $criteria   = EvaluationCriteria::where('is_active',true)->get()->keyBy('id');
            $totalWeight = 0;
            $weightedSum = 0;

            $eval = PerformanceEvaluation::create([
                'employee_id'         => $request->employee_id,
                'period_id'           => $request->period_id,
                'evaluator_id'        => auth()->id(),
                'evaluator_comments'  => $request->evaluator_comments,
                'development_goals'   => $request->development_goals,
                'training_needs'      => $request->training_needs,
                'status'              => 'submitted',
            ]);

            foreach ($request->scores as $criterionId => $score) {
                $crit = $criteria[$criterionId] ?? null;
                if (!$crit) continue;
                $max    = $crit->max_score ?: 20;
                $weight = (float)($crit->weight ?: 1);
                $pct    = ($max > 0) ? ($score / $max) * 100 : 0;
                $weightedSum += $pct * $weight;
                $totalWeight += $weight;

                EvaluationScore::create([
                    'evaluation_id'   => $eval->id,
                    'criteria_id'    => $criterionId,
                    'score'           => $score,
                    'comments'      => $request->score_comments[$criterionId] ?? null,
                ]);
            }

            $overall = $totalWeight > 0 ? $weightedSum / $totalWeight : 0;
            $rating  = match(true) {
                $overall >= 90 => 'excellent',
                $overall >= 75 => 'very_good',
                $overall >= 60 => 'satisfactory',
                $overall >= 45 => 'needs_improvement',
                default        => 'unsatisfactory',
            };

            $eval->update(['weighted_score' => $overall, 'rating' => $rating]);
        });

        return redirect()->route('performance.index')->with('success','Evaluation submitted.');
    }

    public function show(PerformanceEvaluation $performance)
    {
        $user = auth()->user();

        // Employees can only see their own
        if ($user->isEmployee()) {
            abort_if($user->employee?->id !== $performance->employee_id, 403);
        }

        $performance->load(['employee.user','employee.department','period','evaluator','scores.criterion']);
        return view('performance.show', compact('performance'));
    }

    public function acknowledge(PerformanceEvaluation $performance)
    {
        // Only the evaluated employee can acknowledge
        abort_if(auth()->user()->employee?->id !== $performance->employee_id, 403);
        $performance->update(['status' => 'acknowledged', 'acknowledged_at' => now()]);
        return back()->with('success','Evaluation acknowledged.');
    }

    public function hrReview(PerformanceEvaluation $performance)
    {
        abort_if(!auth()->user()->isHrOrAdmin(), 403);
        $performance->update(['status' => 'completed', 'hr_reviewed_at' => now()]);
        return back()->with('success','HR review completed.');
    }
}
