<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Branch.php';
requireRole('super_admin');
$pageTitle = 'User Management';

$db = db();

// Handle POST (Create / Update / Delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    try {
        // DELETE USER
        if (isset($_POST['action']) && $_POST['action'] === 'delete') {
            $userId = (int)($_POST['id'] ?? 0);
            if ($userId <= 0) throw new Exception('User ID tidak valid');
            
            if ($userId === currentUserId()) {
                throw new Exception('Tidak dapat menghapus akun Anda sendiri!');
            }
            
            $targetUser = $db->prepare("SELECT role FROM users WHERE id = ?");
            $targetUser->execute([$userId]);
            $target = $targetUser->fetch();
            
            if ($target && $target['role'] === 'super_admin' && $userId !== currentUserId()) {
                throw new Exception('Tidak dapat menghapus sesama Super Admin!');
            }
            
            $db->prepare("DELETE FROM users WHERE id = ?")->execute([$userId]);
            redirect('/admin/users.php', '✅ User berhasil dihapus');
        }
        
        // CREATE / UPDATE USER
        $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $role = $_POST['role'] ?? 'staff';
        $status = $_POST['status'] ?? 'active';
        $branchId = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
        
        if (empty($name)) throw new Exception('Nama wajib diisi');
        if ($id === null && empty($username)) throw new Exception('Username wajib diisi untuk user baru');
        if ($id === null && empty($password)) throw new Exception('Password wajib diisi untuk user baru');
        
        if ($id) {
            $sql = "UPDATE users SET name = ?, email = ?, role = ?, status = ?, branch_id = ?";
            $params = [$name, $email, $role, $status, $branchId];
            
            if (!empty($username)) {
                $check = $db->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
                $check->execute([$username, $id]);
                if ($check->fetch()) throw new Exception("Username '{$username}' sudah digunakan");
                
                $sql .= ", username = ?";
                $params[] = $username;
            }
            
            if (!empty($password)) {
                $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
                $sql .= ", password = ?";
                $params[] = $hashedPassword;
            }
            
            $sql .= " WHERE id = ?";
            $params[] = $id;
            
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            
            redirect('/admin/users.php', '✅ User berhasil diupdate');
            
        } else {
            $check = $db->prepare("SELECT id FROM users WHERE username = ?");
            $check->execute([$username]);
            if ($check->fetch()) throw new Exception("Username '{$username}' sudah digunakan");
            
            if (!empty($email)) {
                $checkEmail = $db->prepare("SELECT id FROM users WHERE email = ?");
                $checkEmail->execute([$email]);
                if ($checkEmail->fetch()) throw new Exception("Email '{$email}' sudah digunakan");
            }
            
            $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
            
            $sql = "INSERT INTO users (branch_id, username, password, name, email, role, status, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([$branchId, $username, $hashedPassword, $name, $email, $role, $status]);
            
            redirect('/admin/users.php', "✅ User '{$username}' berhasil ditambahkan");
        }
        
    } catch (\Throwable $e) {
        $_SESSION['flash_error'] = '❌ Error: ' . $e->getMessage();
    }
}

// Load data
$users = $db->query("
    SELECT u.*, b.name as branch_name 
    FROM users u 
    LEFT JOIN branches b ON u.branch_id = b.id 
    ORDER BY u.role DESC, u.name ASC
")->fetchAll();

$branches = Branch::all();

$errorMessage = $_SESSION['flash_error'] ?? '';
unset($_SESSION['flash_error']);

// Statistics
$totalUsers = count($users);
$activeUsers = count(array_filter($users, fn($u) => $u['status'] === 'active'));
$superAdmins = count(array_filter($users, fn($u) => $u['role'] === 'super_admin'));
$branchAdmins = count(array_filter($users, fn($u) => $u['role'] === 'branch_admin'));

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>

<style>
/* === PAGE HEADER === */
.page-header {
    margin-bottom: 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.page-title {
    font-size: 1.8rem;
    font-weight: 700;
    color: #003D7A;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 12px;
}

.page-title i {
    font-size: 2rem;
    color: #0066CC;
}

.page-subtitle {
    color: #666;
    font-size: 0.95rem;
    margin: 4px 0 0;
}

.btn-add {
    padding: 12px 24px;
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    border: none;
    border-radius: 12px;
    font-size: 0.95rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
    box-shadow: 0 4px 15px rgba(0, 102, 204, 0.3);
}

.btn-add:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 102, 204, 0.4);
    color: white;
}

