<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');

try {
    $section_id = (int)($_POST['id'] ?? 0);
    if ($section_id <= 0) { echo json_encode(['status'=>'error','message'=>'ID required']); exit; }

    $stmt = $pdo->prepare('SELECT * FROM pattern_sections WHERE section_id = ?');
    $stmt->execute([$section_id]);
    $before = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$before) { echo json_encode(['status'=>'error','message'=>'Not found']); exit; }

    // First delete all questions in this section
    $pdo->prepare('DELETE FROM pattern_questions WHERE section_id = ?')->execute([$section_id]);
    
    // Then delete the section
    $pdo->prepare('DELETE FROM pattern_sections WHERE section_id = ?')->execute([$section_id]);

    write_audit_log($pdo, [
        'module' => 'Question Papers',
        'action' => 'delete',
        'entity_table' => 'pattern_sections',
        'entity_id' => $section_id,
        'before_data' => $before,
        'message' => 'Pattern section and all its questions deleted'
    ]);

    echo json_encode(['status'=>'success','message'=>'Pattern section and all its questions deleted successfully']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>


