<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
include('includes/dbconnection.php');
include('includes/flash.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($_SESSION['csrf_token'])) {
        flash_alert('CSRF token is missing from session.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
        exit();
    }

    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        flash_alert('CSRF token validation failed.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
        exit();
    }

    $teacher_id = $_POST['teacher_id'] ?? null;
    $class_id = $_POST['class_id'] ?? null;
    $subjects = $_POST['subjects'] ?? [];
    $subject_class_id = $_POST['subject_class_id'] ?? null;


    if (!$teacher_id) {
        flash_alert('Please select a teacher.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
        exit();
    }

    $con->begin_transaction();

    try {
        // ✅ Get class name
        $class_name = "Unknown Class";
        if (!empty($class_id)) {
            $classQ = mysqli_query($con, "SELECT class, section FROM class_section WHERE id = '$class_id' LIMIT 1");
            $classData = mysqli_fetch_assoc($classQ);
            if ($classData) {
                $class_name = $classData['class'] . ' ' . $classData['section'];
            }
        }

        // ✅ 1. Check if the class already has a class teacher
        if (!empty($class_id)) {
            $check = $con->prepare("SELECT teacher_id FROM teacher_assignments WHERE class_id = ? AND is_class_teacher = 1");
            $check->bind_param("i", $class_id);
            $check->execute();
            $check->store_result();

            if ($check->num_rows > 0) {
                flash_alert('Another teacher is already assigned as class teacher for ' . $class_name . '.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
                exit();
            }

            // ✅ 2. Check if this teacher is already a class teacher somewhere else
            $check_teacher = $con->prepare("SELECT class_id FROM teacher_assignments WHERE teacher_id = ? AND is_class_teacher = 1");
            $check_teacher->bind_param("i", $teacher_id);
            $check_teacher->execute();
            $check_teacher->store_result();

            if ($check_teacher->num_rows > 0) {
                flash_alert('This teacher is already assigned as class teacher for another class.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
                exit();
            }

            // ✅ All clear — assign as class teacher
            $stmt = $con->prepare("INSERT INTO teacher_assignments (teacher_id, class_id, subject_id, is_class_teacher) 
                                   VALUES (?, ?, NULL, 1)");
            $stmt->bind_param("ii", $teacher_id, $class_id);
            $stmt->execute();
        }

        // ✅ 3. Check subject assignments

        if (!empty($subjects)) {
            foreach ($subjects as $subject_id) {
                $subjectQ = mysqli_query($con, "SELECT Subject_name FROM subjectcombination WHERE id = '$subject_id' LIMIT 1");
                $subjectData = mysqli_fetch_assoc($subjectQ);
                $subject_name = $subjectData['Subject_name'] ?? "Subject ID $subject_id";

                $checkSub = $con->prepare("SELECT teacher_id FROM teacher_assignments 
                                           WHERE class_id = ? AND subject_id = ? AND is_class_teacher = 0");
                $checkSub->bind_param("ii", $subject_class_id, $subject_id);
                $checkSub->execute();
                $checkSub->store_result();

                if ($checkSub->num_rows > 0) {
                    flash_alert('The subject \\\"' . $subject_name . '\\\" is already assigned to another teacher.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
                    exit();
                }

                $stmt = $con->prepare("INSERT INTO teacher_assignments (teacher_id, class_id, subject_id, is_class_teacher) 
                                       VALUES (?, ?, ?, 0)");
                $stmt->bind_param("iii", $teacher_id, $subject_class_id, $subject_id);
                $stmt->execute();
            }
        }


        $con->commit();
        flash_alert('Teacher assigned successfully!');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
    } catch (Exception $e) {
        $con->rollback();
        $msg = addslashes($e->getMessage()); // Escape any quotes
        flash_alert('Error: ' . $msg);
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;
    }
}
