<?php
/**
 * Branch Course Controller — NEW
 * 
 * Allows branch admins to:
 *   1. View all courses
 *   2. Set their own fee per course
 *   3. Set exactly 3 subjects per course (for marksheet)
 *   These settings are branch-specific and override global defaults.
 */

namespace BranchAdmin\Controllers;

use BranchAdmin\Controllers\BranchBaseController;

class BranchCourseController extends BranchBaseController
{
    /**
     * List all courses with branch-specific fee and subjects
     */
    public function index(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();

        // Ensure table exists
        $this->ensureTableExists();

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

        // Get branch-specific settings for all courses
        $stmt = $this->db->prepare("SELECT * FROM branch_course_settings WHERE branch_id = :bid");
        $stmt->execute([':bid' => $branchId]);
        $branchSettings = $stmt->fetchAll() ?: [];
        
        // Index by course_id for easy lookup
        $settingsMap = [];
        foreach ($branchSettings as $s) {
            $settingsMap[$s['course_id']] = $s;
        }

        // Merge global courses with branch settings
        foreach ($courses as &$course) {
            $cid = $course['id'];
            $course['branch_fee'] = $settingsMap[$cid]['course_fee'] ?? $course['fee'] ?? 0;
            $course['branch_subject_1'] = $settingsMap[$cid]['subject_1'] ?? '';
            $course['branch_subject_2'] = $settingsMap[$cid]['subject_2'] ?? '';
            $course['branch_subject_3'] = $settingsMap[$cid]['subject_3'] ?? '';
        }
        unset($course);

        $this->branchAdminView('courses/index', [
            'title'       => 'My Courses & Settings',
            'currentPage' => 'branch_courses',
            'courses'     => $courses,
            'csrfToken'   => $this->csrfToken ?? '',
        ]);
    }

    /**
     * Update branch-specific course settings (fee + 3 subjects)
     */
    public function update(): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();

        $courseId = (int)($_POST['course_id'] ?? 0);
        $courseFee = (float)($_POST['course_fee'] ?? 0);
        $subject1 = trim($_POST['subject_1'] ?? '');
        $subject2 = trim($_POST['subject_2'] ?? '');
        $subject3 = trim($_POST['subject_3'] ?? '');

        if (!$courseId) {
            flash('error', 'Invalid course.');
            redirect(BASE_PATH . '/branch/courses');
        }

        try {
            // Upsert query (Insert if not exists, Update if exists)
            $stmt = $this->db->prepare(
                "INSERT INTO branch_course_settings 
                    (branch_id, course_id, course_fee, subject_1, subject_2, subject_3, updated_at)
                 VALUES 
                    (:bid, :cid, :fee, :s1, :s2, :s3, NOW())
                 ON DUPLICATE KEY UPDATE 
                    course_fee = :fee2, 
                    subject_1 = :s12, 
                    subject_2 = :s22, 
                    subject_3 = :s32, 
                    updated_at = NOW()"
            );
            $stmt->execute([
                ':bid'  => $branchId,
                ':cid'  => $courseId,
                ':fee'  => $courseFee,
                ':s1'   => $subject1,
                ':s2'   => $subject2,
                ':s3'   => $subject3,
                ':fee2' => $courseFee,
                ':s12'  => $subject1,
                ':s22'  => $subject2,
                ':s32'  => $subject3,
            ]);

            flash('success', '✅ Course settings updated successfully! Fee and subjects will be used for this branch only.');
        } catch (\Throwable $e) {
            flash('error', 'Error updating settings: ' . $e->getMessage());
        }

        redirect(BASE_PATH . '/branch/courses');
    }

    /**
     * Ensure the branch_course_settings table exists
     */
    private function ensureTableExists(): void
    {
        try {
            $this->db->exec("CREATE TABLE IF NOT EXISTS `branch_course_settings` (
              `id` INT AUTO_INCREMENT PRIMARY KEY,
              `branch_id` INT NOT NULL,
              `course_id` INT NOT NULL,
              `course_fee` DECIMAL(10,2) NULL DEFAULT NULL,
              `subject_1` VARCHAR(150) NULL DEFAULT NULL,
              `subject_2` VARCHAR(150) NULL DEFAULT NULL,
              `subject_3` VARCHAR(150) NULL DEFAULT NULL,
              `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              UNIQUE KEY `unique_branch_course` (`branch_id`, `course_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        } catch (\Throwable $e) {
            // Table might already exist, ignore error
        }
    }
}
