<?php

namespace App\Http\Controllers;

use App\Models\AppraisalPeriod;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AppraisalPeriodController extends Controller
{
    public function index(Request $request)
    {
        $periods = AppraisalPeriod::with('creator:id,surname,firstname')
            ->withCount('appraisals')
            ->orderByDesc('start_date')
            ->paginate(15);

        return Inertia::render('AppraisalPeriods/Index', [
            'periods' => $periods,
        ]);
    }

    public function create()
    {
        return Inertia::render('AppraisalPeriods/Form');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'description' => 'nullable|string',
            'status' => 'required|in:draft,active,closed',
        ]);

        // If activating, deactivate any current active period
        if ($validated['status'] === 'active') {
            AppraisalPeriod::where('status', 'active')->update(['status' => 'closed']);
        }

        $validated['created_by'] = $request->user()->id;

        AppraisalPeriod::create($validated);

        return redirect()->route('appraisal-periods.index')->with('success', 'Appraisal period created successfully.');
    }

    public function edit(AppraisalPeriod $appraisalPeriod)
    {
        return Inertia::render('AppraisalPeriods/Form', [
            'period' => $appraisalPeriod,
        ]);
    }

    public function update(Request $request, AppraisalPeriod $appraisalPeriod)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'description' => 'nullable|string',
            'status' => 'required|in:draft,active,closed',
        ]);

        if ($validated['status'] === 'active' && $appraisalPeriod->status !== 'active') {
            AppraisalPeriod::where('status', 'active')
                ->where('id', '!=', $appraisalPeriod->id)
                ->update(['status' => 'closed']);
        }

        $appraisalPeriod->update($validated);

        return redirect()->route('appraisal-periods.index')->with('success', 'Appraisal period updated successfully.');
    }

    public function destroy(AppraisalPeriod $appraisalPeriod)
    {
        if ($appraisalPeriod->appraisals()->count() > 0) {
            return back()->with('error', 'Cannot delete period with existing appraisals.');
        }

        $appraisalPeriod->delete();

        return redirect()->route('appraisal-periods.index')->with('success', 'Appraisal period deleted successfully.');
    }
}
