<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * User Permissions Management - Assign individual permissions to users
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct base path
$base_path = dirname(__DIR__, 3);
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(dirname(__DIR__)));
}
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}

// Require authentication
require_auth();

// Check permission
if (function_exists('require_permission')) {
    require_permission('users.permissions');
}

// Set page title
$page_title = 'User Permissions';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

// Get user ID from URL
$target_user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;

if (!$target_user_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid user ID');
    }
    header('Location: index.php');
    exit;
}

// Get user details
$user = null;
try {
    $user = db_fetch_one("
        SELECT u.*, r.role_name 
        FROM users u
        LEFT JOIN roles r ON u.role_id = r.role_id
        WHERE u.user_id = ?
    ", [$target_user_id]);
} catch (Exception $e) {
    error_log("Error fetching user: " . $e->getMessage());
}

if (!$user) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'User not found');
    }
    header('Location: index.php');
    exit;
}

// Get all permissions grouped by module
$permissions = [];
try {
    $permissions = db_fetch_all("
        SELECT * FROM permissions 
        ORDER BY 
            CASE 
                WHEN module IS NULL OR module = '' THEN 'zzz' 
                ELSE module 
            END, 
            permission_name
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching permissions: " . $e->getMessage());
}

// Group permissions by module
$grouped_permissions = [];
foreach ($permissions as $perm) {
    $module = !empty($perm['module']) ? $perm['module'] : 'General';
    if (!isset($grouped_permissions[$module])) {
        $grouped_permissions[$module] = [];
    }
    $grouped_permissions[$module][] = $perm;
}

// Get role-based permissions for this user
$role_permission_ids = [];
try {
    $role_permissions = db_fetch_all("
        SELECT p.permission_id 
        FROM permissions p
        JOIN role_permissions rp ON p.permission_id = rp.permission_id
        WHERE rp.role_id = ?
    ", [$user['role_id']]) ?: [];
    $role_permission_ids = array_column($role_permissions, 'permission_id');
} catch (Exception $e) {
    error_log("Error fetching role permissions: " . $e->getMessage());
}

// Get user-specific permissions (directly assigned)
$user_permission_ids = [];
try {
    $user_permissions = db_fetch_all("
        SELECT permission_id FROM user_permissions WHERE user_id = ?
    ", [$target_user_id]) ?: [];
    $user_permission_ids = array_column($user_permissions, 'permission_id');
} catch (Exception $e) {
    error_log("Error fetching user permissions: " . $e->getMessage());
}

// Calculate effective permissions (role + user-specific)
$effective_permission_ids = array_unique(array_merge($role_permission_ids, $user_permission_ids));

// Handle form submission
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token (simplified for now)
    $csrf_valid = true;
    
    if (!$csrf_valid) {
        $error = 'Invalid security token. Please try again.';
    } else {
        try {
            if (function_exists('db_begin_transaction')) {
                db_begin_transaction();
            }
            
            // Get submitted permissions (user-specific only)
            $submitted_permissions = isset($_POST['permissions']) ? $_POST['permissions'] : [];
            $submitted_permissions = array_map('intval', $submitted_permissions);
            
            // Filter out permissions that are already from role
            // We only want to manage user-specific overrides
            $to_assign = array_diff($submitted_permissions, $role_permission_ids);
            $to_remove = array_diff($user_permission_ids, $submitted_permissions);
            
            error_log("To Assign: " . print_r($to_assign, true));
            error_log("To Remove: " . print_r($to_remove, true));
            
            // Assign new user-specific permissions
            foreach ($to_assign as $perm_id) {
                // Check if already exists as user permission
                $exists = db_fetch_value("
                    SELECT COUNT(*) FROM user_permissions 
                    WHERE user_id = ? AND permission_id = ?
                ", [$target_user_id, $perm_id]);
                
                if (!$exists) {
                    db_insert('user_permissions', [
                        'user_id' => $target_user_id,
                        'permission_id' => $perm_id,
                        'granted_by' => $current_user['user_id'] ?? 0
                    ]);
                }
            }
            
            // Remove user-specific permissions
            if (!empty($to_remove)) {
                $placeholders = implode(',', array_fill(0, count($to_remove), '?'));
                $params = array_merge([$target_user_id], $to_remove);
                db_query("
                    DELETE FROM user_permissions 
                    WHERE user_id = ? AND permission_id IN ($placeholders)
                ", $params);
            }
            
            if (function_exists('db_commit')) {
                db_commit();
            }
            
            $message = 'User permissions updated successfully';
            
            // Refresh user permission IDs
            $user_permissions = db_fetch_all("
                SELECT permission_id FROM user_permissions WHERE user_id = ?
            ", [$target_user_id]) ?: [];
            $user_permission_ids = array_column($user_permissions, 'permission_id');
            $effective_permission_ids = array_unique(array_merge($role_permission_ids, $user_permission_ids));
            
        } catch (Exception $e) {
            if (function_exists('db_rollback')) {
                db_rollback();
            }
            $error = 'Failed to update permissions: ' . $e->getMessage();
            error_log("Permissions update failed: " . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Permissions: <?php echo htmlspecialchars($user['username'] ?? ''); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
        .content-header { padding: 20px; background: #fff; border-bottom: 1px solid #dee2e6; margin-bottom: 20px; }
        .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
        .card-header { background: #f8f9fa; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        .module-card { margin-bottom: 20px; border: 1px solid #dee2e6; border-radius: 0.5rem; overflow: hidden; }
        .module-header { background: #e9ecef; padding: 10px 15px; font-weight: 600; border-bottom: 1px solid #dee2e6; }
        .module-body { padding: 15px; background: #fff; }
        .permission-item { margin-bottom: 10px; padding: 8px; border-radius: 4px; transition: background 0.2s; }
        .permission-item:hover { background: #f8f9fa; }
        .role-permission { background-color: #e7f3ff; border-left: 3px solid #007bff; }
        .user-permission { background-color: #e6ffe6; border-left: 3px solid #28a745; }
        .badge-role { background: #007bff; color: white; font-size: 0.7rem; padding: 2px 6px; border-radius: 10px; }
        .badge-user { background: #28a745; color: white; font-size: 0.7rem; padding: 2px 6px; border-radius: 10px; }
        .badge-both { background: #6f42c1; color: white; font-size: 0.7rem; padding: 2px 6px; border-radius: 10px; }
        .fixed-counter { position: fixed; bottom: 20px; right: 20px; z-index: 1000; background: #17a2b8; color: white; padding: 10px 20px; border-radius: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.2); }
        .me-1 { margin-right: 0.25rem; }
        .me-2 { margin-right: 0.5rem; }
        .mb-3 { margin-bottom: 1rem; }
        .mt-2 { margin-top: 0.5rem; }
        .ms-2 { margin-left: 0.5rem; }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">Ruhondo Beach Resort</a>
            <div class="navbar-nav ms-auto">
                <span class="nav-item nav-link text-white">
                    <i class="fas fa-user"></i> 
                    <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                </span>
                <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>
    </nav>

    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">
                        User Permissions: <?php echo htmlspecialchars($user['username'] ?? ''); ?>
                        <small class="text-muted">(<?php echo htmlspecialchars($user['first_name'] ?? '') . ' ' . htmlspecialchars($user['last_name'] ?? ''); ?>)</small>
                    </h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="/HMSPOS/admin/dashboard.php">Admin</a></li>
                        <li class="breadcrumb-item"><a href="index.php">Users</a></li>
                        <li class="breadcrumb-item"><a href="view.php?id=<?php echo $target_user_id; ?>">View User</a></li>
                        <li class="breadcrumb-item active">Permissions</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Messages -->
            <?php if ($message): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- User Info -->
            <div class="row mb-3">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <strong>Role:</strong> 
                                    <span class="badge bg-info"><?php echo htmlspecialchars($user['role_name'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="col-md-3">
                                    <strong>Department:</strong> 
                                    <span class="badge bg-secondary"><?php echo htmlspecialchars($user['department'] ?? 'Not assigned'); ?></span>
                                </div>
                                <div class="col-md-3">
                                    <strong>Status:</strong>
                                    <?php if (!empty($user['is_active'])): ?>
                                        <span class="badge bg-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">Inactive</span>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-3 text-end">
                                    <span class="badge bg-primary">Role Permissions: <?php echo count($role_permission_ids); ?></span>
                                    <span class="badge bg-success ms-1">User Permissions: <?php echo count($user_permission_ids); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Legend -->
            <div class="row mb-3">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body py-2">
                            <span class="badge bg-primary me-2">Role Permission</span> - Granted through role (cannot be changed here)
                            <span class="badge bg-success ms-3 me-2">User Permission</span> - Directly assigned to this user
                            <span class="badge bg-warning ms-3 me-2">Override</span> - User permission overrides role
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h3 class="card-title">
                                <i class="fas fa-key me-1"></i>
                                Manage User Permissions
                            </h3>
                            <div>
                                <button type="button" class="btn btn-sm btn-info" id="selectAll">
                                    <i class="fas fa-check-double me-1"></i> Select All
                                </button>
                                <button type="button" class="btn btn-sm btn-secondary" id="deselectAll">
                                    <i class="fas fa-times me-1"></i> Deselect All
                                </button>
                            </div>
                        </div>
                        
                        <form method="POST" id="permissionsForm">
                            <div class="card-body">
                                <?php if (empty($grouped_permissions)): ?>
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle me-2"></i>
                                        No permissions found in the system.
                                    </div>
                                <?php else: ?>
                                    <?php foreach ($grouped_permissions as $module => $perms): ?>
                                        <div class="module-card">
                                            <div class="module-header d-flex justify-content-between align-items-center">
                                                <span>
                                                    <i class="fas fa-cube me-1"></i>
                                                    <?php echo ucfirst($module); ?> Module
                                                </span>
                                                <button type="button" class="btn btn-sm btn-info select-module" data-module="<?php echo $module; ?>">
                                                    Select All
                                                </button>
                                            </div>
                                            <div class="module-body">
                                                <div class="row">
                                                    <?php foreach ($perms as $perm): 
                                                        $perm_id = $perm['permission_id'] ?? 0;
                                                        $is_role_perm = in_array($perm_id, $role_permission_ids);
                                                        $is_user_perm = in_array($perm_id, $user_permission_ids);
                                                        $is_effective = in_array($perm_id, $effective_permission_ids);
                                                        
                                                        // Determine classes and badges
                                                        $item_class = 'permission-item';
                                                        $badge_html = '';
                                                        
                                                        if ($is_role_perm && $is_user_perm) {
                                                            $item_class .= ' both-permission';
                                                            $badge_html = '<span class="badge bg-warning ms-2">Override</span>';
                                                        } elseif ($is_role_perm) {
                                                            $item_class .= ' role-permission';
                                                            $badge_html = '<span class="badge bg-primary ms-2">Role</span>';
                                                        } elseif ($is_user_perm) {
                                                            $item_class .= ' user-permission';
                                                            $badge_html = '<span class="badge bg-success ms-2">User</span>';
                                                        }
                                                    ?>
                                                        <div class="col-md-4 col-sm-6">
                                                            <div class="<?php echo $item_class; ?>">
                                                                <div class="form-check">
                                                                    <input type="checkbox" 
                                                                           class="form-check-input permission-checkbox module-<?php echo preg_replace('/[^a-z0-9]/', '', strtolower($module)); ?>"
                                                                           id="perm_<?php echo $perm_id; ?>" 
                                                                           name="permissions[]" 
                                                                           value="<?php echo $perm_id; ?>"
                                                                           <?php echo $is_user_perm ? 'checked' : ''; ?>
                                                                           <?php echo $is_role_perm ? 'disabled' : ''; ?>
                                                                           title="<?php echo $is_role_perm ? 'This permission is granted through role and cannot be changed' : ''; ?>">
                                                                    <label class="form-check-label" for="perm_<?php echo $perm_id; ?>">
                                                                        <strong><?php echo htmlspecialchars($perm['permission_name'] ?? ''); ?></strong>
                                                                        <?php echo $badge_html; ?>
                                                                        <br>
                                                                        <small class="text-muted"><?php echo htmlspecialchars($perm['permission_key'] ?? ''); ?></small>
                                                                    </label>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            
                            <div class="card-footer">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-1"></i> Save User Permissions
                                </button>
                                <a href="view.php?id=<?php echo $target_user_id; ?>" class="btn btn-secondary">
                                    <i class="fas fa-times me-1"></i> Cancel
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Selected Count Display -->
    <div class="fixed-counter" id="selectedCount">
        0 user permissions selected
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    $(document).ready(function() {
        // Select all user-assignable permissions (not disabled)
        $('#selectAll').click(function() {
            $('.permission-checkbox:not(:disabled)').prop('checked', true);
            updateSelectedCount();
        });
        
        // Deselect all user-assignable permissions
        $('#deselectAll').click(function() {
            $('.permission-checkbox:not(:disabled)').prop('checked', false);
            updateSelectedCount();
        });
        
        // Select module permissions (only user-assignable)
        $('.select-module').click(function() {
            var module = $(this).data('module');
            var className = '.module-' + module.toLowerCase().replace(/[^a-z0-9]/g, '');
            $(className + ':not(:disabled)').prop('checked', true);
            updateSelectedCount();
        });
        
        // Update selected count on checkbox change
        $('.permission-checkbox').change(updateSelectedCount);
        
        // Update selected count function
        function updateSelectedCount() {
            var total = $('.permission-checkbox:not(:disabled)').length;
            var checked = $('.permission-checkbox:checked:not(:disabled)').length;
            $('#selectedCount').text(checked + ' of ' + total + ' user permissions selected');
        }
        
        // Initial count
        updateSelectedCount();
        
        // Form validation
        $('#permissionsForm').submit(function(e) {
            // No validation needed, can submit with 0 selections
        });
    });
    </script>
</body>
</html>