<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Role 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/roles.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: Last resort - try parent of parent of current directory
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = __DIR__ . '/../..';
}

// Verify config file exists
if (!file_exists($base_path . '/config/config.php')) {
    die('Critical Error: Cannot locate config.php. Please check file paths. Base path: ' . $base_path);
}

// 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 format_date function if not exists
if (!function_exists('format_date')) {
    function format_date($date, $format = 'Y-m-d H:i:s') {
        if (empty($date)) return 'N/A';
        $timestamp = strtotime($date);
        return $timestamp ? date($format, $timestamp) : 'N/A';
    }
}

// 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 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');
}

// Define audit constants if not defined
if (!defined('AUDIT_CREATE')) {
    define('AUDIT_CREATE', 'create');
    define('AUDIT_UPDATE', 'update');
    define('AUDIT_DELETE', 'delete');
}

// 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 Management';

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

// Handle actions with error handling
$message = '';
$error = '';

// Create/Edit Role
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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 {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'create':
                $role_name = isset($_POST['role_name']) ? sanitize_input($_POST['role_name']) : '';
                $role_description = isset($_POST['role_description']) ? sanitize_input($_POST['role_description']) : '';
                
                if (empty($role_name)) {
                    $error = 'Role name is required';
                } else {
                    try {
                        // Check if role exists
                        $exists = 0;
                        if (function_exists('db_fetch_value')) {
                            $exists = db_fetch_value("SELECT COUNT(*) FROM roles WHERE role_name = ?", [$role_name]);
                        }
                        
                        if ($exists) {
                            $error = 'Role name already exists';
                        } else {
                            if (function_exists('db_insert')) {
                                $role_id = db_insert('roles', [
                                    'role_name' => $role_name,
                                    'role_description' => $role_description,
                                    'is_system' => 0,
                                    'created_at' => date('Y-m-d H:i:s')
                                ]);
                                
                                if ($role_id) {
                                    // Audit log
                                    $user_id = $current_user['user_id'] ?? 0;
                                    audit_log($user_id, AUDIT_CREATE ?? 'create', 'roles', $role_id, null, $_POST);
                                    $message = 'Role created successfully';
                                } else {
                                    $error = 'Failed to create role';
                                }
                            } else {
                                $error = 'Database insert function not available';
                            }
                        }
                    } catch (Exception $e) {
                        $error = 'Failed to create role: ' . $e->getMessage();
                        log_message("Role creation failed: " . $e->getMessage(), 'ERROR');
                    }
                }
                break;
                
            case 'edit':
                $role_id = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
                $role_name = isset($_POST['role_name']) ? sanitize_input($_POST['role_name']) : '';
                $role_description = isset($_POST['role_description']) ? sanitize_input($_POST['role_description']) : '';
                
                if (!$role_id) {
                    $error = 'Invalid role ID';
                } elseif (empty($role_name)) {
                    $error = 'Role name is required';
                } else {
                    try {
                        // Check if role is system role
                        $is_system = 0;
                        if (function_exists('db_fetch_value')) {
                            $is_system = db_fetch_value("SELECT is_system FROM roles WHERE role_id = ?", [$role_id]);
                        }
                        
                        if ($is_system) {
                            $error = 'System roles cannot be edited';
                        } else {
                            // Check if name exists for another role
                            $exists = 0;
                            if (function_exists('db_fetch_value')) {
                                $exists = db_fetch_value("SELECT COUNT(*) FROM roles WHERE role_name = ? AND role_id != ?", 
                                                        [$role_name, $role_id]);
                            }
                            
                            if ($exists) {
                                $error = 'Role name already exists';
                            } else {
                                // Get old values for audit
                                $old_values = [];
                                if (function_exists('db_fetch_one')) {
                                    $old_values = db_fetch_one("SELECT * FROM roles WHERE role_id = ?", [$role_id]);
                                }
                                
                                if (function_exists('db_update')) {
                                    $result = db_update('roles', [
                                        'role_name' => $role_name,
                                        'role_description' => $role_description
                                    ], 'role_id = ?', [$role_id]);
                                    
                                    if ($result !== false) {
                                        $user_id = $current_user['user_id'] ?? 0;
                                        audit_log($user_id, AUDIT_UPDATE ?? 'update', 'roles', $role_id, $old_values, $_POST);
                                        $message = 'Role updated successfully';
                                        
                                        // Redirect to clear edit mode
                                        header('Location: ' . base_url('admin/users/roles.php?success=1'));
                                        exit;
                                    } else {
                                        $error = 'Failed to update role';
                                    }
                                } else {
                                    $error = 'Database update function not available';
                                }
                            }
                        }
                    } catch (Exception $e) {
                        $error = 'Failed to update role: ' . $e->getMessage();
                        log_message("Role update failed: " . $e->getMessage(), 'ERROR');
                    }
                }
                break;
                
            case 'delete':
                $role_id = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
                
                if (!$role_id) {
                    $error = 'Invalid role ID';
                } else {
                    try {
                        // Check if role is system role
                        $is_system = 0;
                        if (function_exists('db_fetch_value')) {
                            $is_system = db_fetch_value("SELECT is_system FROM roles WHERE role_id = ?", [$role_id]);
                        }
                        
                        if ($is_system) {
                            $error = 'System roles cannot be deleted';
                        } else {
                            // Check if role has users
                            $user_count = 0;
                            if (function_exists('db_fetch_value')) {
                                $user_count = db_fetch_value("SELECT COUNT(*) FROM users WHERE role_id = ?", [$role_id]);
                            }
                            
                            if ($user_count > 0) {
                                $error = 'Cannot delete role that has users assigned';
                            } else {
                                // Delete role permissions first
                                if (function_exists('db_delete')) {
                                    db_delete('role_permissions', 'role_id = ?', [$role_id]);
                                    
                                    // Delete role
                                    db_delete('roles', 'role_id = ?', [$role_id]);
                                    
                                    $user_id = $current_user['user_id'] ?? 0;
                                    audit_log($user_id, AUDIT_DELETE ?? 'delete', 'roles', $role_id);
                                    $message = 'Role deleted successfully';
                                } else {
                                    $error = 'Database delete function not available';
                                }
                            }
                        }
                    } catch (Exception $e) {
                        $error = 'Failed to delete role: ' . $e->getMessage();
                        log_message("Role deletion failed: " . $e->getMessage(), 'ERROR');
                    }
                }
                break;
        }
    }
}

