<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Role Permissions Management
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct base path dynamically
$base_path = null;

// Method 1: Try going up 3 levels from current file
// Current file: /admin/users/permissions.php
// Target: /config/config.php
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: Try with document root
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = $_SERVER['DOCUMENT_ROOT'] . '/HMSPOS';
}

// Method 4: Try one more absolute path for XAMPP
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 5: Try with current directory structure
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = realpath(__DIR__ . '/../../..');
}

// Method 6: Try to find config by traversing up
if (!file_exists($base_path . '/config/config.php')) {
    $current_dir = __DIR__;
    for ($i = 0; $i < 5; $i++) {
        $current_dir = dirname($current_dir);
        if (file_exists($current_dir . '/config/config.php')) {
            $base_path = $current_dir;
            break;
        }
    }
}

// Method 7: Try with the path from the current file's location
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = str_replace('\\', '/', dirname(__DIR__, 3));
}

// Verify config file exists
if (!file_exists($base_path . '/config/config.php')) {
    die('Critical Error: Cannot locate config.php. Please check file paths.<br>
         Base path tried: ' . $base_path . '<br>
         Current directory: ' . __DIR__ . '<br>
         Document root: ' . ($_SERVER['DOCUMENT_ROOT'] ?? 'Not set'));
}

// Initialize system with error handling
try {
    require_once $base_path . '/config/config.php';
    
    // Check if constants.php exists
    if (file_exists($base_path . '/config/constants.php')) {
        require_once $base_path . '/config/constants.php';
    }
    
    // Check if database.php exists
    if (file_exists($base_path . '/config/database.php')) {
        require_once $base_path . '/config/database.php';
    }
    
    // Check if helpers.php exists
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    
    // Check if auth.php exists
    if (file_exists($base_path . '/config/auth.php')) {
        require_once $base_path . '/config/auth.php';
    }
    
    // Check if csrf.php exists
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
    
} catch (Exception $e) {
    die('Error loading system files: ' . $e->getMessage());
}

// Define base_url function if not exists
if (!function_exists('base_url')) {
    function base_url($path = '') {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'];
        $script_name = $_SERVER['SCRIPT_NAME'];
        $dir = dirname(dirname(dirname($script_name)));
        return $protocol . $host . rtrim($dir, '/') . '/' . ltrim($path, '/');
    }
}

// Define escape_html function if not exists
if (!function_exists('escape_html')) {
    function escape_html($string) {
        return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if not exists
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
}

// Define log_message function if not exists
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        $log_file = dirname($base_path) . '/logs/app.log';
        $timestamp = date('Y-m-d H:i:s');
        $log_entry = "[$timestamp] [$level] $message" . PHP_EOL;
        
        // Create logs directory if it doesn't exist
        $log_dir = dirname($log_file);
        if (!is_dir($log_dir)) {
            mkdir($log_dir, 0777, true);
        }
        
        file_put_contents($log_file, $log_entry, FILE_APPEND);
    }
}

// Define set_flash_message function if not exists
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $_SESSION['flash_message'] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if not exists
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . base_url($url));
        exit;
    }
}

// Define begin_transaction function if not exists
if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_begin_transaction')) {
            db_begin_transaction();
        }
    }
}

// Define commit_transaction function if not exists
if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_commit')) {
            db_commit();
        }
    }
}

// Define rollback_transaction function if not exists
if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_rollback')) {
            db_rollback();
        }
    }
}

// Define audit_log function if not exists
if (!function_exists('audit_log')) {
    function audit_log($user_id, $action, $table, $record_id = null, $old_values = null, $new_values = null) {
        try {
            if (function_exists('db_insert')) {
                db_insert('audit_logs', [
                    'user_id' => $user_id,
                    'action' => $action,
                    'table_name' => $table,
                    'record_id' => $record_id,
                    'old_values' => $old_values ? json_encode($old_values) : null,
                    'new_values' => $new_values ? json_encode($new_values) : null,
                    'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
        } catch (Exception $e) {
            log_message("Audit log failed: " . $e->getMessage(), 'ERROR');
        }
    }
}

// Define CSRF constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}

// Require authentication with error handling
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: ' . base_url('login.php'));
        exit;
    }
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('users.roles');
} elseif (function_exists('has_permission')) {
    if (!has_permission('users.roles')) {
        die('Access denied: You do not have permission to manage roles.');
    }
}

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

// Get current user
$current_user = [];
if (function_exists('current_user')) {
    $current_user = current_user();
} elseif (isset($_SESSION)) {
    $current_user = $_SESSION;
}

// Get role ID from URL
$role_id = isset($_GET['role_id']) ? (int)$_GET['role_id'] : 0;

if (!$role_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid role ID');
    }
    if (function_exists('redirect')) {
        redirect('admin/users/roles.php');
    } else {
        header('Location: ' . base_url('admin/users/roles.php'));
        exit;
    }
}

