<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details || $user_details['role_name'] !== 'Administrator') {
    header('Location: index.php');
    exit();
}

$full_name = $user_details['full_name'];
$role_name = $user_details['role_name'];

// Handle AJAX requests
if ($_POST && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    try {
        switch ($_POST['action']) {
            case 'create_user':
                $username = trim($_POST['username']);
                $email = trim($_POST['email']);
                $full_name = trim($_POST['full_name']);
                $password = $_POST['password'];
                $role_id = intval($_POST['role_id']);
                $phone = trim($_POST['phone']);
                $status = $_POST['status'];
                
                // Validate required fields
                if (empty($username) || empty($email) || empty($full_name) || empty($password) || !$role_id) {
                    throw new Exception('All required fields must be filled');
                }
                
                // Check if username or email already exists
                $check_sql = "SELECT user_id FROM users WHERE username = ? OR email = ?";
                $stmt_check = $conn->prepare($check_sql);
                $stmt_check->bind_param("ss", $username, $email);
                $stmt_check->execute();
                if ($stmt_check->get_result()->num_rows > 0) {
                    throw new Exception('Username or email already exists');
                }
                
                // Hash password
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                
                // Create user
                $create_sql = "INSERT INTO users (username, email, full_name, password, role_id, phone, status, created_at) 
                              VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
                $stmt_create = $conn->prepare($create_sql);
                $stmt_create->bind_param("ssssiss", $username, $email, $full_name, $hashed_password, $role_id, $phone, $status);
                
                if ($stmt_create->execute()) {
                    $new_user_id = $conn->insert_id;
                    
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                               VALUES (?, 'CREATE', 'users', ?, ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $log_details = json_encode(['username' => $username, 'email' => $email, 'role_id' => $role_id]);
                    $stmt_log->bind_param("iss", $user_id, $new_user_id, $log_details);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'User created successfully', 'user_id' => $new_user_id]);
                } else {
                    throw new Exception('Failed to create user');
                }
                break;
                
            case 'update_user_status':
                $target_user_id = intval($_POST['user_id']);
                $new_status = $_POST['status'];
                
                if ($target_user_id == $user_id) {
                    throw new Exception('You cannot change your own status');
                }
                
                $update_sql = "UPDATE users SET status = ?, updated_at = NOW() WHERE user_id = ?";
                $stmt_update = $conn->prepare($update_sql);
                $stmt_update->bind_param("si", $new_status, $target_user_id);
                
                if ($stmt_update->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values) 
                               VALUES (?, 'UPDATE', 'users', ?, 'status_change', ?)";
                    $stmt_log = $conn->prepare($log_sql);
                    $stmt_log->bind_param("iss", $user_id, $target_user_id, $new_status);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'User status updated successfully']);
                } else {
                    throw new Exception('Failed to update user status');
                }
                break;
                
            case 'reset_password':
                $target_user_id = intval($_POST['user_id']);
                $new_password = $_POST['new_password'];
                
                if (strlen($new_password) < 8) {
                    throw new Exception('Password must be at least 8 characters long');
                }
                
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                
                $reset_sql = "UPDATE users SET password = ?, last_password_change = NOW() WHERE user_id = ?";
                $stmt_reset = $conn->prepare($reset_sql);
                $stmt_reset->bind_param("si", $hashed_password, $target_user_id);
                
                if ($stmt_reset->execute()) {
                    // Log activity
                    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                               VALUES (?, 'UPDATE', 'users', ?, 'password_reset')";
                    $stmt_log = $conn->prepare($log_sql);
                    $stmt_log->bind_param("is", $user_id, $target_user_id);
                    $stmt_log->execute();
                    
                    echo json_encode(['success' => true, 'message' => 'Password reset successfully']);
                } else {
                    throw new Exception('Failed to reset password');
                }
                break;
                
            default:
                throw new Exception('Invalid action');
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit();
}

// Get filter parameters
$role_filter = $_GET['role'] ?? '';
$status_filter = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if ($role_filter) {
    $where_conditions[] = "ur.role_name = ?";
    $params[] = $role_filter;
    $param_types .= 's';
}

if ($status_filter) {
    $where_conditions[] = "u.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if ($search) {
    $where_conditions[] = "(u.username LIKE ? OR u.full_name LIKE ? OR u.email LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $param_types .= 'sss';
}

$where_clause = empty($where_conditions) ? '' : 'WHERE ' . implode(' AND ', $where_conditions);

