<?php
// 1. Database Connection
require_once '../../includes/config.php';

// 2. Set Header for JSON response
header('Content-Type: application/json');

try {
    // 3. Check if all required fields are present
    if (
        empty($_POST['id']) || 
        empty($_POST['class_id']) || 
        empty($_POST['section_name']) || 
        empty($_POST['status'])
    ) {
        throw new Exception("All fields are required.");
    }

    // 4. Sanitize and Trim variables
    $id           = intval($_POST['id']);
    $class_id     = intval($_POST['class_id']);
    $section_name = trim($_POST['section_name']); // Removes extra spaces
    $status       = trim($_POST['status']);       // Normalizes status string

    // 5. DUPLICATE CHECK FILTER
    // Check if another section already has this name within the SAME class
    $checkSql = "SELECT id FROM sections 
                 WHERE section_name = :name 
                 AND class_id = :class_id 
                 AND id != :id"; // Exclude the current record
    
    $checkStmt = $pdo->prepare($checkSql);
    $checkStmt->execute([
        ':name'     => $section_name,
        ':class_id' => $class_id,
        ':id'       => $id
    ]);

    if ($checkStmt->fetch()) {
        throw new Exception("A section named '$section_name' already exists for this class.");
    }

    // 6. Prepare the UPDATE Statement
    $sql = "UPDATE sections 
            SET class_id = :class_id, 
                section_name = :section_name, 
                status = :status 
            WHERE id = :id";

    $stmt = $pdo->prepare($sql);

    // 7. Execute the query
    $success = $stmt->execute([
        ':class_id'     => $class_id,
        ':section_name' => $section_name,
        ':status'       => $status,
        ':id'           => $id
    ]);

    // 8. Return Success
    if ($success) {
        echo json_encode([
            'status'  => 'success',
            'message' => 'Section updated successfully'
        ]);
    } else {
        throw new Exception("Update failed: No changes made or database error.");
    }

} catch (Exception $e) {
    // 9. Return Error (Using 200 or 400 depending on preference, 400 is cleaner for errors)
    http_response_code(400);
    echo json_encode([
        'status'  => 'error',
        'message' => $e->getMessage()
    ]);
}
?>