<?php
namespace BranchAdmin\Controllers;

use BranchAdmin\Controllers\BranchBaseController;

class BranchExamController extends BranchBaseController
{
    public function index(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();

        $courseFilter = sanitize($_GET['course_id'] ?? '');
        $statusFilter = sanitize($_GET['status'] ?? '');

        $sql = "SELECT e.*, c.name as course_name FROM exams e LEFT JOIN courses c ON e.course_id = c.id WHERE e.branch_id = ?";
        $params = [$branchId];

        if ($courseFilter !== '') {
            $sql .= " AND e.course_id = ?";
            $params[] = $courseFilter;
        }
        if ($statusFilter === 'published') {
            $sql .= " AND e.is_published = 1";
        } elseif ($statusFilter === 'draft') {
            $sql .= " AND e.is_published = 0";
        }
        $sql .= " ORDER BY e.created_at DESC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $exams = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        // Question counts
        foreach ($exams as &$exam) {
            $qStmt = $this->db->prepare("SELECT COUNT(*) as count FROM exam_questions WHERE exam_id = ?");
            $qStmt->execute([$exam['id']]);
            $exam['question_count'] = (int) ($qStmt->fetch()['count'] ?? 0);
        }
        unset($exam);

        // Courses for filter
        $stmt = $this->db->prepare("SELECT c.* FROM courses c INNER JOIN branch_course_fees bcf ON c.id = bcf.course_id WHERE bcf.branch_id = ? AND bcf.is_active = 1 ORDER BY c.name");
        $stmt->execute([$branchId]);
        $courses = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        $this->branchAdminView('exams/index', [
            'title' => 'Manage Exams', 'currentPage' => 'exams',
            'exams' => $exams, 'courses' => $courses,
            'courseFilter' => $courseFilter, 'statusFilter' => $statusFilter,
        ]);
    }

    public function create(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();

        $stmt = $this->db->prepare("SELECT c.* FROM courses c INNER JOIN branch_course_fees bcf ON c.id = bcf.course_id WHERE bcf.branch_id = ? AND bcf.is_active = 1 ORDER BY c.name");
        $stmt->execute([$branchId]);
        $courses = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        $this->branchAdminView('exams/create', [
            'title' => 'Create Exam', 'currentPage' => 'exams', 'courses' => $courses,
        ]);
    }

    public function store(): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();

        $title = sanitize($_POST['title'] ?? '');
        $courseId = sanitize($_POST['course_id'] ?? '');
        $durationMinutes = (int) sanitize($_POST['duration_minutes'] ?? 0);
        $totalMarks = (int) sanitize($_POST['total_marks'] ?? 0);
        $passMarks = (int) sanitize($_POST['pass_marks'] ?? 0);
        $instructions = $_POST['instructions'] ?? '';
        $startTime = sanitize($_POST['start_time'] ?? '') ?: null;
        $endTime = sanitize($_POST['end_time'] ?? '') ?: null;

        if (empty($title) || empty($courseId)) {
            flash('error', 'Please fill in all required fields.');
            redirect(BASE_PATH . '/branch/exams/create');
            return;
        }

