<?php
include('includes/session1.php');
error_reporting(0);
include('includes/dbconnection.php');

if (!isset($_SESSION['sid'])) {
    header('location:logoutteacher.php');
    exit();
}

$assigned_by = $_SESSION['sid'];
$class = $_POST['class'];
$section = $_POST['section'];
$student_ids = $_POST['student_ids'];
$subjects = $_POST['subjects'] ?? [];
$tabSessionID = $_POST['tab_id'] ?? '';

// Step 1: Fetch compulsory subjects
$comp_stmt = $con->prepare("SELECT subject_name FROM subjectcombination WHERE class = ? AND section = ? AND subject_type = 'Compulsory'");
$comp_stmt->bind_param("ss", $class, $section);
$comp_stmt->execute();
$comp_res = $comp_stmt->get_result();

$compulsory_subjects = [];
while ($row = $comp_res->fetch_assoc()) {
    $compulsory_subjects[] = $row['subject_name'];
}
$comp_stmt->close();

// Step 2: Loop through each student and update their subjects
foreach ($student_ids as $student_id) {
    $selected_subjects = $subjects[$student_id] ?? [];

    // Merge electives + compulsory (no duplicates)
    $all_subjects = array_unique(array_merge($selected_subjects, $compulsory_subjects));

    // Clear previous subject allocations
    $delete_stmt = $con->prepare("DELETE FROM subject_allocations WHERE student_id = ?");
    $delete_stmt->bind_param("i", $student_id);
    $delete_stmt->execute();
    $delete_stmt->close();

    // Insert new subject allocations
    $insert_stmt = $con->prepare("INSERT INTO subject_allocations (student_id, subject_name, class, section, assigned_by) VALUES (?, ?, ?, ?, ?)");
    foreach ($all_subjects as $subject) {
        $insert_stmt->bind_param("isssi", $student_id, $subject, $class, $section, $assigned_by);
        $insert_stmt->execute();
    }
    $insert_stmt->close();
}

// Step 3: Feedback and go back
echo "<script>
    alert('Subjects successfully assigned!');
    window.history.back();
</script>";