<?php
include('../includes/db.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $class_id = (int)$_POST['class_id'];
    $section_id = (int)$_POST['section_id'];
    $subject_ids = $_POST['subject_ids'];
    $academic_year = isset($_POST['academic_year']) ? $conn->real_escape_string($_POST['academic_year']) : NULL;
    
    if (!is_array($subject_ids)) {
        echo json_encode(['success' => false, 'message' => 'Invalid subject data']);
        exit;
    }
    
    // Get class_section mapping id
    $mappingQuery = $conn->query("SELECT id FROM class_section WHERE class_id = $class_id AND section_id = $section_id");
    if ($mappingQuery->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Class-section mapping not found']);
        exit;
    }
    $mappingRow = $mappingQuery->fetch_assoc();
    $mapping_id = $mappingRow['id'];
    
    $successCount = 0;
    $errorCount = 0;
    
    foreach ($subject_ids as $subject_id) {
        $subject_id = (int)$subject_id;
        
        // Check if mapping already exists
        $check = $conn->query("SELECT * FROM class_subject_mapping 
                               WHERE class_id = $class_id AND subject_id = $subject_id");
        
        if ($check->num_rows == 0) {
            // Get subject details
            $subjectQuery = $conn->query("SELECT subject_name FROM subjects WHERE id = $subject_id");
            $subjectRow = $subjectQuery->fetch_assoc();
            $subject_name = $subjectRow['subject_name'];
            
            // Insert new mapping
            $insert = $conn->query("INSERT INTO class_subject_mapping (class_id, subject_id, subject_name) 
                                   VALUES ($class_id, $subject_id, '$subject_name')");
            
            if ($insert) {
                $successCount++;
                
                // Also update studentsub table if needed
                // This would require student data for the class-section
            } else {
                $errorCount++;
            }
        } else {
            $successCount++; // Already exists
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Assigned $successCount subject(s)" . ($errorCount > 0 ? ", $errorCount failed" : "")
    ]);
}
?>