<?php

namespace App\Http\Controllers\Academic;

use App\Http\Controllers\Controller;
use App\Models\Academic\AcademicYear;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AcademicYearController extends Controller
{
    public function index()
    {
        $academicYears = AcademicYear::all();
        return view('pages.academic.academic_year.index', compact('academicYears'));
    }

    public function store(Request $request){
        $request->validate([
            'year' => 'required|string|max:255|unique:academic_years,year',
        ]);
        $academicYear = AcademicYear::create([
            'year' => $request->year,
            'is_default_year' => $request->is_default_year,
            'status' => $request->status,
            'created_by' => auth()->id()
        ]);

        if($request->is_default_year=='yes'){
            AcademicYear::where('id', '!=', $academicYear->id)->update([
                'is_default_year' => 'no',
            ]);
        }

        Cache::forget('default_academic_year');

        return redirect()->route('academic-years.index')->with('success', 'Academic year created successfully.');
    }

    public function update(Request $request)
    {
        $request->validate([
            'year' => 'required|string|max:255|unique:academic_years,year,' . $request->id,
        ]);

        AcademicYear::where('id',$request->id)->update([
            'year' => $request->year,
            'is_default_year' => $request->is_default_year,
            'status' => $request->status,
            'updated_by' => auth()->id(),
        ]);

        if($request->is_default_year=='yes'){
            AcademicYear::where('id', '!=', $request->id)->update([
                'is_default_year' => 'no',
            ]);
        }
        Cache::forget('default_academic_year');
        return redirect()->route('academic-years.index')->with('success', 'Academic year updated successfully.');
    }

    public function destroy(AcademicYear $academicYear)
    {
        $academicYear->delete();

        return redirect()->route('academic-years.index')->with('success', 'Academic year deleted successfully.');
    }
}
