<?php
// app/Http/Controllers/Admin/ExamController.php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Exam;
use App\Models\Subject;
use App\Models\School;
use Illuminate\Http\Request;

class ExamController extends Controller
{
    public function index(Request $request)
    {
        $filters = [
            'q'          => trim((string)$request->get('q','')),
            'subject_id' => $request->get('subject_id'),
            'school_id'  => $request->get('school_id'),
            'grade'      => trim((string)$request->get('grade','')),
            'lang'       => $request->get('lang'),
            'year'       => $request->get('year'),
            'active'     => $request->get('active'), // '', '1', '0'
        ];

        $q = Exam::with(['subject','school'])->orderByDesc('created_at');

        if ($filters['q'] !== '') {
            $needle = '%'.mb_strtolower($filters['q']).'%';
            $q->whereRaw('LOWER(title) LIKE ?', [$needle]);
        }
        if ($filters['subject_id']) $q->where('subject_id', (int)$filters['subject_id']);
        if ($filters['school_id'])  $q->where('school_id',  (int)$filters['school_id']);
        if ($filters['grade'] !== '') $q->where('grade', $filters['grade']);
        if ($filters['lang']) $q->where('question_language', $filters['lang']);
        if ($filters['year']) $q->where('year', (int)$filters['year']);
        if ($filters['active'] !== null && $filters['active'] !== '') $q->where('is_active', (bool)$filters['active']);

        $exams = $q->paginate(20)->appends($filters);

        $subjects = Subject::orderBy('name')->get(['id','name']);
        $schools  = School::orderBy('name')->get(['id','name']);
        $years    = Exam::select('year')->whereNotNull('year')->distinct()->orderByDesc('year')->pluck('year');

        return view('admin.exams.index', compact('exams','filters','subjects','schools','years'));
    }

    // JSON for Edit modal
    public function show(Exam $exam)
    {
        return response()->json([
            'id'                 => $exam->id,
            'title'              => $exam->title,
            'subject_id'         => $exam->subject_id,
            'question_language'  => $exam->question_language,
            'grade'              => $exam->grade,
            'year'               => $exam->year,
            'school_id'          => $exam->school_id,
            'exam_date'          => optional($exam->exam_date)->format('Y-m-d'),
            'type'               => $exam->type,
            'num_questions'      => $exam->num_questions,
            'is_active'          => (bool)$exam->is_active,
        ]);
    }

    public function store(Request $request)
    {
        $data = $this->validated($request);
        Exam::create($data);
        return back()->with('status', __('app.admin.exams.flash.created'));
    }

    public function update(Request $request, Exam $exam)
    {
        $data = $this->validated($request, $exam);
        $exam->update($data);
        return back()->with('status', __('app.admin.exams.flash.updated'));
    }

    public function destroy(Exam $exam)
    {
        if ($exam->attempts()->exists()) {
            return back()->withErrors(['delete' => __('app.admin.exams.errors.has_attempts')]);
        }
        $exam->delete();
        return back()->with('status', __('app.admin.exams.flash.deleted'));
    }

    private function validated(Request $request, ?Exam $existing=null): array
    {
        return $request->validate([
            'title'             => ['required','string','max:255'],
            'subject_id'        => ['required','integer','exists:subjects,id'],
            'question_language' => ['required','in:en,ar'],
            'grade'             => ['nullable','string','max:50'],
            'year'              => ['nullable','integer','min:2000','max:2100'],
            'school_id'         => ['required','integer','exists:schools,id'],
            'exam_date'         => ['nullable','date'],
            'type'              => ['nullable','string','max:100'],
            'num_questions'     => ['required','integer','in:15,30,45,60'],
            'is_active'         => ['required','boolean'],
        ]);
    }
}