/* === SUMMARY CARDS === */
.summary-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin-bottom: 25px;
}

.summary-card {
    background: white;
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
}

.summary-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.12);
}

.summary-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
}

.summary-card.primary::before { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.success::before { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.summary-card.danger::before { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.summary-card.warning::before { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }

.summary-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
}

.summary-card-title {
    color: #666;
    font-size: 0.85rem;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 6px;
}

.summary-card-icon {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.2rem;
}

.summary-card.primary .summary-card-icon { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.success .summary-card-icon { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.summary-card.danger .summary-card-icon { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.summary-card.warning .summary-card-icon { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }

.summary-card-value {
    font-size: 1.6rem;
    font-weight: 800;
    margin-bottom: 4px;
    letter-spacing: -0.5px;
}

.summary-card.primary .summary-card-value { color: #0066CC; }
.summary-card.success .summary-card-value { color: #00C853; }
.summary-card.danger .summary-card-value { color: #DC3545; }
.summary-card.warning .summary-card-value { color: #FF9900; }

.summary-card-footer {
    font-size: 0.8rem;
    color: #999;
}

/* === USER CARDS === */
.users-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}

.user-card {
    background: white;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
    position: relative;
}

.user-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 30px rgba(0,0,0,0.12);
}

.user-card-header {
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    border-bottom: 1px dashed #e8f4f8;
}

.user-avatar-modern {
    width: 55px;
    height: 55px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    font-weight: 800;
    color: white;
    flex-shrink: 0;
    box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3);
}

.user-avatar-modern.super_admin { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.user-avatar-modern.branch_admin { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.user-avatar-modern.staff { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }

.user-card-info {
    flex: 1;
    min-width: 0;
}

.user-card-name {
    font-size: 1.05rem;
    font-weight: 700;
    color: #003D7A;
    margin: 0 0 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.user-card-username {
    font-size: 0.82rem;
    color: #999;
    margin: 0;
}

.user-card-body {
    padding: 16px 20px;
}

.user-detail {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 10px;
    font-size: 0.88rem;
    color: #555;
    line-height: 1.5;
}

.user-detail:last-child {
    margin-bottom: 0;
}

.user-detail i {
    color: #0066CC;
    font-size: 1rem;
    margin-top: 2px;
    flex-shrink: 0;
    width: 20px;
    text-align: center;
}

.user-detail .label {
    color: #999;
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 600;
    display: block;
    margin-bottom: 2px;
}

.user-badges {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px dashed #e8f4f8;
}

/* === BADGE MODERN === */
.badge-modern {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 12px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.badge-modern.super_admin {
    background: #f8d7da;
    color: #842029;
    border: 1px solid #f1aeb5;
}

.badge-modern.branch_admin {
    background: #fff3cd;
    color: #856404;
    border: 1px solid #ffe69c;
}

.badge-modern.staff {
    background: #cfe2ff;
    color: #084298;
    border: 1px solid #b6d4fe;
}

.badge-modern.active {
    background: #d1e7dd;
    color: #0f5132;
    border: 1px solid #a3cfbb;
}

.badge-modern.inactive {
    background: #e9ecef;
    color: #6c757d;
    border: 1px solid #dee2e6;
}

/* === ACTION BUTTONS === */
.user-card-footer {
    padding: 12px 20px;
    background: #f8fafc;
    border-top: 1px solid #f0f0f0;
    display: flex;
    gap: 8px;
}

.btn-user-action {
    flex: 1;
    padding: 9px;
    border: none;
    border-radius: 10px;
    font-size: 0.82rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
}

.btn-user-action.edit {
    background: #fff3cd;
    color: #856404;
}

.btn-user-action.edit:hover {
    background: #FF9900;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(255, 153, 0, 0.3);
}

.btn-user-action.delete {
    background: #f8d7da;
    color: #842029;
}

.btn-user-action.delete:hover {
    background: #DC3545;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}

/* === EMPTY STATE === */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
}

.empty-state-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto 20px;
    background: #f8fafc;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2.5rem;
    color: #ccc;
}

.empty-state-title {
    color: #666;
    font-weight: 600;
    margin-bottom: 6px;
    font-size: 1.1rem;
}

.empty-state-subtitle {
    color: #999;
    font-size: 0.9rem;
    margin: 0 0 20px;
}

/* === ALERT MODERN === */
.alert-modern {
    padding: 16px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: flex-start;
    gap: 12px;
    font-size: 0.95rem;
    border: 2px solid;
}

.alert-modern.success {
    background: #e8f5e9;
    border-color: #a5d6a7;
    color: #2e7d32;
}

.alert-modern.danger {
    background: #ffebee;
    border-color: #ef9a9a;
    color: #c62828;
}

.alert-modern.info {
    background: #e3f2fd;
    border-color: #90caf9;
    color: #1565c0;
}

.alert-modern i {
    font-size: 1.3rem;
    margin-top: 2px;
}

/* === MODAL MODERN === */
.modal-modern .modal-content {
    border: none;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2);
}

.modal-modern .modal-header {
    color: white;
    padding: 18px 24px;
    border: none;
}

.modal-modern .modal-header.primary {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
}

.modal-modern .modal-header.danger {
    background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%);
}

.modal-modern .modal-title {
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1.1rem;
}

.modal-modern .modal-body {
    padding: 24px;
}

.modal-modern .modal-footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    background: #f8fafc;
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}

.form-group-modern {
    margin-bottom: 18px;
}

.form-label-modern {
    display: block;
    font-weight: 600;
    color: #003D7A;
    margin-bottom: 8px;
    font-size: 0.9rem;
}

.form-control-modern,
.form-select-modern {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e8f4f8;
    border-radius: 12px;
    font-size: 0.95rem;
    transition: all 0.3s ease;
    background: #f8fafc;
    font-family: inherit;
}

.form-control-modern:focus,
.form-select-modern:focus {
    outline: none;
    border-color: #0066CC;
    background: white;
    box-shadow: 0 0 0 4px rgba(0, 102, 204, 0.1);
}

.form-hint {
    display: block;
    margin-top: 6px;
    font-size: 0.8rem;
    color: #999;
}

.btn-modal {
    padding: 10px 20px;
    border: none;
    border-radius: 10px;
    font-size: 0.95rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.btn-modal.secondary {
    background: white;
    color: #666;
    border: 2px solid #e8f4f8;
}

.btn-modal.secondary:hover {
    background: #f8fafc;
}

.btn-modal.primary {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3);
}

.btn-modal.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 102, 204, 0.4);
}

.btn-modal.danger {
    background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}

.btn-modal.danger:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(220, 53, 69, 0.4);
}

.divider-modern {
    border: none;
    border-top: 2px dashed #e8f4f8;
    margin: 20px 0;
}

.delete-warning {
    background: #ffebee;
    border: 2px solid #ef9a9a;
    border-radius: 12px;
    padding: 16px;
    margin-top: 12px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.delete-warning i {
    color: #c62828;
    font-size: 1.5rem;
}

.delete-warning-text {
    color: #842029;
    font-size: 0.9rem;
    margin: 0;
}

.delete-user-info {
    background: #e3f2fd;
    border: 2px solid #90caf9;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.delete-user-info .user-avatar-modern {
    width: 45px;
    height: 45px;
    font-size: 1.2rem;
}

/* === RESPONSIVE === */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .page-title {
        font-size: 1.4rem;
    }
    
    .page-title i {
        font-size: 1.6rem;
    }
    
    .btn-add {
        width: 100%;
        justify-content: center;
    }
    
    .summary-row {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }
    
    .summary-card {
        padding: 16px;
    }
    
    .summary-card-value {
        font-size: 1.3rem;
    }
    
    .summary-card-title {
        font-size: 0.75rem;
    }
    
    .summary-card-icon {
        width: 34px;
        height: 34px;
        font-size: 1rem;
    }
    
    .users-grid {
        grid-template-columns: 1fr;
    }
    
    .user-card-header {
        padding: 16px;
    }
    
    .user-card-body {
        padding: 14px 16px;
    }
    
    .user-avatar-modern {
        width: 48px;
        height: 48px;
        font-size: 1.3rem;
    }
    
    .user-card-name {
        font-size: 1rem;
    }
    
    .user-detail {
        font-size: 0.85rem;
    }
    
    .modal-modern .modal-dialog {
        margin: 0;
        max-width: 100%;
        min-height: 100vh;
    }
    
    .modal-modern .modal-content {
        border-radius: 0;
        min-height: 100vh;
    }
}

@media (max-width: 480px) {
    .page-title {
        font-size: 1.2rem;
        gap: 8px;
    }
    
    .summary-row {
        grid-template-columns: 1fr 1fr;
        gap: 10px;
    }
    
    .summary-card {
        padding: 12px;
    }
    
    .summary-card-value {
        font-size: 1.05rem;
    }
    
    .summary-card-footer {
        font-size: 0.7rem;
    }
    
    .user-avatar-modern {
        width: 42px;
        height: 42px;
        font-size: 1.1rem;
    }
    
    .user-card-name {
        font-size: 0.95rem;
    }
    
    .user-detail {
        font-size: 0.82rem;
    }
    
    .btn-user-action {
        font-size: 0.78rem;
        padding: 8px;
    }
    
    .badge-modern {
        font-size: 0.7rem;
        padding: 4px 10px;
    }
}
</style>

<div class="main-content">
    <!-- ============================================================
         🔄 PERUBAHAN #1: NAVBAR - TAMBAH SUBTITLE
         ============================================================
         ✅ TAMBAH: <p class="navbar-subtitle">Kelola pengguna sistem</p>
         ============================================================ -->
    <div class="navbar-modern">
        <div class="navbar-left">
            <button class="burger-btn" onclick="toggleSidebar()">
                <i class="bi bi-list"></i>
            </button>
            <div>
                <h1 class="navbar-title">User Management</h1>
                <p class="navbar-subtitle">Kelola pengguna sistem</p>
            </div>
        </div>
        <div class="navbar-right">
            <span class="navbar-badge">
                <i class="bi bi-shield-check"></i> Super Admin
            </span>
        </div>
    </div>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- ============================================================
             🔄 PERUBAHAN #2: PAGE HEADER - TAMBAH TITLE & SUBTITLE
             ============================================================
             ✅ TAMBAH: <h2 class="page-title"> dan <p class="page-subtitle">
             ============================================================ -->
        <div class="page-header">
            <div>
                <h2 class="page-title">
                    <i class="bi bi-people-fill"></i>
                    <span>User Management</span>
                </h2>
                <p class="page-subtitle">Kelola pengguna dan hak akses sistem</p>
            </div>
            <button class="btn-add" data-bs-toggle="modal" data-bs-target="#userModal" onclick="resetForm()">
                <i class="bi bi-person-plus-fill"></i>
                <span>Tambah User</span>
            </button>
        </div>

        <?= flashMessage() ?>
        
        <?php if ($errorMessage): ?>
            <div class="alert-modern danger">
                <i class="bi bi-exclamation-circle-fill"></i>
                <div><?= htmlspecialchars($errorMessage) ?></div>
            </div>
        <?php endif; ?>

        <!-- Summary Cards -->
        <div class="summary-row">
            <div class="summary-card primary">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">
                        <i class="bi bi-people"></i> Total User
                    </h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-people-fill"></i>
                    </div>
                </div>
                <div class="summary-card-value"><?= $totalUsers ?></div>
                <div class="summary-card-footer">👥 Seluruh user terdaftar</div>
            </div>
            <div class="summary-card success">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">
                        <i class="bi bi-check-circle"></i> User Aktif
                    </h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-check-circle-fill"></i>
                    </div>
                </div>
                <div class="summary-card-value"><?= $activeUsers ?></div>
                <div class="summary-card-footer">✅ User yang aktif</div>
            </div>
            <div class="summary-card danger">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">
                        <i class="bi bi-shield-fill-check"></i> Super Admin
                    </h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-shield-fill-check"></i>
                    </div>
                </div>
                <div class="summary-card-value"><?= $superAdmins ?></div>
                <div class="summary-card-footer">🛡️ Administrator utama</div>
            </div>
            <div class="summary-card warning">
                <div class="summary-card-header">
                    <h6 class="summary-card-title">
                        <i class="bi bi-building"></i> Branch Admin
                    </h6>
                    <div class="summary-card-icon">
                        <i class="bi bi-building-fill"></i>
                    </div>
                </div>
                <div class="summary-card-value"><?= $branchAdmins ?></div>
                <div class="summary-card-footer">🏢 Admin cabang</div>
            </div>
        </div>

        <!-- Users Grid -->
        <?php if (empty($users)): ?>
            <div class="empty-state">
                <div class="empty-state-icon">
                    <i class="bi bi-people"></i>
                </div>
                <h5 class="empty-state-title">Belum ada user</h5>
                <p class="empty-state-subtitle">Mulai tambahkan user pertama Anda untuk mengelola sistem</p>
                <button class="btn-add" data-bs-toggle="modal" data-bs-target="#userModal" onclick="resetForm()">
                    <i class="bi bi-person-plus-fill"></i>
                    <span>Tambah User Pertama</span>
                </button>
            </div>
        <?php else: ?>
            <div class="users-grid">
                <?php foreach ($users as $u): ?>
                    <div class="user-card">
                        <div class="user-card-header">
                            <div class="user-avatar-modern <?= $u['role'] ?>">
                                <?= strtoupper(substr($u['name'], 0, 1)) ?>
                            </div>
                            <div class="user-card-info">
                                <h5 class="user-card-name"><?= htmlspecialchars($u['name']) ?></h5>
                                <p class="user-card-username">@<?= htmlspecialchars($u['username']) ?></p>
                            </div>
                        </div>
                        
                        <div class="user-card-body">
                            <?php if (!empty($u['email'])): ?>
                                <div class="user-detail">
                                    <i class="bi bi-envelope-fill"></i>
                                    <div>
                                        <span class="label">Email</span>
                                        <?= htmlspecialchars($u['email']) ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <div class="user-detail">
                                <i class="bi bi-building-fill"></i>
                                <div>
                                    <span class="label">Cabang</span>
                                    <?= !empty($u['branch_name']) ? htmlspecialchars($u['branch_name']) : '<em style="color: #999;">Pusat</em>' ?>
                                </div>
                            </div>
                            
                            <div class="user-detail">
                                <i class="bi bi-clock-fill"></i>
                                <div>
                                    <span class="label">Last Login</span>
                                    <?= $u['last_login'] ? date('d/m/Y H:i', strtotime($u['last_login'])) : '<em style="color: #999;">Belum pernah</em>' ?>
                                </div>
                            </div>
                            
                            <div class="user-badges">
                                <?php
                                    $roleLabels = [
                                        'super_admin' => ['🛡️', 'Super Admin'],
                                        'branch_admin' => ['🏢', 'Branch Admin'],
                                        'staff' => ['👤', 'Staff'],
                                    ];
                                    $rl = $roleLabels[$u['role']] ?? ['👤', ucfirst($u['role'])];
                                ?>
                                <span class="badge-modern <?= $u['role'] ?>">
                                    <?= $rl[0] ?> <?= $rl[1] ?>
                                </span>
                                <span class="badge-modern <?= $u['status'] ?>">
                                    <?= $u['status'] === 'active' ? '✅' : '⏸️' ?> <?= ucfirst($u['status']) ?>
                                </span>
                            </div>
                        </div>
                        
                        <div class="user-card-footer">
                            <button class="btn-user-action edit" onclick='editUser(<?= json_encode($u) ?>)'>
                                <i class="bi bi-pencil-fill"></i>
                                <span>Edit</span>
                            </button>
                            <button class="btn-user-action delete" onclick="confirmDelete(<?= $u['id'] ?>, '<?= htmlspecialchars(addslashes($u['username'])) ?>', '<?= htmlspecialchars(addslashes($u['name'])) ?>')">
                                <i class="bi bi-trash-fill"></i>
                                <span>Hapus</span>
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <!-- End Content Wrapper -->
</div>

<!-- Modal Add/Edit User -->
<div class="modal fade modal-modern" id="userModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <form method="POST" id="userForm">
            <?= csrfField() ?>
            <input type="hidden" name="id" id="userId">
            <div class="modal-content">
                <div class="modal-header primary">
                    <h5 class="modal-title" id="modalTitle">
                        <i class="bi bi-person-plus-fill"></i>
                        <span>Tambah User Baru</span>
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <!-- Cabang & Role -->
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group-modern">
                            <label class="form-label-modern">
                                <i class="bi bi-building"></i> Cabang
                            </label>
                            <select name="branch_id" id="branch_id" class="form-select-modern">
                                <option value="">-- Pusat (Semua Cabang) --</option>
                                <?php foreach($branches as $b): ?>
                                    <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small class="form-hint">Kosongkan jika user untuk pusat</small>
                        </div>
                        <div class="form-group-modern">
                            <label class="form-label-modern">
                                <i class="bi bi-shield"></i> Role *
                            </label>
                            <select name="role" id="role" class="form-select-modern" required>
                                <option value="staff">👤 Staff</option>
                                <option value="branch_admin">🏢 Branch Admin</option>
                                <option value="super_admin">🛡️ Super Admin</option>
                            </select>
                        </div>
                    </div>
                    
                    <hr class="divider-modern">
                    
                    <!-- Username & Password -->
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group-modern">
                            <label class="form-label-modern">
                                <i class="bi bi-person"></i> Username *
                            </label>
                            <input type="text" name="username" id="username" class="form-control-modern" 
                                   placeholder="username" required>
                            <small class="form-hint">Untuk login ke sistem</small>
                        </div>
                        <div class="form-group-modern">
                            <label class="form-label-modern">
                                <i class="bi bi-lock"></i> Password <span id="passwordRequired">*</span>
                            </label>
                            <input type="password" name="password" id="password" class="form-control-modern" 
                                   placeholder="••••••••">
                            <small class="form-hint" id="passwordHint">Minimal 6 karakter</small>
                        </div>
                    </div>
                    
                    <hr class="divider-modern">
                    
                    <!-- Nama & Email -->
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group-modern">
                            <label class="form-label-modern">
                                <i class="bi bi-person-badge"></i> Nama Lengkap *
                            </label>
                            <input type="text" name="name" id="name" class="form-control-modern" 
                                   placeholder="Nama lengkap" required>
                        </div>
                        <div class="form-group-modern">
                            <label class="form-label-modern">
                                <i class="bi bi-envelope"></i> Email
                            </label>
                            <input type="email" name="email" id="email" class="form-control-modern" 
                                   placeholder="email@domain.com">
                        </div>
                    </div>
                    
                    <hr class="divider-modern">
                    
                    <!-- Status -->
                    <div class="form-group-modern">
                        <label class="form-label-modern">
                            <i class="bi bi-toggle-on"></i> Status *
                        </label>
                        <select name="status" id="status" class="form-select-modern" required>
                            <option value="active">✅ Active</option>
                            <option value="inactive">⏸️ Inactive</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-modal secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn-modal primary">
                        <i class="bi bi-save-fill"></i> Simpan
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Modal Delete Confirmation -->
<div class="modal fade modal-modern" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" id="deleteUserId">
            <div class="modal-content">
                <div class="modal-header danger">
                    <h5 class="modal-title">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        Konfirmasi Hapus User
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="delete-user-info">
                        <div class="user-avatar-modern staff" id="deleteUserAvatar">?</div>
                        <div>
                            <div style="font-weight: 700; color: #003D7A;" id="deleteUserName"></div>
                            <div style="font-size: 0.85rem; color: #666;" id="deleteUserUsername"></div>
                        </div>
                    </div>
                    <p style="color: #333; margin-bottom: 0;">
                        Apakah Anda yakin ingin menghapus user ini?
                    </p>
                    <div class="delete-warning">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <p class="delete-warning-text">
                            <strong>Peringatan!</strong> Tindakan ini tidak dapat dibatalkan. 
                            Semua data terkait user ini akan ikut terhapus.
                        </p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-modal secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn-modal danger">
                        <i class="bi bi-trash-fill"></i> Hapus User
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}

function resetForm() {
    document.getElementById('userForm').reset();
    document.getElementById('userId').value = '';
    document.getElementById('modalTitle').innerHTML = '<i class="bi bi-person-plus-fill"></i><span>Tambah User Baru</span>';
    document.getElementById('username').required = true;
    document.getElementById('password').required = true;
    document.getElementById('passwordRequired').style.display = 'inline';
    document.getElementById('passwordHint').textContent = 'Minimal 6 karakter';
}

function editUser(u) {
    document.getElementById('userId').value = u.id;
    document.getElementById('username').value = u.username || '';
    document.getElementById('name').value = u.name || '';
    document.getElementById('email').value = u.email || '';
    document.getElementById('role').value = u.role || 'staff';
    document.getElementById('status').value = u.status || 'active';
    document.getElementById('branch_id').value = u.branch_id || '';
    
    document.getElementById('modalTitle').innerHTML = '<i class="bi bi-pencil-fill"></i><span>Edit User: ' + u.username + '</span>';
    document.getElementById('username').required = false;
    document.getElementById('password').required = false;
    document.getElementById('passwordRequired').style.display = 'none';
    document.getElementById('passwordHint').textContent = 'Kosongkan jika tidak ingin mengubah password';
    
    new bootstrap.Modal(document.getElementById('userModal')).show();
}

function confirmDelete(id, username, name) {
    document.getElementById('deleteUserId').value = id;
    document.getElementById('deleteUserName').textContent = name;
    document.getElementById('deleteUserUsername').textContent = '@' + username;
    document.getElementById('deleteUserAvatar').textContent = name.charAt(0).toUpperCase();
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}

// Responsive grid for modal on mobile
function adjustModalGrid() {
    const grids = document.querySelectorAll('.modal-body > div[style*="grid-template-columns"]');
    if (window.innerWidth < 576) {
        grids.forEach(grid => {
            grid.style.gridTemplateColumns = '1fr';
        });
    } else {
        grids.forEach(grid => {
            grid.style.gridTemplateColumns = '1fr 1fr';
        });
    }
}

window.addEventListener('resize', adjustModalGrid);
window.addEventListener('load', adjustModalGrid);
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>