<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * View User Details
 * 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
$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;
        }
    }
}

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

// Initialize system with proper error handling
try {
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/constants.php';
    require_once $base_path . '/config/database.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    
    if (file_exists($base_path . '/config/auth.php')) {
        require_once $base_path . '/config/auth.php';
    }
    
    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 format_datetime function if not exists
if (!function_exists('format_datetime')) {
    function format_datetime($datetime) {
        if (empty($datetime)) return 'N/A';
        $timestamp = strtotime($datetime);
        return $timestamp ? date('Y-m-d H:i:s', $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 uploads_url function if not exists
if (!function_exists('uploads_url')) {
    function uploads_url($path = '') {
        return base_url('uploads/' . ltrim($path, '/'));
    }
}

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

// Check permission
if (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 Details';

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

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

if (!$user_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid user ID');
    }
    header('Location: ' . base_url('admin/users/index.php'));
    exit;
}

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

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

// Get user statistics
$stats = [
    'total_logins' => 0,
    'total_actions' => 0,
    'reservations_created' => 0,
    'pos_transactions' => 0,
    'last_login' => $user['last_login'] ?? null,
    'member_since' => $user['created_at'] ?? null
];

try {
    if (function_exists('db_count')) {
        $stats['total_logins'] = db_count('audit_logs', 'user_id = ? AND action = ?', [$user_id, 'login']) ?: 0;
        $stats['total_actions'] = db_count('audit_logs', 'user_id = ?', [$user_id]) ?: 0;
        $stats['reservations_created'] = db_count('reservations', 'created_by = ?', [$user_id]) ?: 0;
        $stats['pos_transactions'] = db_count('pos_sales', 'user_id = ?', [$user_id]) ?: 0;
    }
} catch (Exception $e) {
    error_log("Error fetching stats: " . $e->getMessage());
}

// Get recent activity
$recent_activity = [];
try {
    $recent_activity = db_fetch_all("
        SELECT * FROM audit_logs 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 20
    ", [$user_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching activity: " . $e->getMessage());
}

// Get active sessions
$active_sessions = [];
try {
    $active_sessions = db_fetch_all("
        SELECT * FROM user_sessions 
        WHERE user_id = ? 
        ORDER BY last_activity DESC
    ", [$user_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching sessions: " . $e->getMessage());
}

// Get user permissions
$permissions = [];
$grouped_permissions = [];

try {
    $permissions = db_fetch_all("
        SELECT p.* 
        FROM permissions p
        JOIN role_permissions rp ON p.permission_id = rp.permission_id
        WHERE rp.role_id = ?
        ORDER BY p.module, p.permission_name
    ", [$user['role_id']]) ?: [];
    
    foreach ($permissions as $perm) {
        $grouped_permissions[$perm['module'] ?? 'General'][] = $perm;
    }
} catch (Exception $e) {
    error_log("Error fetching permissions: " . $e->getMessage());
}

// Include header
$header_file = $base_path . '/views/partials/header.php';
if (file_exists($header_file)) {
    require_once $header_file;
} else {
    ?>
    <!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; }
            .profile-user-img { width: 100px; height: 100px; object-fit: cover; border-radius: 50%; }
            .timeline { position: relative; padding: 20px 0; }
            .timeline-item { position: relative; padding-left: 40px; margin-bottom: 20px; }
            .timeline-item:before { content: ''; position: absolute; left: 15px; top: 0; bottom: -20px; width: 2px; background: #e9ecef; }
            .timeline-item:last-child:before { display: none; }
            .timeline-body { background: #f8f9fa; padding: 15px; border-radius: 5px; }
            .info-box { min-height: 80px; padding: 10px; box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2); border-radius: 5px; margin-bottom: 15px; }
            .info-box-icon { width: 60px; height: 60px; font-size: 24px; line-height: 60px; text-align: center; border-radius: 5px; }
            .btn-purple { 
                background-color: #6f42c1; 
                color: white; 
                border-color: #6f42c1; 
            }
            .btn-purple:hover { 
                background-color: #5e34a5; 
                color: white; 
                border-color: #5e34a5; 
            }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
        </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 Details: <?php echo escape_html($user['username'] ?? ''); ?></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">View</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Action Buttons -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="btn-group">
                    <a href="<?php echo base_url('admin/users/index.php'); ?>" class="btn btn-secondary">
                        <i class="fas fa-arrow-left mr-1"></i> Back to List
                    </a>
                    
                    <?php if (function_exists('has_permission') && has_permission('users.edit')): ?>
                        <a href="<?php echo base_url('admin/users/edit.php?id=' . $user_id); ?>" class="btn btn-warning">
                            <i class="fas fa-edit mr-1"></i> Edit User
                        </a>
                    <?php endif; ?>
                    
                    <?php if (function_exists('has_permission') && has_permission('users.edit') && isset($current_user['user_id']) && $user_id != $current_user['user_id']): ?>
                        <button type="button" class="btn btn-info" onclick="resetPassword(<?php echo $user_id; ?>)">
                            <i class="fas fa-key mr-1"></i> Reset Password
                        </button>
                    <?php endif; ?>
                    
                    <?php if (function_exists('has_permission') && has_permission('users.delete') && isset($current_user['user_id']) && $user_id != $current_user['user_id']): ?>
                        <button type="button" class="btn btn-danger" onclick="deleteUser(<?php echo $user_id; ?>, '<?php echo escape_html($user['username'] ?? ''); ?>')">
                            <i class="fas fa-trash mr-1"></i> Delete User
                        </button>
                    <?php endif; ?>
                    
                    <!-- NEW: User Permissions Button -->
                    <?php if (function_exists('has_permission') && has_permission('users.permissions')): ?>
                        <a href="user-permissions.php?user_id=<?php echo $user_id; ?>" class="btn btn-purple">
                            <i class="fas fa-user-lock mr-1"></i> User Permissions
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- User Info Card -->
            <div class="col-md-4">
                <div class="card card-primary card-outline">
                    <div class="card-body box-profile">
                        <div class="text-center">
                            <?php if (!empty($user['profile_image'])): ?>
                                <img class="profile-user-img img-fluid img-circle"
                                     src="<?php echo uploads_url('ids/' . $user['profile_image']); ?>"
                                     alt="User profile picture">
                            <?php else: ?>
                                <div class="profile-user-img img-fluid img-circle d-flex align-items-center justify-content-center bg-primary text-white mx-auto"
                                     style="width: 100px; height: 100px; font-size: 2.5rem;">
                                    <?php echo strtoupper(substr($user['first_name'] ?? '', 0, 1) . substr($user['last_name'] ?? '', 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <h3 class="profile-username text-center"><?php echo escape_html(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')); ?></h3>

                        <p class="text-muted text-center"><?php echo escape_html($user['role_name'] ?? ''); ?></p>

                        <ul class="list-group list-group-unbordered mb-3">
                            <li class="list-group-item">
                                <b>Username</b> <a class="float-right"><?php echo escape_html($user['username'] ?? ''); ?></a>
                            </li>
                            <li class="list-group-item">
                                <b>Email</b> <a class="float-right"><?php echo escape_html($user['email'] ?? ''); ?></a>
                            </li>
                            <li class="list-group-item">
                                <b>Phone</b> <a class="float-right"><?php echo escape_html($user['phone'] ?? 'Not provided'); ?></a>
                            </li>
                            <li class="list-group-item">
                                <b>Department</b> <a class="float-right"><?php echo escape_html($user['department'] ?? 'Not assigned'); ?></a>
                            </li>
                            <li class="list-group-item">
                                <b>Status</b> 
                                <span class="float-right">
                                    <?php if (!empty($user['is_active'])): ?>
                                        <span class="badge badge-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Inactive</span>
                                    <?php endif; ?>
                                </span>
                            </li>
                        </ul>
                    </div>
                </div>

                <!-- Stats Card -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">User Statistics</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <div class="info-box bg-info">
                                    <span class="info-box-icon"><i class="fas fa-sign-in-alt"></i></span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Logins</span>
                                        <span class="info-box-number"><?php echo $stats['total_logins']; ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="info-box bg-success">
                                    <span class="info-box-icon"><i class="fas fa-history"></i></span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Actions</span>
                                        <span class="info-box-number"><?php echo $stats['total_actions']; ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="info-box bg-warning">
                                    <span class="info-box-icon"><i class="fas fa-calendar-check"></i></span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Reservations</span>
                                        <span class="info-box-number"><?php echo $stats['reservations_created']; ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="info-box bg-primary">
                                    <span class="info-box-icon"><i class="fas fa-cash-register"></i></span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">POS Sales</span>
                                        <span class="info-box-number"><?php echo $stats['pos_transactions']; ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <p><strong>Member Since:</strong> <?php echo format_datetime($stats['member_since'] ?? ''); ?></p>
                        <p><strong>Last Login:</strong> <?php echo !empty($stats['last_login']) ? format_datetime($stats['last_login']) : 'Never'; ?></p>
                        <p><strong>Last IP:</strong> <?php echo $user['last_login_ip'] ?? 'Unknown'; ?></p>
                    </div>
                </div>
            </div>

            <!-- Tabs Content -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header p-2">
                        <ul class="nav nav-pills">
                            <li class="nav-item">
                                <a class="nav-link active" href="#activity" data-toggle="tab">
                                    <i class="fas fa-history mr-1"></i> Activity
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#permissions" data-toggle="tab">
                                    <i class="fas fa-key mr-1"></i> Permissions
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#sessions" data-toggle="tab">
                                    <i class="fas fa-desktop mr-1"></i> Sessions
                                    <?php if (count($active_sessions) > 0): ?>
                                        <span class="badge badge-info"><?php echo count($active_sessions); ?></span>
                                    <?php endif; ?>
                                </a>
                            </li>
                        </ul>
                    </div>
                    
                    <div class="card-body">
                        <div class="tab-content">
                            <!-- Activity Tab -->
                            <div class="tab-pane active" id="activity">
                                <?php if (empty($recent_activity)): ?>
                                    <div class="text-center text-muted py-4">
                                        <i class="fas fa-history fa-3x mb-3"></i>
                                        <p>No activity recorded yet</p>
                                    </div>
                                <?php else: ?>
                                    <div class="timeline">
                                        <?php foreach ($recent_activity as $activity): ?>
                                            <div class="timeline-item">
                                                <span class="time">
                                                    <i class="fas fa-clock"></i> <?php echo time_ago($activity['created_at'] ?? ''); ?>
                                                </span>
                                                <div class="timeline-body">
                                                    <i class="fas <?php 
                                                        switch($activity['action'] ?? '') {
                                                            case 'login': echo 'fa-sign-in-alt text-success'; break;
                                                            case 'logout': echo 'fa-sign-out-alt text-warning'; break;
                                                            case 'create': echo 'fa-plus-circle text-success'; break;
                                                            case 'update': echo 'fa-edit text-info'; break;
                                                            case 'delete': echo 'fa-trash text-danger'; break;
                                                            default: echo 'fa-info-circle text-secondary';
                                                        }
                                                    ?> mr-2"></i>
                                                    <strong><?php echo ucfirst($activity['action'] ?? 'Unknown'); ?></strong>
                                                    <?php if (!empty($activity['table_name'])): ?>
                                                        on <?php echo str_replace('_', ' ', $activity['table_name']); ?>
                                                        <?php if (!empty($activity['record_id'])): ?>
                                                            #<?php echo $activity['record_id']; ?>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                    <br>
                                                    <small class="text-muted">
                                                        IP: <?php echo $activity['ip_address'] ?? 'Unknown'; ?>
                                                        <?php if (!empty($activity['old_values']) || !empty($activity['new_values'])): ?>
                                                            - <a href="#" onclick="showAuditDetails(this)" 
                                                                 data-old='<?php echo $activity['old_values'] ?? ''; ?>' 
                                                                 data-new='<?php echo $activity['new_values'] ?? ''; ?>'>
                                                                View Details
                                                            </a>
                                                        <?php endif; ?>
                                                    </small>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                    
                                    <div class="text-center mt-3">
                                        <a href="<?php echo base_url('admin/users/audit-logs.php?user_id=' . $user_id); ?>" class="btn btn-primary">
                                            View All Activity
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Permissions Tab -->
                            <div class="tab-pane" id="permissions">
                                <?php if (empty($grouped_permissions)): ?>
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle mr-2"></i>
                                        This user has no specific permissions assigned.
                                    </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>
                                            <div class="card-body">
                                                <div class="row">
                                                    <?php foreach ($perms as $perm): ?>
                                                        <div class="col-md-6">
                                                            <div class="custom-control custom-checkbox">
                                                                <input type="checkbox" class="custom-control-input" 
                                                                       id="perm_<?php echo $perm['permission_id'] ?? 0; ?>" 
                                                                       checked 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>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>

                            <!-- Sessions Tab -->
                            <div class="tab-pane" id="sessions">
                                <?php if (empty($active_sessions)): ?>
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle mr-2"></i>
                                        No active sessions found.
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Device</th>
                                                    <th>IP Address</th>
                                                    <th>Last Activity</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($active_sessions as $session): 
                                                    $is_current = isset($session['session_id']) && $session['session_id'] === session_id();
                                                ?>
                                                <tr>
                                                    <td>
                                                        <?php
                                                        $user_agent = $session['user_agent'] ?? 'Unknown';
                                                        $browser = 'Unknown';
                                                        $os = 'Unknown';
                                                        
                                                        if (preg_match('/Chrome/i', $user_agent) && !preg_match('/Edge/i', $user_agent)) {
                                                            $browser = 'Chrome';
                                                        } elseif (preg_match('/Firefox/i', $user_agent)) {
                                                            $browser = 'Firefox';
                                                        } elseif (preg_match('/Safari/i', $user_agent) && !preg_match('/Chrome/i', $user_agent)) {
                                                            $browser = 'Safari';
                                                        } elseif (preg_match('/Edge/i', $user_agent)) {
                                                            $browser = 'Edge';
                                                        }
                                                        
                                                        if (preg_match('/Windows/i', $user_agent)) {
                                                            $os = 'Windows';
                                                        } elseif (preg_match('/Mac/i', $user_agent)) {
                                                            $os = 'macOS';
                                                        } elseif (preg_match('/Linux/i', $user_agent)) {
                                                            $os = 'Linux';
                                                        } elseif (preg_match('/Android/i', $user_agent)) {
                                                            $os = 'Android';
                                                        } elseif (preg_match('/iPhone/i', $user_agent) || preg_match('/iPad/i', $user_agent)) {
                                                            $os = 'iOS';
                                                        }
                                                        
                                                        echo "<i class='fas fa-" . ($os == 'Windows' ? 'windows' : ($os == 'macOS' ? 'apple' : 'desktop')) . " mr-2'></i>";
                                                        echo "$browser on $os";
                                                        ?>
                                                    </td>
                                                    <td><?php echo $session['ip_address'] ?? 'Unknown'; ?></td>
                                                    <td><?php echo !empty($session['last_activity']) ? time_ago($session['last_activity']) : 'Never'; ?></td>
                                                    <td>
                                                        <?php if ($is_current): ?>
                                                            <span class="badge badge-success">Current Session</span>
                                                        <?php else: ?>
                                                            <span class="badge badge-secondary">Active</span>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Audit Details Modal -->
<div class="modal fade" id="auditDetailsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Audit Details</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Old Values</h6>
                        <pre id="oldValues" class="bg-light p-2 rounded" style="max-height: 200px; overflow: auto;"></pre>
                    </div>
                    <div class="col-md-6">
                        <h6>New Values</h6>
                        <pre id="newValues" class="bg-light p-2 rounded" style="max-height: 200px; overflow: auto;"></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 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 {
                        $csrf_token = bin2hex(random_bytes(32));
                        session_start();
                        $_SESSION['csrf_token'] = $csrf_token;
                        echo '<input type="hidden" name="csrf_token" 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: <strong id="resetEmail"></strong></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 {
                        $csrf_token = bin2hex(random_bytes(32));
                        session_start();
                        $_SESSION['csrf_token'] = $csrf_token;
                        echo '<input type="hidden" name="csrf_token" 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>
function showAuditDetails(element) {
    const oldValues = $(element).data('old');
    const newValues = $(element).data('new');
    
    $('#oldValues').text(oldValues ? JSON.stringify(JSON.parse(oldValues), null, 2) : 'No old values');
    $('#newValues').text(newValues ? JSON.stringify(JSON.parse(newValues), null, 2) : 'No new values');
    
    $('#auditDetailsModal').modal('show');
}

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

function resetPassword(userId) {
    $.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);
            $('#resetEmail').text(response.data.email);
            $('#resetPasswordModal').modal('show');
        } else {
            alert('Error loading user data');
        }
    }).fail(function() {
        alert('Failed to load user data');
    });
}
</script>

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