<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * User Management - List Users
 * 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/index.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__ . '/../..';
}

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

// Method 8: Try to find config by traversing up until we find it
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;
        }
    }
}

// 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 constants if not defined
if (!defined('ITEMS_PER_PAGE')) {
    define('ITEMS_PER_PAGE', 20);
}

// 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 = 'M d, Y') {
        if (empty($date)) return 'N/A';
        $timestamp = strtotime($date);
        return $timestamp ? date($format, $timestamp) : 'N/A';
    }
}

// Define time_ago function if not exists
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        if (empty($datetime)) return 'Never';
        
        $timestamp = strtotime($datetime);
        if (!$timestamp) return 'Invalid date';
        
        $diff = time() - $timestamp;
        
        if ($diff < 60) return $diff . ' seconds ago';
        if ($diff < 3600) return round($diff / 60) . ' minutes ago';
        if ($diff < 86400) return round($diff / 3600) . ' hours ago';
        if ($diff < 2592000) return round($diff / 86400) . ' days ago';
        
        return date('M j, Y', $timestamp);
    }
}

// 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 db_paginate function if not exists
if (!function_exists('db_paginate')) {
    function db_paginate($table, $columns = '*', $where = '1=1', $params = [], $order_by = 'user_id DESC', $page = 1, $per_page = 20) {
        try {
            // Get total count
            $count_sql = "SELECT COUNT(*) as total FROM $table WHERE $where";
            $count_result = db_fetch_one($count_sql, $params);
            $total = $count_result['total'] ?? 0;
            
            // Calculate pagination
            $offset = ($page - 1) * $per_page;
            $total_pages = ceil($total / $per_page);
            
            // Get data for current page
            $data_sql = "SELECT $columns FROM $table WHERE $where ORDER BY $order_by LIMIT ? OFFSET ?";
            $data_params = array_merge($params, [$per_page, $offset]);
            $data = db_fetch_all($data_sql, $data_params) ?: [];
            
            return [
                'data' => $data,
                'total' => $total,
                'current_page' => $page,
                'total_pages' => $total_pages,
                'per_page' => $per_page,
                'has_previous' => $page > 1,
                'has_next' => $page < $total_pages,
                'previous_page' => $page - 1,
                'next_page' => $page + 1
            ];
        } catch (Exception $e) {
            log_message("Pagination error: " . $e->getMessage(), 'ERROR');
            return [
                'data' => [],
                'total' => 0,
                'current_page' => 1,
                'total_pages' => 1,
                'per_page' => $per_page,
                'has_previous' => false,
                'has_next' => false,
                'previous_page' => 1,
                'next_page' => 1
            ];
        }
    }
}

// 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.view');
} elseif (function_exists('has_permission')) {
    if (!has_permission('users.view')) {
        die('Access denied: You do not have permission to view users.');
    }
}

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

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