        try {
            $stmt = $this->db->prepare(
                "INSERT INTO exams (title, course_id, duration_minutes, total_marks, pass_marks, is_published, branch_id, instructions, start_time, end_time, created_at, updated_at)
                 VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, NOW(), NOW())"
            );
            $stmt->execute([$title, $courseId, $durationMinutes, $totalMarks, $passMarks, $branchId, $instructions, $startTime, $endTime]);
            flash('success', 'Exam created successfully.');
        } catch (\Exception $e) {
            flash('error', 'Failed to create exam. ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/branch/exams');
    }

    public function edit(array $params): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();
        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("SELECT e.*, c.name as course_name FROM exams e LEFT JOIN courses c ON e.course_id = c.id WHERE e.id = ? AND e.branch_id = ?");
        $stmt->execute([$id, $branchId]);
        $exam = $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;

        if (!$exam) {
            flash('error', 'Exam not found.');
            redirect(BASE_PATH . '/branch/exams');
            return;
        }

        $stmt = $this->db->prepare("SELECT c.* FROM courses c INNER JOIN branch_course_fees bcf ON c.id = bcf.course_id WHERE bcf.branch_id = ? AND bcf.is_active = 1 ORDER BY c.name");
        $stmt->execute([$branchId]);
        $courses = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        $this->branchAdminView('exams/edit', [
            'title' => 'Edit Exam', 'currentPage' => 'exams', 'exam' => $exam, 'courses' => $courses,
        ]);
    }

    public function update(array $params): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();
        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("SELECT * FROM exams WHERE id = ? AND branch_id = ?");
        $stmt->execute([$id, $branchId]);
        if (!$stmt->fetch()) {
            flash('error', 'Exam not found.');
            redirect(BASE_PATH . '/branch/exams');
            return;
        }

        $title = sanitize($_POST['title'] ?? '');
        $courseId = sanitize($_POST['course_id'] ?? '');
        $durationMinutes = (int) sanitize($_POST['duration_minutes'] ?? 0);
        $totalMarks = (int) sanitize($_POST['total_marks'] ?? 0);
        $passMarks = (int) sanitize($_POST['pass_marks'] ?? 0);
        $instructions = $_POST['instructions'] ?? '';
        $startTime = sanitize($_POST['start_time'] ?? '') ?: null;
        $endTime = sanitize($_POST['end_time'] ?? '') ?: null;
        $isPublished = isset($_POST['is_published']) ? 1 : 0;

        try {
            $stmt = $this->db->prepare(
                "UPDATE exams SET title=?, course_id=?, duration_minutes=?, total_marks=?, pass_marks=?, is_published=?, instructions=?, start_time=?, end_time=?, updated_at=NOW() WHERE id=? AND branch_id=?"
            );
            $stmt->execute([$title, $courseId, $durationMinutes, $totalMarks, $passMarks, $isPublished, $instructions, $startTime, $endTime, $id, $branchId]);
            flash('success', 'Exam updated successfully.');
        } catch (\Exception $e) {
            flash('error', 'Failed to update exam. ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/branch/exams');
    }

    public function delete(array $params): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();
        $id = (int) ($params['id'] ?? 0);

        try {
            $this->db->beginTransaction();
            $this->db->prepare("DELETE FROM exam_questions WHERE exam_id = ?")->execute([$id]);
            $this->db->prepare("DELETE FROM exam_results WHERE exam_id = ?")->execute([$id]);
            $this->db->prepare("DELETE FROM exams WHERE id = ? AND branch_id = ?")->execute([$id, $branchId]);
            $this->db->commit();
            flash('success', 'Exam deleted successfully.');
        } catch (\Exception $e) {
            $this->db->rollBack();
            flash('error', 'Failed to delete exam. ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/branch/exams');
    }

    public function questions(array $params): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();
        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("SELECT e.*, c.name as course_name FROM exams e LEFT JOIN courses c ON e.course_id = c.id WHERE e.id = ? AND e.branch_id = ?");
        $stmt->execute([$id, $branchId]);
        $exam = $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;

        if (!$exam) {
            flash('error', 'Exam not found.');
            redirect(BASE_PATH . '/branch/exams');
            return;
        }

        $stmt = $this->db->prepare("SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY id ASC");
        $stmt->execute([$id]);
        $questions = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        $this->branchAdminView('exams/questions', [
            'title' => 'Manage Questions', 'currentPage' => 'exams', 'exam' => $exam, 'questions' => $questions,
        ]);
    }

    public function addQuestion(array $params): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();
        $examId = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("SELECT * FROM exams WHERE id = ? AND branch_id = ?");
        $stmt->execute([$examId, $branchId]);
        if (!$stmt->fetch()) {
            flash('error', 'Exam not found.');
            redirect(BASE_PATH . '/branch/exams');
            return;
        }

        $questionText = sanitize($_POST['question_text'] ?? '');
        $optionA = sanitize($_POST['option_a'] ?? '');
        $optionB = sanitize($_POST['option_b'] ?? '');
        $optionC = sanitize($_POST['option_c'] ?? '');
        $optionD = sanitize($_POST['option_d'] ?? '');
        $correctAnswer = sanitize($_POST['correct_answer'] ?? '');
        $marks = (int) sanitize($_POST['marks'] ?? 1);

        if (empty($questionText) || empty($correctAnswer)) {
            flash('error', 'Question text and correct answer are required.');
            redirect(BASE_PATH . '/branch/exams/' . $examId . '/questions');
            return;
        }

        try {
            $stmt = $this->db->prepare(
                "INSERT INTO exam_questions (exam_id, question_text, option_a, option_b, option_c, option_d, correct_answer, marks, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())"
            );
            $stmt->execute([$examId, $questionText, $optionA, $optionB, $optionC, $optionD, $correctAnswer, $marks]);
            flash('success', 'Question added successfully.');
        } catch (\Exception $e) {
            flash('error', 'Failed to add question. ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/branch/exams/' . $examId . '/questions');
    }

    public function deleteQuestion(array $params): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();
        $examId = (int) ($params['exam_id'] ?? 0);
        $questionId = (int) ($params['question_id'] ?? 0);

        $stmt = $this->db->prepare("SELECT * FROM exams WHERE id = ? AND branch_id = ?");
        $stmt->execute([$examId, $branchId]);
        if (!$stmt->fetch()) {
            flash('error', 'Exam not found.');
            redirect(BASE_PATH . '/branch/exams');
            return;
        }

        $this->db->prepare("DELETE FROM exam_questions WHERE id = ? AND exam_id = ?")->execute([$questionId, $examId]);
        flash('success', 'Question deleted successfully.');
        redirect(BASE_PATH . '/branch/exams/' . $examId . '/questions');
    }
}
