<?php
require_once 'shikanisha.kts.php';

header('Content-Type: application/json');

try {
    // Check if this is a POST request
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    // Validate required field exists in POST data
    if (!isset($_POST['page_id'])) {
        throw new Exception('Page ID is required');
    }

    // Sanitize input
    $pageId = $conn->real_escape_string(trim($_POST['page_id']));

    // Validate page_id is numeric
    if (!is_numeric($pageId)) {
        throw new Exception('Invalid Page ID');
    }

    // Begin transaction for atomic operation
    $conn->begin_transaction();

    try {
        // First delete from access_control
        $conn->query("DELETE FROM access_control WHERE page_id = '$pageId'");
        
        // Then delete the page
        $query = "DELETE FROM pages WHERE page_id = '$pageId'";
        if (!$conn->query($query)) {
            throw new Exception('Database error: ' . $conn->error);
        }

        // Commit transaction if both queries succeeded
        $conn->commit();
        
        $response = [
            'success' => true,
            'message' => 'Page deleted successfully'
        ];
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        throw $e;
    }
} catch (Exception $e) {
    $response = [
        'success' => false,
        'message' => $e->getMessage()
    ];
} finally {
    // Close connection and send response
    if (isset($conn)) $conn->close();
    echo json_encode($response);
}
?>