// Handle bulk actions
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    // Check edit permission
    if (function_exists('has_permission')) {
        if (!has_permission('users.edit')) {
            $error = 'You do not have permission to perform bulk actions';
        }
    }
    
    if (empty($error)) {
        // 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 {
            $action = $_POST['bulk_action'];
            $user_ids = $_POST['user_ids'] ?? [];
            
            if (empty($user_ids)) {
                $error = 'Please select at least one user';
            } else {
                // Filter out disabled checkboxes (own user)
                $user_ids = array_filter($user_ids, function($id) use ($current_user) {
                    return $id != ($current_user['user_id'] ?? 0);
                });
                
                if (empty($user_ids)) {
                    $error = 'No valid users selected for bulk action';
                } else {
                    $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
                    
                    try {
                        switch ($action) {
                            case 'activate':
                                if (function_exists('db_query')) {
                                    db_query("UPDATE users SET is_active = 1 WHERE user_id IN ($placeholders)", $user_ids);
                                    $message = count($user_ids) . ' user(s) activated successfully';
                                }
                                break;
                                
                            case 'deactivate':
                                // Don't allow deactivating yourself (already filtered)
                                if (function_exists('db_query')) {
                                    db_query("UPDATE users SET is_active = 0 WHERE user_id IN ($placeholders)", $user_ids);
                                    $message = count($user_ids) . ' user(s) deactivated successfully';
                                }
                                break;
                                
                            case 'delete':
                                // Check if users have any related records
                                $has_relations = 0;
                                if (function_exists('db_fetch_value')) {
                                    $has_relations = db_fetch_value("
                                        SELECT COUNT(*) FROM users 
                                        WHERE user_id IN ($placeholders) 
                                        AND (user_id IN (SELECT created_by FROM reservations) 
                                             OR user_id IN (SELECT posted_by FROM folio_charges)
                                             OR user_id IN (SELECT user_id FROM pos_sales))
                                    ", $user_ids);
                                }
                                
                                if ($has_relations > 0) {
                                    $error = 'Some users have related records and cannot be deleted. Consider deactivating them instead.';
                                } else {
                                    if (function_exists('db_query')) {
                                        db_query("DELETE FROM users WHERE user_id IN ($placeholders)", $user_ids);
                                        $message = count($user_ids) . ' user(s) deleted successfully';
                                    }
                                }
                                break;
                        }
                        
                        // Audit log
                        if (!empty($message) && function_exists('audit_log')) {
                            audit_log($current_user['user_id'] ?? 0, 'bulk_' . $action, 'users', null, null, ['user_ids' => $user_ids]);
                        }
                    } catch (Exception $e) {
                        $error = 'Error performing bulk action: ' . $e->getMessage();
                        log_message("Bulk action error: " . $e->getMessage(), 'ERROR');
                    }
                }
            }
        }
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$role_id = isset($_GET['role_id']) && $_GET['role_id'] !== '' ? (int)$_GET['role_id'] : null;
$status = $_GET['status'] ?? '';
$sort = $_GET['sort'] ?? 'user_id';
$order = $_GET['order'] ?? 'DESC';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = defined('ITEMS_PER_PAGE') ? ITEMS_PER_PAGE : 20;

// Build where clause
$where = "1=1";
$params = [];

if (!empty($search)) {
    $where .= " AND (username LIKE ? OR email LIKE ? OR first_name LIKE ? OR last_name LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term]);
}

if ($role_id !== null) {
    $where .= " AND role_id = ?";
    $params[] = $role_id;
}

if ($status === 'active') {
    $where .= " AND is_active = 1";
} elseif ($status === 'inactive') {
    $where .= " AND is_active = 0";
}

// Validate sort column
$allowed_sort = ['user_id', 'username', 'email', 'first_name', 'last_name', 'role_id', 'is_active', 'last_login', 'created_at'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'user_id';
}

// Get users with pagination
$users = [
    'data' => [],
    'total' => 0,
    'current_page' => $page,
    'total_pages' => 1,
    'has_previous' => false,
    'has_next' => false,
    'previous_page' => 1,
    'next_page' => 1
];

try {
    if (function_exists('db_paginate')) {
        $users = db_paginate(
            'users',
            '*',
            $where,
            $params,
            "$sort $order",
            $page,
            $per_page
        );
    }
} catch (Exception $e) {
    $error = 'Error loading users: ' . $e->getMessage();
    log_message("Error loading users: " . $e->getMessage(), 'ERROR');
}

// Get all roles for filter
$roles = [];
try {
    if (function_exists('db_fetch_all')) {
        $roles = db_fetch_all("SELECT role_id, role_name FROM roles ORDER BY role_name") ?: [];
    }
} catch (Exception $e) {
    log_message("Error loading roles: " . $e->getMessage(), 'ERROR');
}

// Get role names mapping
$role_names = [];
foreach ($roles as $role) {
    $role_names[$role['role_id'] ?? 0] = $role['role_name'] ?? 'Unknown';
}

// 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; }
            .pagination { margin-bottom: 0; }
        </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">User 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 active">Users</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; ?>

        <!-- Filters and Actions -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter mr-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="form-inline">
                    <div class="form-group mb-2 mr-2">
                        <input type="text" class="form-control" name="search" placeholder="Search users..." 
                               value="<?php echo escape_html($search); ?>" style="min-width: 250px;">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="role_id">
                            <option value="">All Roles</option>
                            <?php foreach ($roles as $role): ?>
                                <option value="<?php echo $role['role_id'] ?? ''; ?>" <?php echo $role_id == ($role['role_id'] ?? '') ? 'selected' : ''; ?>>
                                    <?php echo escape_html($role['role_name'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="status">
                            <option value="">All Status</option>
                            <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary mb-2 mr-2">
                        <i class="fas fa-search mr-1"></i> Apply Filters
                    </button>
                    
                    <a href="<?php echo base_url('admin/users/index.php'); ?>" class="btn btn-secondary mb-2">
                        <i class="fas fa-times mr-1"></i> Clear
                    </a>
                </form>
            </div>
        </div>

        <!-- Users Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-users mr-1"></i>
                    Users (<?php echo $users['total'] ?? 0; ?> total)
                </h3>
                <div class="card-tools">
                    <?php if (function_exists('has_permission') && has_permission('users.create')): ?>
                        <a href="<?php echo base_url('/create.php'); ?>" class="btn btn-sm btn-primary">
                            <i class="fas fa-plus"></i> Add User
                        </a>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($users['data'])): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-users-slash fa-4x mb-3"></i>
                        <h5>No users found</h5>
                        <p>Try adjusting your filters or create a new user</p>
                        <?php if (function_exists('has_permission') && has_permission('users.create')): ?>
                            <a href="<?php echo base_url('admin/users/create.php'); ?>" class="btn btn-primary">
                                <i class="fas fa-plus mr-1"></i> Add User
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <form method="POST" id="bulkActionForm">
                        <?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 . '">';
                        }
                        ?>
                        <input type="hidden" name="bulk_action" id="bulkAction" value="">
                        
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th width="30">
                                            <input type="checkbox" id="selectAll">
                                        </th>
                                        <th>
                                            <a href="?sort=user_id&order=<?php echo $sort === 'user_id' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&role_id=<?php echo $role_id; ?>&status=<?php echo $status; ?>">
                                                ID
                                                <?php if ($sort === 'user_id'): ?>
                                                    <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                                <?php endif; ?>
                                            </a>
                                        </th>
                                        <th>
                                            <a href="?sort=username&order=<?php echo $sort === 'username' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&role_id=<?php echo $role_id; ?>&status=<?php echo $status; ?>">
                                                Username
                                                <?php if ($sort === 'username'): ?>
                                                    <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                                <?php endif; ?>
                                            </a>
                                        </th>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Role</th>
                                        <th>Status</th>
                                        <th>Last Login</th>
                                        <th>Created</th>
                                        <th width="150">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($users['data'] as $user): ?>
                                    <tr>
                                        <td>
                                            <input type="checkbox" name="user_ids[]" value="<?php echo $user['user_id'] ?? ''; ?>" 
                                                   <?php echo ($user['user_id'] ?? 0) == ($current_user['user_id'] ?? 0) ? 'disabled' : ''; ?>>
                                        </td>
                                        <td><?php echo $user['user_id'] ?? ''; ?></td>
                                        <td><?php echo escape_html($user['username'] ?? ''); ?></td>
                                        <td><?php echo escape_html(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')); ?></td>
                                        <td><?php echo escape_html($user['email'] ?? ''); ?></td>
                                        <td>
                                            <span class="badge badge-info">
                                                <?php echo escape_html($role_names[$user['role_id'] ?? 0] ?? 'Unknown'); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if (!empty($user['is_active'])): ?>
                                                <span class="badge badge-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge badge-danger">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php echo !empty($user['last_login']) ? time_ago($user['last_login']) : 'Never'; ?>
                                        </td>
                                        <td><?php echo !empty($user['created_at']) ? format_date($user['created_at'], 'M d, Y') : 'N/A'; ?></td>
                                        <td>
                                            <div class="btn-group">
                                                <a href="<?php echo base_url('admin/users/view.php?id=' . ($user['user_id'] ?? 0)); ?>" 
                                                   class="btn btn-sm btn-info" title="View">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                
                                                <?php if (function_exists('has_permission') && has_permission('users.edit')): ?>
                                                    <a href="<?php echo base_url('admin/users/edit.php?id=' . ($user['user_id'] ?? 0)); ?>" 
                                                       class="btn btn-sm btn-primary" title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                <?php endif; ?>
                                                
                                                <?php if (function_exists('has_permission') && has_permission('users.edit') && ($user['user_id'] ?? 0) != ($current_user['user_id'] ?? 0)): ?>
                                                    <button type="button" class="btn btn-sm btn-warning" 
                                                            onclick="resetPassword(<?php echo $user['user_id'] ?? 0; ?>)"
                                                            title="Reset Password">
                                                        <i class="fas fa-key"></i>
                                                    </button>
                                                <?php endif; ?>
                                                
                                                <?php if (function_exists('has_permission') && has_permission('users.delete') && ($user['user_id'] ?? 0) != ($current_user['user_id'] ?? 0)): ?>
                                                    <button type="button" class="btn btn-sm btn-danger" 
                                                            onclick="deleteUser(<?php echo $user['user_id'] ?? 0; ?>, '<?php echo escape_html($user['username'] ?? ''); ?>')"
                                                            title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Bulk Actions -->
                        <div class="card-footer clearfix">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="btn-group">
                                        <select class="form-control form-control-sm" id="bulkActionSelect" style="width: auto;">
                                            <option value="">Bulk Actions</option>
                                            <option value="activate">Activate</option>
                                            <option value="deactivate">Deactivate</option>
                                            <?php if (function_exists('has_permission') && has_permission('users.delete')): ?>
                                                <option value="delete">Delete</option>
                                            <?php endif; ?>
                                        </select>
                                        <button type="button" class="btn btn-sm btn-primary" onclick="executeBulkAction()">
                                            Apply
                                        </button>
                                    </div>
                                    <span class="text-muted ml-2" id="selectedCount">0 selected</span>
                                </div>
                                
                                <div class="col-md-6">
                                    <?php if (($users['total_pages'] ?? 1) > 1): ?>
                                        <ul class="pagination pagination-sm m-0 float-right">
                                            <?php if (!empty($users['has_previous'])): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $users['previous_page'] ?? 1; ?>&search=<?php echo urlencode($search); ?>&role_id=<?php echo $role_id; ?>&status=<?php echo $status; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                                        <i class="fas fa-chevron-left"></i>
                                                    </a>
                                                </li>
                                            <?php endif; ?>
                                            
                                            <?php
                                            $current_page = $users['current_page'] ?? 1;
                                            $total_pages = $users['total_pages'] ?? 1;
                                            $start = max(1, $current_page - 2);
                                            $end = min($total_pages, $current_page + 2);
                                            
                                            for ($i = $start; $i <= $end; $i++):
                                            ?>
                                                <li class="page-item <?php echo $i == $current_page ? 'active' : ''; ?>">
                                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&role_id=<?php echo $role_id; ?>&status=<?php echo $status; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                                        <?php echo $i; ?>
                                                    </a>
                                                </li>
                                            <?php endfor; ?>
                                            
                                            <?php if (!empty($users['has_next'])): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $users['next_page'] ?? 1; ?>&search=<?php echo urlencode($search); ?>&role_id=<?php echo $role_id; ?>&status=<?php echo $status; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                                        <i class="fas fa-chevron-right"></i>
                                                    </a>
                                                </li>
                                            <?php endif; ?>
                                        </ul>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" 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 user <strong id="deleteUsername"></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" action="<?php echo base_url('admin/users/delete.php'); ?>" id="deleteForm">
                    <?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 . '">';
                    }
                    ?>
                    <input type="hidden" name="user_id" id="deleteUserId">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Reset Password Modal -->
<div class="modal fade" id="resetPasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">Reset Password</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 reset password for <strong id="resetUsername"></strong>?</p>
                <p>A password reset link will be sent to the user's email.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" action="<?php echo base_url('admin/users/reset-password.php'); ?>" id="resetForm">
                    <?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 . '">';
                    }
                    ?>
                    <input type="hidden" name="user_id" id="resetUserId">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning">Send Reset Link</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>