// Check for success message from redirect
if (isset($_GET['success']) && $_GET['success'] == 1) {
    $message = 'Role updated successfully';
}

// Get all roles with error handling
$roles = [];
try {
    if (function_exists('db_fetch_all')) {
        $roles = db_fetch_all("
            SELECT r.*, COUNT(u.user_id) as user_count 
            FROM roles r
            LEFT JOIN users u ON r.role_id = u.role_id
            GROUP BY r.role_id
            ORDER BY r.is_system DESC, r.role_name
        ") ?: [];
    }
} catch (Exception $e) {
    $error = 'Error loading roles: ' . $e->getMessage();
    log_message("Error loading roles: " . $e->getMessage(), 'ERROR');
}

// Get role to edit (if any)
$edit_role = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    try {
        if (function_exists('db_fetch_one')) {
            $edit_role = db_fetch_one("SELECT * FROM roles WHERE role_id = ? AND is_system = 0", [$edit_id]);
        }
    } catch (Exception $e) {
        $error = 'Error loading role: ' . $e->getMessage();
        log_message("Error loading role for edit: " . $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; }
        </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">Role Management</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 active">Roles</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; ?>

        <div class="row">
            <!-- Role List -->
            <div class="col-md-<?php echo $edit_role ? '7' : '12'; ?>">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-tags mr-1"></i>
                            Roles
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#createRoleModal">
                                <i class="fas fa-plus"></i> New Role
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Role Name</th>
                                        <th>Description</th>
                                        <th>Users</th>
                                        <th>Type</th>
                                        <th>Created</th>
                                        <th width="150">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($roles)): ?>
                                        <tr>
                                            <td colspan="7" class="text-center text-muted">
                                                <i class="fas fa-info-circle mr-1"></i> No roles found
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($roles as $role): ?>
                                        <tr>
                                            <td><?php echo $role['role_id'] ?? ''; ?></td>
                                            <td>
                                                <strong><?php echo escape_html($role['role_name'] ?? ''); ?></strong>
                                            </td>
                                            <td><?php echo escape_html($role['role_description'] ?? ''); ?></td>
                                            <td>
                                                <span class="badge badge-info"><?php echo $role['user_count'] ?? 0; ?></span>
                                            </td>
                                            <td>
                                                <?php if (!empty($role['is_system'])): ?>
                                                    <span class="badge badge-danger">System</span>
                                                <?php else: ?>
                                                    <span class="badge badge-success">Custom</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo format_date($role['created_at'] ?? '', 'M d, Y'); ?></td>
                                            <td>
                                                <div class="btn-group">
                                                    <a href="<?php echo base_url('admin/users/permissions.php?role_id=' . ($role['role_id'] ?? '')); ?>" 
                                                       class="btn btn-sm btn-info" title="Manage Permissions">
                                                        <i class="fas fa-key"></i>
                                                    </a>
                                                    
                                                    <?php if (empty($role['is_system'])): ?>
                                                        <a href="?edit=<?php echo $role['role_id'] ?? ''; ?>" class="btn btn-sm btn-warning" title="Edit">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        
                                                        <?php if (($role['user_count'] ?? 0) == 0): ?>
                                                            <button type="button" class="btn btn-sm btn-danger" 
                                                                    onclick="deleteRole(<?php echo $role['role_id'] ?? 0; ?>, '<?php echo escape_html($role['role_name'] ?? ''); ?>')"
                                                                    title="Delete">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Edit Role Form -->
            <?php if ($edit_role): ?>
            <div class="col-md-5">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit mr-1"></i>
                            Edit Role: <?php echo escape_html($edit_role['role_name'] ?? ''); ?>
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php 
                        if (function_exists('csrf_field')) {
                            echo csrf_field();
                        } else {
                            // Simple CSRF field
                            $csrf_token = bin2hex(random_bytes(32));
                            $_SESSION[CSRF_TOKEN_NAME] = $csrf_token;
                            echo '<input type="hidden" name="' . CSRF_TOKEN_NAME . '" value="' . $csrf_token . '">';
                        }
                        ?>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="role_id" value="<?php echo $edit_role['role_id'] ?? 0; ?>">
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="role_name">Role Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="role_name" name="role_name" 
                                       value="<?php echo escape_html($edit_role['role_name'] ?? ''); ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="role_description">Description</label>
                                <textarea class="form-control" id="role_description" name="role_description" rows="3"><?php echo escape_html($edit_role['role_description'] ?? ''); ?></textarea>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save mr-1"></i> Update Role
                            </button>
                            <a href="?" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Create Role Modal -->
<div class="modal fade" id="createRoleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h5 class="modal-title">Create New Role</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            
            <form method="POST">
                <?php 
                if (function_exists('csrf_field')) {
                    echo csrf_field();
                } else {
                    // Simple CSRF field
                    $csrf_token = bin2hex(random_bytes(32));
                    $_SESSION[CSRF_TOKEN_NAME] = $csrf_token;
                    echo '<input type="hidden" name="' . CSRF_TOKEN_NAME . '" value="' . $csrf_token . '">';
                }
                ?>
                <input type="hidden" name="action" value="create">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label for="new_role_name">Role Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="new_role_name" name="role_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="new_role_description">Description</label>
                        <textarea class="form-control" id="new_role_description" name="role_description" rows="3"></textarea>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Role</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Role Modal -->
<div class="modal fade" id="deleteRoleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Confirm Delete</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete role <strong id="deleteRoleName"></strong>?</p>
                <p class="text-danger"><i class="fas fa-exclamation-triangle mr-1"></i> This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteRoleForm">
                    <?php 
                    if (function_exists('csrf_field')) {
                        echo csrf_field();
                    } else {
                        // Simple CSRF field
                        $csrf_token = bin2hex(random_bytes(32));
                        $_SESSION[CSRF_TOKEN_NAME] = $csrf_token;
                        echo '<input type="hidden" name="' . CSRF_TOKEN_NAME . '" value="' . $csrf_token . '">';
                    }
                    ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="role_id" id="deleteRoleId">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete Role</button>
                </form>
            </div>
        </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>
function deleteRole(roleId, roleName) {
    $('#deleteRoleId').val(roleId);
    $('#deleteRoleName').text(roleName);
    $('#deleteRoleModal').modal('show');
}

// Auto-show create modal if there are errors in create form
<?php if ($error && strpos($error, 'create') !== false): ?>
    $(document).ready(function() {
        $('#createRoleModal').modal('show');
    });
<?php endif; ?>
</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>';
}
?>