<?php

namespace App\Http\Controllers;

use App\ExamNotice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

    /**
     * Display the exam notices management interface.
     */
    public function index()
    {
        if (!Auth::user()->hasAnyRole(['super-admin', 'admin', 'Super Admin', 'Admin'])) {
            abort(403, 'Unauthorized action.');
        }

        $notices = ExamNotice::orderBy('id', 'desc')->get();
        $activeNotice = ExamNotice::getActiveNotice();

        return view('admin.pages.exam_notices', compact('notices', 'activeNotice'));
    }

    /**
     * Store or update an exam notice record.
     */
    public function store(Request $request)
    {
        if (!Auth::user()->hasAnyRole(['super-admin', 'admin', 'Super Admin', 'Admin'])) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'semester_title' => 'required|string|max:255',
            'auth_title' => 'nullable|string|max:255',
            'auth_instructions' => 'nullable|string',
            'regulations_title' => 'nullable|string|max:255',
            'regulations_content' => 'nullable|string',
        ]);

        if ($request->has('is_active') && $request->is_active == 1) {
            ExamNotice::query()->update(['is_active' => 0]);
        }

        if ($request->filled('id')) {
            $notice = ExamNotice::findOrFail($request->id);
            $notice->update([
                'semester_title' => $request->semester_title,
                'auth_title' => $request->auth_title ?? 'Authentication Requirements',
                'auth_instructions' => $request->auth_instructions,
                'regulations_title' => $request->regulations_title ?? 'Important Regulations & Deadlines',
                'regulations_content' => $request->regulations_content,
                'is_active' => $request->has('is_active') ? 1 : $notice->is_active,
            ]);
            $msg = 'Examination notice record updated successfully.';
        } else {
            // Set active if requested or if it's the first
            $isActive = $request->has('is_active') || ExamNotice::count() == 0 ? 1 : 0;
            if ($isActive) {
                ExamNotice::query()->update(['is_active' => 0]);
            }

            ExamNotice::create([
                'semester_title' => $request->semester_title,
                'auth_title' => $request->auth_title ?? 'Authentication Requirements',
                'auth_instructions' => $request->auth_instructions,
                'regulations_title' => $request->regulations_title ?? 'Important Regulations & Deadlines',
                'regulations_content' => $request->regulations_content,
                'is_active' => $isActive,
            ]);
            $msg = 'New examination notice record published successfully.';
        }

        return redirect()->route('admin.exam-notices.index')->with('success', $msg);
    }

    /**
     * Activate a specific notice record.
     */
    public function activate($id)
    {
        if (!Auth::user()->hasAnyRole(['super-admin', 'admin', 'Super Admin', 'Admin'])) {
            abort(403, 'Unauthorized action.');
        }

        ExamNotice::query()->update(['is_active' => 0]);
        $notice = ExamNotice::findOrFail($id);
        $notice->update(['is_active' => 1]);

        return redirect()->route('admin.exam-notices.index')->with('success', "Notice '{$notice->semester_title}' is now active on the portal login page.");
    }

    /**
     * Delete a notice record.
     */
    public function destroy($id)
    {
        if (!Auth::user()->hasAnyRole(['super-admin', 'admin', 'Super Admin', 'Admin'])) {
            abort(403, 'Unauthorized action.');
        }

        $notice = ExamNotice::findOrFail($id);
        $notice->delete();

        // Ensure at least one active notice exists
        if (ExamNotice::where('is_active', 1)->count() == 0) {
            $latest = ExamNotice::latest()->first();
            if ($latest) {
                $latest->update(['is_active' => 1]);
            }
        }

        return redirect()->route('admin.exam-notices.index')->with('success', 'Examination notice deleted.');
    }
}