// Get users with role information
$sql_users = "SELECT u.*, ur.role_name, ur.description as role_description,
                     DATE(u.last_login) as last_login_date,
                     DATEDIFF(NOW(), u.last_login) as days_since_login
              FROM users u
              INNER JOIN user_roles ur ON u.role_id = ur.role_id
              $where_clause
              ORDER BY u.created_at DESC";

$stmt_users = $conn->prepare($sql_users);
if (!empty($params)) {
    $stmt_users->bind_param($param_types, ...$params);
}
$stmt_users->execute();
$users_result = $stmt_users->get_result();

// Get user roles for dropdown
$sql_roles = "SELECT role_id, role_name, description FROM user_roles ORDER BY role_name";
$roles_result = $conn->query($sql_roles);

// Get user statistics
$sql_stats = "SELECT 
                COUNT(*) as total_users,
                SUM(CASE WHEN u.status = 'ACTIVE' THEN 1 ELSE 0 END) as active_users,
                SUM(CASE WHEN u.status = 'INACTIVE' THEN 1 ELSE 0 END) as inactive_users,
                SUM(CASE WHEN u.status = 'SUSPENDED' THEN 1 ELSE 0 END) as suspended_users,
                SUM(CASE WHEN u.last_login >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as recent_logins,
                SUM(CASE WHEN u.last_login IS NULL OR u.last_login < DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as inactive_logins
              FROM users u
              INNER JOIN user_roles ur ON u.role_id = ur.role_id
              $where_clause";

$stmt_stats = $conn->prepare($sql_stats);
if (!empty($params)) {
    $stmt_stats->bind_param($param_types, ...$params);
}
$stmt_stats->execute();
$stats = $stmt_stats->get_result()->fetch_assoc();

// Get role distribution
$sql_role_dist = "SELECT ur.role_name, COUNT(*) as user_count
                  FROM users u
                  INNER JOIN user_roles ur ON u.role_id = ur.role_id
                  WHERE u.status = 'ACTIVE'
                  GROUP BY ur.role_id, ur.role_name
                  ORDER BY user_count DESC";
$role_dist_result = $conn->query($sql_role_dist);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'User Management - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .users-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .users-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            margin-bottom: 1.5rem;
        }
        
        .users-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .summary-card:hover {
            transform: translateY(-5px);
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-active { background: #d1e7dd; color: #0a3622; }
        .status-inactive { background: #f8d7da; color: #58151c; }
        .status-suspended { background: #fff3cd; color: #664d03; }
        
        .role-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
            margin: 0.1rem;
        }
        
        .role-administrator { background: #fee2e2; color: #991b1b; }
        .role-finance-manager { background: #fef3c7; color: #92400e; }
        .role-operations-manager { background: #dbeafe; color: #1e40af; }
        .role-customer-service { background: #d1fae5; color: #065f46; }
        .role-warehouse-staff { background: #e0e7ff; color: #3730a3; }
        .role-driver { background: #f3e8ff; color: #6b21a8; }
        .role-customs-officer { background: #fecaca; color: #7f1d1d; }
        
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .action-btn {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            margin: 0.1rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-suspend { background: #fff3cd; color: #664d03; }
        .btn-activate { background: #d1fae5; color: #065f46; }
        .btn-reset { background: #f0f9ff; color: #0c4a6e; }
        .btn-delete { background: #ffebee; color: #c62828; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .create-user-btn {
            background: linear-gradient(45deg, #10b981, #059669);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }
        
        .create-user-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
            color: white;
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .login-indicator {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.75rem;
        }
        
        .login-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }
        
        .login-recent { background: #10b981; }
        .login-old { background: #ef4444; }
        .login-never { background: #6b7280; }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .users-header {
                padding: 1.5rem;
            }
            
            .summary-value {
                font-size: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><i class="ri-group-line me-2"></i>User Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="system_settings.php">System</a></li>
                                        <li class="breadcrumb-item active">Users</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($stats['total_users']); ?></div>
                                <div class="summary-label">Total Users</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                                <div class="summary-value"><?php echo number_format($stats['active_users']); ?></div>
                                <div class="summary-label">Active Users</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                                <div class="summary-value"><?php echo number_format($stats['inactive_users']); ?></div>
                                <div class="summary-label">Inactive Users</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                                <div class="summary-value"><?php echo number_format($stats['suspended_users']); ?></div>
                                <div class="summary-label">Suspended</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);">
                                <div class="summary-value"><?php echo number_format($stats['recent_logins']); ?></div>
                                <div class="summary-label">Recent Logins</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);">
                                <div class="summary-value"><?php echo number_format($stats['inactive_logins']); ?></div>
                                <div class="summary-label">Inactive Logins</div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions and Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="users-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <button class="btn create-user-btn me-2" onclick="showCreateUserModal()">
                                                <i class="ri-user-add-line me-1"></i>Create User
                                            </button>
                                            <button class="btn btn-outline-success me-2" onclick="exportUsers()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                            <button class="btn btn-outline-info" onclick="bulkActions()">
                                                <i class="ri-settings-3-line me-1"></i>Bulk Actions
                                            </button>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                                <i class="ri-filter-3-line me-1"></i>Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="collapse" id="filterSection">
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label for="role" class="form-label">Role</label>
                                    <select class="form-select" name="role" id="role">
                                        <option value="">All Roles</option>
                                        <?php
                                        $roles_result->data_seek(0);
                                        while ($role = $roles_result->fetch_assoc()):
                                        ?>
                                        <option value="<?php echo $role['role_name']; ?>" <?php echo $role_filter == $role['role_name'] ? 'selected' : ''; ?>>
                                            <?php echo $role['role_name']; ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-3">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" name="status" id="status">
                                        <option value="">All Status</option>
                                        <option value="ACTIVE" <?php echo $status_filter == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                        <option value="INACTIVE" <?php echo $status_filter == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                        <option value="SUSPENDED" <?php echo $status_filter == 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4">
                                    <label for="search" class="form-label">Search</label>
                                    <input type="text" class="form-control" name="search" id="search" 
                                           placeholder="Search users..." value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary d-block w-100">
                                        <i class="ri-search-line"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Users Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="users-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-group-2-line me-2"></i>Users List
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="usersTable">
                                            <thead>
                                                <tr>
                                                    <th>User</th>
                                                    <th>Role</th>
                                                    <th>Status</th>
                                                    <th>Last Login</th>
                                                    <th>Created</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($user = $users_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="user-avatar me-3">
                                                                <?php echo strtoupper(substr($user['full_name'], 0, 2)); ?>
                                                            </div>
                                                            <div>
                                                                <div class="fw-bold"><?php echo htmlspecialchars($user['full_name']); ?></div>
                                                                <div class="text-muted small">@<?php echo htmlspecialchars($user['username']); ?></div>
                                                                <div class="text-muted small"><?php echo htmlspecialchars($user['email']); ?></div>
                                                                <?php if ($user['phone']): ?>
                                                                <div class="text-muted small"><?php echo htmlspecialchars($user['phone']); ?></div>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="role-badge role-<?php echo strtolower(str_replace(' ', '-', $user['role_name'])); ?>">
                                                            <?php echo htmlspecialchars($user['role_name']); ?>
                                                        </span>
                                                        <?php if ($user['role_description']): ?>
                                                        <div class="text-muted small mt-1"><?php echo htmlspecialchars($user['role_description']); ?></div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="status-badge status-<?php echo strtolower($user['status']); ?>">
                                                            <?php echo ucfirst(strtolower($user['status'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if ($user['last_login']): ?>
                                                        <div class="login-indicator">
                                                            <span class="login-dot <?php 
                                                                echo $user['days_since_login'] <= 7 ? 'login-recent' : 
                                                                    ($user['days_since_login'] <= 30 ? 'login-old' : 'login-never');
                                                            ?>"></span>
                                                            <div>
                                                                <div class="small"><?php echo date('M j, Y', strtotime($user['last_login'])); ?></div>
                                                                <div class="text-muted" style="font-size: 0.65rem;">
                                                                    <?php echo $user['days_since_login']; ?> days ago
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <?php else: ?>
                                                        <div class="login-indicator">
                                                            <span class="login-dot login-never"></span>
                                                            <span class="text-muted small">Never</span>
                                                        </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="small"><?php echo date('M j, Y', strtotime($user['created_at'])); ?></div>
                                                        <div class="text-muted" style="font-size: 0.65rem;">
                                                            <?php echo date('H:i', strtotime($user['created_at'])); ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button class="action-btn btn-edit" onclick="editUser(<?php echo $user['user_id']; ?>)" title="Edit User">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            
                                                            <?php if ($user['user_id'] != $user_id): ?>
                                                                <?php if ($user['status'] == 'ACTIVE'): ?>
                                                                <button class="action-btn btn-suspend" onclick="updateUserStatus(<?php echo $user['user_id']; ?>, 'SUSPENDED')" title="Suspend User">
                                                                    <i class="ri-pause-line"></i>
                                                                </button>
                                                                <?php else: ?>
                                                                <button class="action-btn btn-activate" onclick="updateUserStatus(<?php echo $user['user_id']; ?>, 'ACTIVE')" title="Activate User">
                                                                    <i class="ri-play-line"></i>
                                                                </button>
                                                                <?php endif; ?>
                                                                
                                                                <button class="action-btn btn-reset" onclick="resetPassword(<?php echo $user['user_id']; ?>)" title="Reset Password">
                                                                    <i class="ri-lock-password-line"></i>
                                                                </button>
                                                                
                                                                <button class="action-btn btn-delete" onclick="deleteUser(<?php echo $user['user_id']; ?>)" title="Delete User">
                                                                    <i class="ri-delete-bin-line"></i>
                                                                </button>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Create User Modal -->
    <div class="modal fade" id="createUserModal" tabindex="-1" aria-labelledby="createUserModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createUserModalLabel">
                        <i class="ri-user-add-line me-2"></i>Create New User
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="createUserForm">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="user_full_name" class="form-label">Full Name *</label>
                                <input type="text" class="form-control" id="user_full_name" name="full_name" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="user_username" class="form-label">Username *</label>
                                <input type="text" class="form-control" id="user_username" name="username" required>
                                <div class="form-text">Unique username for login</div>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="user_email" class="form-label">Email Address *</label>
                                <input type="email" class="form-control" id="user_email" name="email" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="user_phone" class="form-label">Phone Number</label>
                                <input type="tel" class="form-control" id="user_phone" name="phone">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="user_role" class="form-label">Role *</label>
                                <select class="form-select" id="user_role" name="role_id" required>
                                    <option value="">Select Role</option>
                                    <?php 
                                    $roles_result->data_seek(0);
                                    while ($role = $roles_result->fetch_assoc()): 
                                    ?>
                                    <option value="<?php echo $role['role_id']; ?>"><?php echo htmlspecialchars($role['role_name']); ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="user_status" class="form-label">Status *</label>
                                <select class="form-select" id="user_status" name="status" required>
                                    <option value="ACTIVE">Active</option>
                                    <option value="INACTIVE">Inactive</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="user_password" class="form-label">Password *</label>
                                <input type="password" class="form-control" id="user_password" name="password" required minlength="8">
                                <div class="form-text">Minimum 8 characters</div>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="user_confirm_password" class="form-label">Confirm Password *</label>
                                <input type="password" class="form-control" id="user_confirm_password" name="confirm_password" required>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="ri-user-add-line me-1"></i>Create User
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Initialize DataTable
    $('#usersTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[4, 'desc']],
        columnDefs: [
            { targets: [5], orderable: false }
        ],
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                text: '<i class="ri-file-excel-line me-1"></i>Excel',
                className: 'btn btn-success btn-sm'
            },
            {
                extend: 'pdf',
                text: '<i class="ri-file-pdf-line me-1"></i>PDF', 
                className: 'btn btn-danger btn-sm'
            }
        ]
    });

    // Create User Form Handler
    $('#createUserForm').on('submit', function(e) {
        e.preventDefault();
        
        // Validate password confirmation
        const password = $('#user_password').val();
        const confirmPassword = $('#user_confirm_password').val();
        
        if (password !== confirmPassword) {
            Swal.fire({
                title: 'Password Mismatch',
                text: 'Password and confirm password do not match.',
                icon: 'error'
            });
            return;
        }
        
        const formData = new FormData(this);
        formData.append('action', 'create_user');
        
        // Show loading
        Swal.fire({
            title: 'Creating User...',
            text: 'Please wait while we create the new user account.',
            icon: 'info',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        $.ajax({
            url: 'users.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'User Created!',
                        text: response.message,
                        icon: 'success',
                        timer: 3000,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error',
                        text: response.message,
                        icon: 'error'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error',
                    text: 'An error occurred while creating the user.',
                    icon: 'error'
                });
            }
        });
    });
});

// Define all functions in global scope
window.showCreateUserModal = function() {
    $('#createUserModal').modal('show');
};

window.updateUserStatus = function(userId, newStatus) {
    const actionText = newStatus === 'ACTIVE' ? 'activate' : 'suspend';
    
    Swal.fire({
        title: `${actionText.charAt(0).toUpperCase() + actionText.slice(1)} User`,
        text: `Are you sure you want to ${actionText} this user?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: `Yes, ${actionText}`,
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'users.php',
                method: 'POST',
                data: {
                    action: 'update_user_status',
                    user_id: userId,
                    status: newStatus
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Success',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while updating user status.',
                        icon: 'error'
                    });
                }
            });
        }
    });
};

window.resetPassword = function(userId) {
    Swal.fire({
        title: 'Reset User Password',
        html: `
            <div class="mb-3 text-start">
                <label class="form-label">New Password:</label>
                <input type="password" class="form-control" id="newPassword" placeholder="Enter new password" minlength="8">
                <div class="form-text">Password must be at least 8 characters long</div>
            </div>
            <div class="mb-3 text-start">
                <label class="form-label">Confirm Password:</label>
                <input type="password" class="form-control" id="confirmPassword" placeholder="Confirm new password">
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Reset Password',
        preConfirm: () => {
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            if (!newPassword || newPassword.length < 8) {
                Swal.showValidationMessage('Password must be at least 8 characters long');
                return false;
            }
            
            if (newPassword !== confirmPassword) {
                Swal.showValidationMessage('Passwords do not match');
                return false;
            }
            
            return { newPassword };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'users.php',
                method: 'POST',
                data: {
                    action: 'reset_password',
                    user_id: userId,
                    new_password: result.value.newPassword
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Password Reset!',
                            text: response.message,
                            icon: 'success',
                            timer: 3000,
                            showConfirmButton: false
                        });
                    } else {
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while resetting the password.',
                        icon: 'error'
                    });
                }
            });
        }
    });
};

window.editUser = function(userId) {
    // Navigate to edit user page
    window.location.href = `edit_user.php?id=${userId}`;
};

window.deleteUser = function(userId) {
    Swal.fire({
        title: 'Delete User',
        text: 'Are you sure you want to delete this user? This action cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#d33'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'User Deleted!',
                text: 'The user has been permanently deleted.',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        }
    });
};

window.exportUsers = function() {
    Swal.fire({
        title: 'Export Users',
        html: `
            <div class="mb-3">
                <label class="form-label">Export Format:</label>
                <select class="form-select" id="exportFormat">
                    <option value="excel">Excel (.xlsx)</option>
                    <option value="pdf">PDF Report</option>
                    <option value="csv">CSV Data</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Include:</label>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includePasswords">
                    <label class="form-check-label" for="includePasswords">Password Information</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeLoginHistory" checked>
                    <label class="form-check-label" for="includeLoginHistory">Login History</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeInactive" checked>
                    <label class="form-check-label" for="includeInactive">Inactive Users</label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Generating Export...',
                text: 'Please wait while we prepare your user data export.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.close();
                        // Simulate download
                        const link = document.createElement('a');
                        link.href = '#';
                        link.download = `users_export_${new Date().toISOString().split('T')[0]}.xlsx`;
                        link.click();
                    }, 2000);
                }
            });
        }
    });
};

window.bulkActions = function() {
    Swal.fire({
        title: 'Bulk Actions',
        text: 'Select users from the table and choose an action to perform on multiple users at once.',
        icon: 'info',
        confirmButtonText: 'OK'
    });
};

// Password strength indicator
$('#user_password').on('input', function() {
    const password = $(this).val();
    const strength = calculatePasswordStrength(password);
    
    // Remove existing strength indicator
    $(this).next('.password-strength').remove();
    
    if (password.length > 0) {
        const strengthColor = strength < 3 ? 'danger' : strength < 4 ? 'warning' : 'success';
        const strengthText = strength < 2 ? 'Weak' : strength < 3 ? 'Fair' : strength < 4 ? 'Good' : 'Strong';
        
        $(this).after(`<div class="password-strength">
            <div class="progress mt-1" style="height: 4px;">
                <div class="progress-bar bg-${strengthColor}" style="width: ${(strength / 4) * 100}%"></div>
            </div>
            <small class="text-${strengthColor}">Password strength: ${strengthText}</small>
        </div>`);
    }
});

function calculatePasswordStrength(password) {
    let strength = 0;
    if (password.length >= 8) strength++;
    if (/[a-z]/.test(password)) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/\d/.test(password)) strength++;
    if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) strength++;
    return Math.min(strength, 4);
}
</script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>