<?php

namespace App\Http\Controllers;

use App\Models\Exam;
use App\Models\ExamTemplate;
use App\Models\Batch;
use App\Models\ExamSubjectRule;
use App\Models\ExamTemplateSubjectRule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ExamController extends Controller
{
    public function index(Request $request)
    {
        // If searching or filtering by specific attributes (other than basic page load), show list
        // OR if a specific batch is selected
        if ($request->has('batch_id') || $request->filled('search') || $request->filled('status')) {
            $query = Exam::with(['batch', 'examTemplate']);

            if ($request->filled('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%");
                });
            }

            if ($request->filled('batch_id')) {
                $query->where('batch_id', $request->batch_id);
            }

            if ($request->filled('status')) {
                $query->where('status', $request->status);
            }

            $exams = $query->latest()->paginate(15);
            $batches = Batch::where('is_active', true)->get();

            // Get current batch info if selected
            $currentBatch = null;
            if ($request->filled('batch_id')) {
                $currentBatch = Batch::find($request->batch_id);
            }

            return view('exams.index', compact('exams', 'batches', 'currentBatch'));
        }

        // Default Mode: Show Batch Folders
        $batches = Batch::withCount('exams')->orderBy('name', 'desc')->get();
        return view('exams.batches', compact('batches'));
    }

    public function create()
    {
        $batches = Batch::where('is_active', true)->get();
        $examTemplates = ExamTemplate::orderByDesc('created_at')->get(['id', 'name']);
        return view('exams.create', compact('batches', 'examTemplates'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'exam_template_id' => 'required|exists:exam_templates,id',
            'batch_id' => 'required|exists:batches,id',
            'class' => 'required|in:11,12', // Added class validation
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'status' => 'required|in:upcoming,open_for_entry,published,archived',
        ]);

        DB::transaction(function () use ($validated) {
            // Create exam
            $exam = Exam::create($validated);

            // Copy template rules to exam_subject_rules
            $templateRules = ExamTemplateSubjectRule::where('exam_template_id', $validated['exam_template_id'])->get();

            foreach ($templateRules as $rule) {
                ExamSubjectRule::create([
                    'exam_id' => $exam->id,
                    'subject_id' => $rule->subject_id,
                    'paper_mode' => $rule->paper_mode,
                    'config' => $rule->config ?? [],
                    'total_marks' => $rule->total_marks,
                    'pass_marks' => $rule->pass_marks,
                ]);
            }
        });

        return redirect()->route('exams.index')
            ->with('success', 'Exam created successfully with template rules applied!');
    }

    public function show(Exam $exam)
    {
        $exam->load(['batch', 'examTemplate', 'subjectRules.subject', 'marks', 'finalResults']);
        return view('exams.show', compact('exam'));
    }

    public function edit(Exam $exam)
    {
        $batches = Batch::where('is_active', true)->get();
        $examTemplates = ExamTemplate::orderByDesc('created_at')->get(['id', 'name']);
        $exam->load('subjectRules.subject');
        return view('exams.edit', compact('exam', 'batches', 'examTemplates'));
    }

    public function update(Request $request, Exam $exam)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'batch_id' => 'required|exists:batches,id',
            'class' => 'required|in:11,12',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'status' => 'required|in:upcoming,open_for_entry,published,archived',
        ]);

        $exam->update($validated);

        return redirect()->route('exams.index')
            ->with('success', 'Exam updated successfully!');
    }

    public function destroy(Exam $exam)
    {
        $exam->delete();

        return redirect()->route('exams.index')
            ->with('success', 'Exam deleted successfully!');
    }
}
