<?php

namespace App\Http\Controllers;

use App\Models\School_session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SchoolController extends Controller
{
    public function index()
    {
        $active_session = School_session::where('status', 'active')->first();
        $school_sessions = School_session::paginate(10);
        return view('schoolSession.session', compact('school_sessions', 'active_session'));
    }

    public function get_school_session_data($id)
    {
        $school_session = School_session::find($id);

        if (! $school_session) {
            return response()->json(['error' => 'Session not found'], 404);
        }

        return response()->json($school_session);
    }

    public function store(Request $request)
    {
        $request->validate([
            'session_year' => 'required|string|regex:/^\d{4}-\d{4}$/',
            'start_date'   => 'required|date',
            'end_date'     => 'required|date|after_or_equal:start_date',
            'status'       => 'required|in:active,inactive',
        ]);
        // Check if the session year already exists
        $existingSession = School_session::where('session_year', $request->session_year)->first();
        if ($existingSession) {
            return redirect()->back()->with('error', 'Session year already exists.');
        }

        if ($request->status === 'active') {
            School_session::where('status', 'active')->update(['status' => 'inactive']);
        }

        School_session::create($request->all());
        return redirect()->back()->with('success', 'School session created successfully.');
    }

    public function update(Request $request)
    {
        $request->validate([
            'id'           => 'required',
            'session_year' => 'required',
            'start_date'   => 'required|date',
            'end_date'     => 'required|date',
            'status'       => 'required|in:active,inactive',
        ]);

        $id      = $request->id;
        $session = School_session::find($id);

        if (! $session) {
            return redirect()->back()->with('error', 'Session not found.');
        }

        if ($request->status === 'active') {
            School_session::where('id', '!=', $id)
                ->where('status', 'active')
                ->update(['status' => 'inactive']);
        }

        $session->update([
            'session_year' => $request->session_year,
            'start_date'   => $request->start_date,
            'end_date'     => $request->end_date,
            'status'       => $request->status,
        ]);

        return redirect()->back()->with('success', 'Session updated successfully!');
    }

    public function delete($id)
    {
        DB::beginTransaction();

        try {
            $session = School_session::findOrFail($id);

            // ❌ Do not delete if it's the only session
            $totalSessions = School_session::count();
            if ($totalSessions <= 1) {
                return redirect()->back()->with('error', 'Cannot delete the only remaining session.');
            }

            $wasActive = $session->status === 'active';

            $session->delete();

            // ✅ If the deleted session was active, activate the most recent inactive one
            if ($wasActive) {
                $latestInactive = School_session::where('status', 'inactive')
                    ->orderBy('start_date', 'desc') // or use `created_at` if preferred
                    ->first();

                if ($latestInactive) {
                    $latestInactive->update(['status' => 'active']);
                }
            }

            DB::commit();

            return redirect()->back()->with('success', 'School Session deleted successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error deleting School Session: ' . $e->getMessage());

            return redirect()->back()->with('error', 'Failed to delete School Session. Please try again. Error: ' . $e->getMessage());
        }
    }
}
