<?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 fields exist in POST data
    if (!isset($_POST['page_id']) || !isset($_POST['role_id']) || !isset($_POST['has_access'])) {
        throw new Exception('Missing required fields');
    }

    // Sanitize inputs
    $pageId = $conn->real_escape_string(trim($_POST['page_id']));
    $roleId = $conn->real_escape_string(trim($_POST['role_id']));
    $hasAccess = $conn->real_escape_string(trim($_POST['has_access']));

    // Validate values
    if (!is_numeric($pageId) || !is_numeric($roleId) || !in_array($hasAccess, ['0', '1'])) {
        throw new Exception('Invalid input values');
    }

    // Prepare query based on access type
    if ($hasAccess == '1') {
        // Add or update access
        $query = "INSERT INTO access_control (page_id, role_id) VALUES ('$pageId', '$roleId')
                 ON DUPLICATE KEY UPDATE page_id = VALUES(page_id), role_id = VALUES(role_id)";
    } else {
        // Remove access
        $query = "DELETE FROM access_control WHERE page_id = '$pageId' AND role_id = '$roleId'";
    }

    // Execute query
    if ($conn->query($query)) {
        $response = [
            'success' => true,
            'message' => 'Access updated successfully'
        ];
    } else {
        throw new Exception('Database error: ' . $conn->error);
    }
} catch (Exception $e) {
    $response = [
        'success' => false,
        'message' => $e->getMessage()
    ];
} finally {
    // Close connection and send response
    if (isset($conn)) $conn->close();
    echo json_encode($response);
}
?>