$(document).ready(function() {
    // Select all checkbox
    $('#selectAll').on('change', function() {
        $('input[name="user_ids[]"]:not(:disabled)').prop('checked', $(this).prop('checked'));
        updateSelectedCount();
    });
    
    // Individual checkboxes
    $('input[name="user_ids[]"]').on('change', function() {
        updateSelectedCount();
        updateSelectAll();
    });
    
    // Update selected count
    function updateSelectedCount() {
        const count = $('input[name="user_ids[]"]:checked').length;
        $('#selectedCount').text(count + ' selected');
    }
    
    // Update select all checkbox
    function updateSelectAll() {
        const total = $('input[name="user_ids[]"]:not(:disabled)').length;
        const checked = $('input[name="user_ids[]"]:checked').length;
        $('#selectAll').prop('checked', total > 0 && checked === total);
    }
    
    // Initial count
    updateSelectedCount();
});

function executeBulkAction() {
    const action = $('#bulkActionSelect').val();
    const selected = $('input[name="user_ids[]"]:checked').length;
    
    if (!action) {
        alert('Please select an action');
        return;
    }
    
    if (selected === 0) {
        alert('Please select at least one user');
        return;
    }
    
    let confirmMessage = '';
    switch(action) {
        case 'activate':
            confirmMessage = 'Activate ' + selected + ' user(s)?';
            break;
        case 'deactivate':
            confirmMessage = 'Deactivate ' + selected + ' user(s)?';
            break;
        case 'delete':
            confirmMessage = 'Delete ' + selected + ' user(s)? This action cannot be undone.';
            break;
    }
    
    if (confirm(confirmMessage)) {
        $('#bulkAction').val(action);
        $('#bulkActionForm').submit();
    }
}

function deleteUser(userId, username) {
    $('#deleteUserId').val(userId);
    $('#deleteUsername').text(username);
    $('#deleteModal').modal('show');
}

function resetPassword(userId) {
    // Get username via AJAX
    $.get('<?php echo base_url('api/get-user.php'); ?>', { id: userId }, function(response) {
        if (response && response.status === 'success') {
            $('#resetUserId').val(userId);
            $('#resetUsername').text(response.data.username);
            $('#resetPasswordModal').modal('show');
        } else {
            alert('Error loading user data');
        }
    }).fail(function() {
        alert('Failed to load user data');
    });
}
</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>';
}
?>