<?php
declare(strict_types=1);
namespace SuperAdmin\Controllers;

/**
 * Super Admin Course Subjects Controller
 *
 * Manages subjects + max marks per course. These subjects fall back to:
 *   - Branch cert-gen result form (auto-loads subjects when creating result)
 *   - Marksheet PDF (subject_marks table renders these subjects with marks)
 */
class SuperAdminCourseSubjectController extends SuperAdminBaseController
{
    /**
     * List all courses with their subjects.
     */
    public function index(): void
    {
        requireSuperAdmin();

        $stmt = $this->db->query("SELECT id, name, duration, subjects FROM courses WHERE active = 1 ORDER BY name");
        $courses = $stmt->fetchAll() ?: [];

        // Parse subjects JSON for each course
        foreach ($courses as &$c) {
            $subs = [];
            if (!empty($c['subjects'])) {
                $decoded = json_decode($c['subjects'], true);
                if (is_array($decoded)) $subs = $decoded;
            }
            $c['parsed_subjects'] = $subs;
            $c['subject_count'] = count($subs);
        }
        unset($c);

        $this->superAdminView('course_subjects/index', [
            'title'       => 'Course Subjects',
            'currentPage' => 'course_subjects',
            'courses'     => $courses,
        ]);
    }

    /**
     * Edit subjects for a specific course.
     */
    public function edit(int $courseId): void
    {
        requireSuperAdmin();

        $stmt = $this->db->prepare("SELECT * FROM courses WHERE id = :cid LIMIT 1");
        $stmt->execute([':cid' => $courseId]);
        $course = $stmt->fetch() ?: null;
        if (!$course) {
            flash('error', 'Course not found.');
            redirect(BASE_PATH . '/super-admin/course-subjects');
        }

        $subjects = [];
        if (!empty($course['subjects'])) {
            $decoded = json_decode($course['subjects'], true);
            if (is_array($decoded)) $subjects = $decoded;
        }

        $this->superAdminView('course_subjects/edit', [
            'title'       => 'Subjects: ' . $course['name'],
            'currentPage' => 'course_subjects',
            'course'      => $course,
            'subjects'    => $subjects,
        ]);
    }

    /**
     * Save subjects for a course.
     */
    public function save(): void
    {
        requireSuperAdmin();
        $this->validateCsrf();

        $courseId = (int)($_POST['course_id'] ?? 0);
        if ($courseId <= 0) {
            flash('error', 'Invalid course ID.');
            redirect(BASE_PATH . '/super-admin/course-subjects');
        }

        $subjectNames = $_POST['subject_name'] ?? [];
        $maxMarks     = $_POST['max_marks'] ?? [];

        // Build subjects array
        $subjects = [];
        for ($i = 0; $i < count($subjectNames); $i++) {
            $name = trim($subjectNames[$i] ?? '');
            $max  = (int)($maxMarks[$i] ?? 100);
            if ($name === '') continue;
            if ($max < 1) $max = 100;
            $subjects[] = ['name' => $name, 'max_marks' => $max];
        }

        $subjectsJson = json_encode($subjects);

        try {
            // Check if subjects column exists
            $stmt = $this->db->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'courses' AND COLUMN_NAME = 'subjects'");
            $stmt->execute();
            $hasCol = (int)$stmt->fetchColumn() > 0;

            if (!$hasCol) {
                $this->db->exec("ALTER TABLE `courses` ADD COLUMN `subjects` TEXT NULL DEFAULT NULL");
            }

            $this->db->prepare("UPDATE courses SET subjects = :subs, updated_at = NOW() WHERE id = :cid")
                ->execute([':subs' => $subjectsJson, ':cid' => $courseId]);

            $this->auditLog('course_subjects_save', 'courses', $courseId, 'Saved ' . count($subjects) . ' subjects');
            flash('success', '✅ Saved ' . count($subjects) . ' subjects for this course. These will auto-load when branches create results.');
        } catch (\Throwable $e) {
            flash('error', 'Failed: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/super-admin/course-subjects');
    }
}
