<?php
// admin/ajax/update_role_permissions.php
// THIS FILE MUST BE AT: C:\xampp\htdocs\NRMS\admin\ajax\update_role_permissions.php

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

error_reporting(E_ALL);
ini_set('display_errors', 0);

// Simple response function
function send_response($success, $message, $data = []) {
    $response = array_merge(['success' => $success, 'message' => $message], $data);
    echo json_encode($response);
    exit;
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    send_response(false, 'Not logged in');
}

require_once __DIR__ . '/db_connection.php';
require_once __DIR__ . '/PermissionManager.php';
require_once __DIR__ . '/AuthMiddleware.php';

// Only users who can manage permissions may rewrite a role's permission set.
$perm_manager = new PermissionManager($conn);
$auth         = new AuthMiddleware($perm_manager);
$auth->requirePermission('manage_permissions');

// Check if we have the required data
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_response(false, 'POST method required');
}

if (!isset($_POST['role_id'])) {
    send_response(false, 'role_id parameter missing');
}

$role_id = intval($_POST['role_id']);
$permissions = isset($_POST['permissions']) ? $_POST['permissions'] : [];

if ($role_id <= 0) {
    send_response(false, 'Invalid role_id');
}

// First, delete all existing permissions for this role
$delete_sql = "DELETE FROM role_permissions WHERE role_id = ?";
$delete_stmt = $conn->prepare($delete_sql);
if (!$delete_stmt) {
    send_response(false, 'Database error: ' . $conn->error);
}

$delete_stmt->bind_param("i", $role_id);
if (!$delete_stmt->execute()) {
    send_response(false, 'Delete failed: ' . $delete_stmt->error);
}
$delete_stmt->close();

// Now insert the new permissions
$insert_count = 0;
if (!empty($permissions)) {
    $insert_sql = "INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)";
    $insert_stmt = $conn->prepare($insert_sql);
    if (!$insert_stmt) {
        send_response(false, 'Prepare insert failed: ' . $conn->error);
    }
    
    foreach ($permissions as $perm_id) {
        $perm_id = intval($perm_id);
        $insert_stmt->bind_param("ii", $role_id, $perm_id);
        if ($insert_stmt->execute()) {
            $insert_count++;
        }
    }
    $insert_stmt->close();
}

// Verify the save worked
$verify_sql = "SELECT COUNT(*) as count FROM role_permissions WHERE role_id = ?";
$verify_stmt = $conn->prepare($verify_sql);
$verify_stmt->bind_param("i", $role_id);
$verify_stmt->execute();
$verify_result = $verify_stmt->get_result();
$verify_row = $verify_result->fetch_assoc();
$final_count = $verify_row['count'];
$verify_stmt->close();

send_response(true, "Permissions saved successfully. Saved " . $insert_count . " permissions. Database now has " . $final_count . " permissions for this role.", [
    'saved_count' => $insert_count,
    'db_count' => $final_count
]);
?>