<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ManagementYear;
use Illuminate\Http\Request;

class ManagementYearController extends Controller
{
    public function create()
    {
        return view('admin.management-years.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'year' => 'required|integer|unique:management_years,year|min:2000|max:2099',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'status' => 'required|in:actif,inactif,cloture',
            'description' => 'nullable|string'
        ]);

        if ($validated['status'] === 'actif') {
            // Désactiver les autres années si celle-ci est active
            ManagementYear::where('status', 'actif')->update(['status' => 'inactif']);
        }

        ManagementYear::create($validated);

        return redirect()->route('admin.settings.index')->with('success', 'Année de gestion ajoutée avec succès.')->with('tab', 'years');
    }

    public function edit(ManagementYear $managementYear)
    {
        return view('admin.management-years.edit', compact('managementYear'));
    }

    public function update(Request $request, ManagementYear $managementYear)
    {
        $validated = $request->validate([
            'year' => 'required|integer|min:2000|max:2099|unique:management_years,year,' . $managementYear->id,
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'status' => 'required|in:actif,inactif,cloture',
            'description' => 'nullable|string'
        ]);

        if ($validated['status'] === 'actif' && $managementYear->status !== 'actif') {
            // Désactiver les autres années si on active celle-ci
            ManagementYear::where('id', '!=', $managementYear->id)
                ->where('status', 'actif')
                ->update(['status' => 'inactif']);
        }

        $managementYear->update($validated);

        // Redirect back to settings page with years tab active
        return redirect()->route('admin.settings.index')->with('success', 'Année de gestion mise à jour avec succès.')->with('tab', 'years');
    }

    public function destroy(ManagementYear $managementYear)
    {
        $managementYear->delete();
        return back()->with('success', 'Année de gestion supprimée avec succès.')->with('tab', 'years');
    }
}
