<?php

declare(strict_types=1);

namespace SuperAdmin\Controllers;

/**
 * Super Admin Course Controller
 *
 * Super Admin manages courses (global — all branches see these courses):
 *   - Create course (name, category, duration, fee, description, syllabus, image)
 *   - Add subjects with max marks (stored in courses.subjects as JSON)
 *   - Edit/Delete courses
 *
 * Branch admins can ONLY set the fee for their branch (via branch_course_fees).
 */
class SuperAdminCourseController extends SuperAdminBaseController
{
    public function index(): void
    {
        requireSuperAdmin();

        $stmt = $this->db->query("SELECT * FROM `courses` ORDER BY `category`, `name`");
        $courses = $stmt->fetchAll() ?: [];

        $this->superAdminView('courses/index', [
            'title' => 'Manage Courses',
            'currentPage' => 'courses',
            'courses' => $courses,
        ]);
    }

    public function create(): void
    {
        requireSuperAdmin();

        $this->superAdminView('courses/create', [
            'title' => 'Add New Course',
            'currentPage' => 'courses',
        ]);
    }

    public function store(): void
    {
        requireSuperAdmin();
        $this->validateCsrf();

        $name = trim($_POST['name'] ?? '');
        $nameHi = trim($_POST['name_hi'] ?? '') ?: null;
        $category = trim($_POST['category'] ?? 'computer');
        $duration = trim($_POST['duration'] ?? '');
        $durationHi = trim($_POST['duration_hi'] ?? '') ?: null;
        $durationUnit = trim($_POST['duration_unit'] ?? 'months');
        $fee = (float)($_POST['fee'] ?? 0);
        $description = $_POST['description'] ?? '';
        $descriptionHi = trim($_POST['description_hi'] ?? '') ?: null;
        $syllabus = $_POST['syllabus'] ?? '';
        $content = $_POST['content'] ?? $description;
        $active = isset($_POST['active']) ? 1 : 0;
        $isFeatured = isset($_POST['is_featured']) ? 1 : 0;

        if (empty($name) || empty($duration)) {
            flash('error', 'Course name and duration are required.');
            redirect(BASE_PATH . '/super-admin/courses/create');
        }

        if (!in_array($category, ['computer','accounting','programming','design','other'], true)) {
            $category = 'computer';
        }

        // Build subjects JSON from form input
        $subjects = [];
        $subjectNames = $_POST['subject_name'] ?? [];
        $subjectMaxMarks = $_POST['subject_max_marks'] ?? [];
        for ($i = 0; $i < count($subjectNames); $i++) {
            $sName = trim($subjectNames[$i] ?? '');
            $sMax = (int)($subjectMaxMarks[$i] ?? 100);
            if (!empty($sName)) {
                $subjects[] = ['name' => $sName, 'max_marks' => $sMax];
            }
        }
        $subjectsJson = !empty($subjects) ? json_encode($subjects) : null;

        // Handle image upload
        $imagePath = $this->handleImageUpload('image', 'courses');

        try {
            $hasSubjectsCol = $this->columnExists('courses', 'subjects');
            $hasContentCol = $this->columnExists('courses', 'content');
            $hasNameHiCol = $this->columnExists('courses', 'name_hi');
            $hasDescHiCol = $this->columnExists('courses', 'description_hi');
            $hasDurHiCol = $this->columnExists('courses', 'duration_hi');
            $hasDurUnitCol = $this->columnExists('courses', 'duration_unit');
            $hasFeaturedCol = $this->columnExists('courses', 'is_featured');

            $sql = "INSERT INTO `courses` (`name`, `category`, `duration`, `fee`, `description`, `syllabus`, `image`, `active`, `created_at`, `updated_at`";
            $params = [$name, $category, $duration, $fee, $description, $syllabus, $imagePath, $active, date('Y-m-d H:i:s'), date('Y-m-d H:i:s')];

            if ($hasContentCol) { $sql .= ", `content`"; $params[] = $content; }
            if ($hasNameHiCol) { $sql .= ", `name_hi`"; $params[] = $nameHi; }
            if ($hasDescHiCol) { $sql .= ", `description_hi`"; $params[] = $descriptionHi; }
            if ($hasDurHiCol) { $sql .= ", `duration_hi`"; $params[] = $durationHi; }
            if ($hasDurUnitCol) { $sql .= ", `duration_unit`"; $params[] = $durationUnit; }
            if ($hasFeaturedCol) { $sql .= ", `is_featured`"; $params[] = $isFeatured; }
            if ($hasSubjectsCol) { $sql .= ", `subjects`"; $params[] = $subjectsJson; }

            $placeholders = implode(', ', array_fill(0, count($params), '?'));
            $sql .= ") VALUES ({$placeholders})";

            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            $courseId = (int)$this->db->lastInsertId();

            $this->auditLog('course_create', 'courses', $courseId, "Created course '{$name}' with " . count($subjects) . " subjects");
            flash('success', "Course '{$name}' created successfully with " . count($subjects) . " subject(s).");
        } catch (\Throwable $e) {
            flash('error', 'Failed: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/super-admin/courses');
    }

    public function edit(int $id): void
    {
        requireSuperAdmin();

        $stmt = $this->db->prepare("SELECT * FROM `courses` WHERE `id` = :id LIMIT 1");
        $stmt->execute([':id' => $id]);
        $course = $stmt->fetch() ?: null;

        if (!$course) { flash('error', 'Course not found.'); redirect(BASE_PATH . '/super-admin/courses'); }

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

        $this->superAdminView('courses/edit', [
            'title' => 'Edit Course: ' . ($course['name'] ?? ''),
            'currentPage' => 'courses',
            'course' => $course,
            'subjects' => $subjects,
        ]);
    }

    public function update(int $id): void
    {
        requireSuperAdmin();
        $this->validateCsrf();

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

        $name = trim($_POST['name'] ?? '');
        $nameHi = trim($_POST['name_hi'] ?? '') ?: null;
        $category = trim($_POST['category'] ?? 'computer');
        $duration = trim($_POST['duration'] ?? '');
        $durationHi = trim($_POST['duration_hi'] ?? '') ?: null;
        $durationUnit = trim($_POST['duration_unit'] ?? 'months');
        $fee = (float)($_POST['fee'] ?? 0);
        $description = $_POST['description'] ?? '';
        $descriptionHi = trim($_POST['description_hi'] ?? '') ?: null;
        $syllabus = $_POST['syllabus'] ?? '';
        $content = $_POST['content'] ?? $description;
        $active = isset($_POST['active']) ? 1 : 0;
        $isFeatured = isset($_POST['is_featured']) ? 1 : 0;

        if (empty($name)) { flash('error', 'Course name required.'); redirect(BASE_PATH . '/super-admin/courses/' . $id . '/edit'); }

        // Build subjects JSON
        $subjects = [];
        $subjectNames = $_POST['subject_name'] ?? [];
        $subjectMaxMarks = $_POST['subject_max_marks'] ?? [];
        for ($i = 0; $i < count($subjectNames); $i++) {
            $sName = trim($subjectNames[$i] ?? '');
            $sMax = (int)($subjectMaxMarks[$i] ?? 100);
            if (!empty($sName)) $subjects[] = ['name' => $sName, 'max_marks' => $sMax];
        }
        $subjectsJson = !empty($subjects) ? json_encode($subjects) : null;

        $imagePath = $course['image'];
        $uploaded = $this->handleImageUpload('image', 'courses');
        if ($uploaded) { if ($imagePath) $this->deleteImageFile($imagePath); $imagePath = $uploaded; }

        try {
            $hasSubjectsCol = $this->columnExists('courses', 'subjects');
            $hasContentCol = $this->columnExists('courses', 'content');
            $hasNameHiCol = $this->columnExists('courses', 'name_hi');
            $hasDescHiCol = $this->columnExists('courses', 'description_hi');
            $hasDurHiCol = $this->columnExists('courses', 'duration_hi');
            $hasDurUnitCol = $this->columnExists('courses', 'duration_unit');
            $hasFeaturedCol = $this->columnExists('courses', 'is_featured');

            $sql = "UPDATE `courses` SET `name` = ?, `category` = ?, `duration` = ?, `fee` = ?, `description` = ?, `syllabus` = ?, `image` = ?, `active` = ?, `updated_at` = NOW()";
            $params = [$name, $category, $duration, $fee, $description, $syllabus, $imagePath, $active];

            if ($hasContentCol) { $sql .= ", `content` = ?"; $params[] = $content; }
            if ($hasNameHiCol) { $sql .= ", `name_hi` = ?"; $params[] = $nameHi; }
            if ($hasDescHiCol) { $sql .= ", `description_hi` = ?"; $params[] = $descriptionHi; }
            if ($hasDurHiCol) { $sql .= ", `duration_hi` = ?"; $params[] = $durationHi; }
            if ($hasDurUnitCol) { $sql .= ", `duration_unit` = ?"; $params[] = $durationUnit; }
            if ($hasFeaturedCol) { $sql .= ", `is_featured` = ?"; $params[] = $isFeatured; }
            if ($hasSubjectsCol) { $sql .= ", `subjects` = ?"; $params[] = $subjectsJson; }

            $sql .= " WHERE `id` = ?";
            $params[] = $id;

            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);

            $this->auditLog('course_update', 'courses', $id, "Updated course '{$name}'");
            flash('success', 'Course updated successfully.');
        } catch (\Throwable $e) {
            flash('error', 'Failed: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/super-admin/courses');
    }

    public function delete(int $id): void
    {
        requireSuperAdmin();
        $this->validateCsrf();
        try {
            $this->db->prepare("DELETE FROM `courses` WHERE `id` = :id")->execute([':id' => $id]);
            flash('success', 'Course deleted.');
        } catch (\Throwable $e) { flash('error', 'Failed: ' . $e->getMessage()); }
        redirect(BASE_PATH . '/super-admin/courses');
    }
}
