<?php
session_start();
include 'layouts/dbconn.php';

// Set content type to JSON
header('Content-Type: application/json');

// Check if user is logged in and has admin privileges
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Access denied']);
    exit();
}

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit();
}

try {
    // Get POST data
    $role_id = intval($_POST['role_id'] ?? 0);
    $permissions = $_POST['permissions'] ?? [];
    
    if ($role_id <= 0) {
        throw new Exception('Invalid role ID');
    }
    
    // Verify role exists and is not a protected system role for certain operations
    $role_check_sql = "SELECT role_name, is_system FROM user_roles WHERE role_id = ? AND is_active = 1";
    $role_check_stmt = $conn->prepare($role_check_sql);
    $role_check_stmt->bind_param('i', $role_id);
    $role_check_stmt->execute();
    $role_result = $role_check_stmt->get_result();
    
    if ($role_result->num_rows === 0) {
        throw new Exception('Role not found or inactive');
    }
    
    $role_data = $role_result->fetch_assoc();
    
    // Start transaction
    $conn->begin_transaction();
    
    // Delete existing permissions for this role
    $delete_sql = "DELETE FROM role_permissions WHERE role_id = ?";
    $delete_stmt = $conn->prepare($delete_sql);
    $delete_stmt->bind_param('i', $role_id);
    
    if (!$delete_stmt->execute()) {
        throw new Exception('Failed to clear existing permissions');
    }
    
    // Insert new permissions
    if (!empty($permissions)) {
        $insert_sql = "INSERT INTO role_permissions (role_id, menu_id, can_view, can_create, can_edit, can_delete) VALUES (?, ?, 1, 0, 0, 0)";
        $insert_stmt = $conn->prepare($insert_sql);
        
        foreach ($permissions as $menu_id) {
            $menu_id = intval($menu_id);
            
            // Verify menu item exists
            $menu_check_sql = "SELECT menu_id FROM menu_items WHERE menu_id = ? AND is_active = 1";
            $menu_check_stmt = $conn->prepare($menu_check_sql);
            $menu_check_stmt->bind_param('i', $menu_id);
            $menu_check_stmt->execute();
            
            if ($menu_check_stmt->get_result()->num_rows > 0) {
                $insert_stmt->bind_param('ii', $role_id, $menu_id);
                if (!$insert_stmt->execute()) {
                    throw new Exception('Failed to insert permission for menu ID: ' . $menu_id);
                }
            }
        }
    }
    
    // Log the activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent) 
                     VALUES (?, 'UPDATE_PERMISSIONS', 'ROLES', ?, 'role_permissions', ?, ?, ?)";
    $activity_stmt = $conn->prepare($activity_sql);
    
    $new_values = json_encode([
        'role_id' => $role_id,
        'role_name' => $role_data['role_name'],
        'permissions_count' => count($permissions),
        'menu_ids' => $permissions
    ]);
    
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? null;
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? null;
    $user_id = $_SESSION['user_id'];
    
    $activity_stmt->bind_param('iisss', $user_id, $role_id, $new_values, $ip_address, $user_agent);
    $activity_stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    // Success response
    echo json_encode([
        'success' => true,
        'message' => 'Permissions updated successfully',
        'data' => [
            'role_id' => $role_id,
            'role_name' => $role_data['role_name'],
            'permissions_count' => count($permissions),
            'updated_at' => date('Y-m-d H:i:s')
        ]
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    if ($conn->inTransaction()) {
        $conn->rollback();
    }
    
    // Error response
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
    
    // Log error for debugging
    error_log("Permission save error: " . $e->getMessage() . " - User ID: " . ($_SESSION['user_id'] ?? 'unknown'));
    
} finally {
    // Close database connection
    if (isset($conn)) {
        $conn->close();
    }
}
?>