// Get role details with error handling
$role = null;
try {
    if (function_exists('db_fetch_one')) {
        $role = db_fetch_one("SELECT * FROM roles WHERE role_id = ?", [$role_id]);
    }
} catch (Exception $e) {
    log_message("Error fetching role: " . $e->getMessage(), 'ERROR');
    die('Error loading role: ' . $e->getMessage());
}

if (!$role) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Role not found');
    }
    if (function_exists('redirect')) {
        redirect('admin/users/roles.php');
    } else {
        header('Location: ' . base_url('admin/users/roles.php'));
        exit;
    }
}

// Check if role is system role (can still view but with warning)
$is_system = isset($role['is_system']) && $role['is_system'] == 1;

// Get all permissions grouped by module with error handling
$permissions = [];
try {
    if (function_exists('db_fetch_all')) {
        $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) {
    log_message("Error fetching permissions: " . $e->getMessage(), 'ERROR');
}

// 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 current role permissions with error handling
$role_permission_ids = [];
try {
    if (function_exists('db_fetch_all')) {
        $role_permissions = db_fetch_all(
            "SELECT permission_id FROM role_permissions WHERE role_id = ?",
            [$role_id]
        ) ?: [];
        $role_permission_ids = array_column($role_permissions, 'permission_id');
    }
} catch (Exception $e) {
    log_message("Error fetching role permissions: " . $e->getMessage(), 'ERROR');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = false;
    
    if (function_exists('verify_csrf_token')) {
        $csrf_valid = verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '');
    } else {
        // Simple CSRF check
        session_start();
        $csrf_valid = (isset($_POST[CSRF_TOKEN_NAME]) && isset($_SESSION[CSRF_TOKEN_NAME]) && 
                      $_POST[CSRF_TOKEN_NAME] === $_SESSION[CSRF_TOKEN_NAME]);
    }
    
    if (!$csrf_valid) {
        $error = 'Invalid security token. Please try again.';
    } else {
        // Check if role is system
        if ($is_system) {
            $error = 'System role permissions cannot be modified';
        } else {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Get submitted permissions
                $submitted_permissions = isset($_POST['permissions']) ? $_POST['permissions'] : [];
                $submitted_permissions = array_map('intval', $submitted_permissions);
                
                // Get current permissions
                $current_ids = $role_permission_ids;
                
                // Calculate changes
                $to_add = array_diff($submitted_permissions, $current_ids);
                $to_remove = array_diff($current_ids, $submitted_permissions);
                
                // Add new permissions
                foreach ($to_add as $perm_id) {
                    if (function_exists('db_insert')) {
                        db_insert('role_permissions', [
                            'role_id' => $role_id,
                            'permission_id' => $perm_id,
                            'granted_by' => $current_user['user_id'] ?? 0
                        ]);
                    }
                }
                
                // Remove permissions
                if (!empty($to_remove) && function_exists('db_query')) {
                    $placeholders = implode(',', array_fill(0, count($to_remove), '?'));
                    $params = array_merge([$role_id], $to_remove);
                    db_query(
                        "DELETE FROM role_permissions WHERE role_id = ? AND permission_id IN ($placeholders)",
                        $params
                    );
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($current_user['user_id'] ?? 0, 'permissions_update', 'roles', $role_id, [
                        'old_permissions' => $current_ids,
                        'new_permissions' => $submitted_permissions
                    ]);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                $message = 'Permissions updated successfully';
                
                // Refresh role permissions
                try {
                    if (function_exists('db_fetch_all')) {
                        $role_permissions = db_fetch_all(
                            "SELECT permission_id FROM role_permissions WHERE role_id = ?",
                            [$role_id]
                        ) ?: [];
                        $role_permission_ids = array_column($role_permissions, 'permission_id');
                    }
                } catch (Exception $e) {
                    log_message("Error refreshing permissions: " . $e->getMessage(), 'ERROR');
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $error = 'Failed to update permissions: ' . $e->getMessage();
                log_message("Permissions update failed: " . $e->getMessage(), 'ERROR');
            }
        }
    }
}

// Include header with error handling
$header_file = $base_path . '/views/partials/header.php';
if (file_exists($header_file)) {
    require_once $header_file;
} else {
    // Fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?php echo $page_title; ?></title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
        <style>
            .content-header { padding: 20px; background: #f4f6f9; }
            .card { box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2); margin-bottom: 20px; }
            .custom-control-label small { display: block; font-size: 11px; color: #6c757d; }
            .card-secondary .card-header { background-color: #6c757d; color: white; }
            .card-secondary .card-header .btn-sm { color: white; border-color: white; }
            .card-secondary .card-header .btn-sm:hover { background-color: white; color: #6c757d; }
            #selectedCount { font-weight: bold; }
        </style>
    </head>
    <body>
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Permissions: <?php echo escape_html($role['role_name'] ?? ''); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/dashboard.php'); ?>">Admin</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/users/index.php'); ?>">Users</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/users/roles.php'); ?>">Roles</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 mr-2"></i>
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo $error; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>

        <!-- System Role Warning -->
        <?php if ($is_system): ?>
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle mr-2"></i>
                <strong>System Role:</strong> This is a system role and its permissions cannot be modified.
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-key mr-1"></i>
                            Manage Permissions
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-info" id="selectAll">
                                <i class="fas fa-check-double mr-1"></i> Select All
                            </button>
                            <button type="button" class="btn btn-sm btn-secondary" id="deselectAll">
                                <i class="fas fa-times mr-1"></i> Deselect All
                            </button>
                        </div>
                    </div>
                    
                    <form method="POST" id="permissionsForm">
                        <?php 
                        if (function_exists('csrf_field')) {
                            echo csrf_field();
                        } else {
                            // Simple CSRF field
                            $csrf_token = bin2hex(random_bytes(32));
                            session_start();
                            $_SESSION[CSRF_TOKEN_NAME] = $csrf_token;
                            echo '<input type="hidden" name="' . CSRF_TOKEN_NAME . '" value="' . $csrf_token . '">';
                        }
                        ?>
                        
                        <div class="card-body">
                            <?php if (empty($grouped_permissions)): ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle mr-2"></i>
                                    No permissions found in the system.
                                </div>
                            <?php else: ?>
                                <?php foreach ($grouped_permissions as $module => $perms): ?>
                                    <div class="card card-secondary mb-3">
                                        <div class="card-header">
                                            <h3 class="card-title">
                                                <i class="fas fa-cube mr-1"></i>
                                                <?php echo ucfirst($module); ?> Module
                                            </h3>
                                            <div class="card-tools">
                                                <button type="button" class="btn btn-sm btn-info select-module" data-module="<?php echo $module; ?>">
                                                    Select All
                                                </button>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <?php foreach ($perms as $perm): ?>
                                                    <div class="col-md-4 col-sm-6">
                                                        <div class="form-group">
                                                            <div class="custom-control custom-checkbox">
                                                                <input type="checkbox" 
                                                                       class="custom-control-input permission-checkbox module-<?php echo preg_replace('/[^a-z0-9]/', '', strtolower($module)); ?>"
                                                                       id="perm_<?php echo $perm['permission_id'] ?? 0; ?>" 
                                                                       name="permissions[]" 
                                                                       value="<?php echo $perm['permission_id'] ?? 0; ?>"
                                                                       <?php echo in_array($perm['permission_id'] ?? 0, $role_permission_ids) ? 'checked' : ''; ?>
                                                                       <?php echo $is_system ? 'disabled' : ''; ?>>
                                                                <label class="custom-control-label" for="perm_<?php echo $perm['permission_id'] ?? 0; ?>">
                                                                    <?php echo escape_html($perm['permission_name'] ?? ''); ?>
                                                                    <br>
                                                                    <small class="text-muted"><?php echo escape_html($perm['permission_key'] ?? ''); ?></small>
                                                                </label>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        
                        <?php if (!$is_system && !empty($grouped_permissions)): ?>
                            <div class="card-footer">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save mr-1"></i> Save Permissions
                                </button>
                                <a href="<?php echo base_url('admin/users/roles.php'); ?>" class="btn btn-secondary">
                                    <i class="fas fa-times mr-1"></i> Cancel
                                </a>
                            </div>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Selected Count Display -->
<div style="position: fixed; bottom: 20px; right: 20px; z-index: 1000;">
    <div class="card card-info">
        <div class="card-body py-2 px-3">
            <span id="selectedCount" class="text-white">0 of 0 selected</span>
        </div>
    </div>
</div>

<!-- Include jQuery and Bootstrap -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
$(document).ready(function() {
    // Select all permissions
    $('#selectAll').click(function() {
        $('.permission-checkbox:not(:disabled)').prop('checked', true);
        updateSelectedCount();
    });
    
    // Deselect all permissions
    $('#deselectAll').click(function() {
        $('.permission-checkbox:not(:disabled)').prop('checked', false);
        updateSelectedCount();
    });
    
    // Select module permissions
    $('.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 + ' selected');
    }
    
    // Initial count
    updateSelectedCount();
    
    // Form validation
    $('#permissionsForm').submit(function(e) {
        var checked = $('.permission-checkbox:checked:not(:disabled)').length;
        if (checked === 0) {
            if (!confirm('No permissions selected. This role will have no access. Continue?')) {
                e.preventDefault();
            }
        }
    });
});
</script>

<?php
// Include footer with error handling
$footer_file = $base_path . '/views/partials/footer.php';
if (file_exists($footer_file)) {
    require_once $footer_file;
} else {
    echo '</body></html>';
}
?>