<?php
session_start();
include('../includes/db_pdo.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = $_POST['student_id'];
    $class_id = $_POST['class_id'];
    $section_id = $_POST['section_id'];
    $academic_year = $_POST['academic_year'];
    $remarks = isset($_POST['remarks']) ? $_POST['remarks'] : '';
    
    try {
        // Check if record exists
        $check_query = "SELECT * FROM student_class_section_data 
                       WHERE student_id = :student_id 
                       AND academic_year = :academic_year";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->execute([
            ':student_id' => $student_id,
            ':academic_year' => $academic_year
        ]);
        
        if ($check_stmt->rowCount() > 0) {
            // Update existing record
            $update_query = "UPDATE student_class_section_data 
                            SET class_id = :class_id,
                                section_id = :section_id,
                                remarks = :remarks,
                                updated_at = NOW()
                            WHERE student_id = :student_id 
                            AND academic_year = :academic_year";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->execute([
                ':class_id' => $class_id,
                ':section_id' => $section_id,
                ':remarks' => $remarks,
                ':student_id' => $student_id,
                ':academic_year' => $academic_year
            ]);
        } else {
            // Insert new record
            $insert_query = "INSERT INTO student_class_section_data 
                            (student_id, class_id, section_id, academic_year, remarks, status, created_at) 
                            VALUES (:student_id, :class_id, :section_id, :academic_year, :remarks, 'active', NOW())";
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->execute([
                ':student_id' => $student_id,
                ':class_id' => $class_id,
                ':section_id' => $section_id,
                ':academic_year' => $academic_year,
                ':remarks' => $remarks
            ]);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Section updated successfully'
        ]);
        
    } catch (PDOException $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
}
?>