<?php
session_start();
require_once 'config/database.php';

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

// Handle form submissions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_user':
                $result = addUser($_POST);
                $message = $result['message'];
                $messageType = $result['success'] ? 'success' : 'error';
                break;
                
            case 'edit_user':
                $result = updateUser($_POST);
                $message = $result['message'];
                $messageType = $result['success'] ? 'success' : 'error';
                break;
                
            case 'delete_user':
                $result = deleteUser($_POST['user_id']);
                $message = $result['message'];
                $messageType = $result['success'] ? 'success' : 'error';
                break;
        }
    }
}

// Get all users
$users = getAllUsers();
$positions = getAllPositions();

// Functions
function addUser($data) {
    try {
        $pdo = getPDOConnection();
        
        // Debug: Log received data
        error_log("Add User Data: " . print_r($data, true));
        
        $username = trim($data['username']);
        $password = trim($data['password'] ?? '');
        $full_name = trim($data['full_name']);
        $position_id = $data['position_id'] ?? '';
        $is_admin = isset($data['is_admin']) ? 1 : 0;
        $is_active = isset($data['is_active']) ? 1 : 0;
        
        // Validate required fields
        if (empty($username)) {
            return ['success' => false, 'message' => 'Username tidak boleh kosong!'];
        }
        
        if (empty($password)) {
            return ['success' => false, 'message' => 'Password tidak boleh kosong!'];
        }
        
        if (empty($full_name)) {
            return ['success' => false, 'message' => 'Nama lengkap tidak boleh kosong!'];
        }
        
        // Handle admin position
        if ($position_id === 'admin' || empty($position_id)) {
            $position_id = null;
            if ($data['position_id'] === 'admin') {
                $is_admin = 1;
            }
        }
        
        // Check if username already exists
        $stmt = $pdo->prepare('SELECT id FROM users WHERE username = ?');
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            return ['success' => false, 'message' => 'Username sudah digunakan!'];
        }
        
        // Hash password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        
        // Debug: Log before insert
        error_log("Inserting user: username=$username, position_id=$position_id, is_admin=$is_admin, is_active=$is_active");
        
        // Insert new user - fill BOTH password columns for compatibility
        $stmt = $pdo->prepare('INSERT INTO users (username, password, password_hash, full_name, position_id, is_admin, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)');
        $result = $stmt->execute([$username, $hashedPassword, $hashedPassword, $full_name, $position_id, $is_admin, $is_active]);
        
        if ($result) {
            return ['success' => true, 'message' => 'User berhasil ditambahkan!'];
        } else {
            return ['success' => false, 'message' => 'Gagal menambahkan user ke database!'];
        }
        
    } catch (Exception $e) {
        error_log("Add User Error: " . $e->getMessage());
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

function updateUser($data) {
    try {
        $pdo = getPDOConnection();
        
        $user_id = $data['user_id'];
        $username = trim($data['username']);
        $full_name = trim($data['full_name']);
        $position_id = $data['position_id'];
        $is_admin = isset($data['is_admin']) ? 1 : 0;
        $is_active = isset($data['is_active']) ? 1 : 0;
        
        // Handle admin position
        if ($position_id === 'admin') {
            $position_id = null; // Admin doesn't have a specific position
            $is_admin = 1; // Force admin role
        }
        
        // Check if username already exists (excluding current user)
        $stmt = $pdo->prepare('SELECT id FROM users WHERE username = ? AND id != ?');
        $stmt->execute([$username, $user_id]);
        if ($stmt->fetch()) {
            return ['success' => false, 'message' => 'Username sudah digunakan!'];
        }
        
        // Update user
        $sql = 'UPDATE users SET username = ?, full_name = ?, position_id = ?, is_admin = ?, is_active = ?';
        $params = [$username, $full_name, $position_id, $is_admin, $is_active];
        
        // Update password if provided
        if (!empty($data['password'])) {
            $sql .= ', password_hash = ?';
            $params[] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        
        $sql .= ' WHERE id = ?';
        $params[] = $user_id;
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        return ['success' => true, 'message' => 'User berhasil diperbarui!'];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

function deleteUser($user_id) {
    try {
        $pdo = getPDOConnection();
        
        // Check if user exists
        $stmt = $pdo->prepare('SELECT id FROM users WHERE id = ?');
        $stmt->execute([$user_id]);
        if (!$stmt->fetch()) {
            return ['success' => false, 'message' => 'User tidak ditemukan!'];
        }
        
        // Delete user
        $stmt = $pdo->prepare('DELETE FROM users WHERE id = ?');
        $stmt->execute([$user_id]);
        
        return ['success' => true, 'message' => 'User berhasil dihapus!'];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

function getAllUsers() {
    try {
        $pdo = getPDOConnection();
        $stmt = $pdo->prepare('
            SELECT u.*, 
                   CASE 
                       WHEN u.is_admin = 1 AND u.position_id IS NULL THEN "Admin"
                       ELSE p.name 
                   END as position_name 
            FROM users u 
            LEFT JOIN positions p ON u.position_id = p.id 
            ORDER BY u.id
        ');
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (Exception $e) {
        return [];
    }
}

function getAllPositions() {
    try {
        $pdo = getPDOConnection();
        $stmt = $pdo->prepare('SELECT * FROM positions ORDER BY name');
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (Exception $e) {
        return [];
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel - Info Hadir</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #0b1021, #1a1f3a);
            min-height: 100vh;
            padding: 20px;
            color: #e5e7eb;
            position: relative;
            overflow-x: hidden;
        }
        
        /* Background Animation - matching dashboard */
        .bg-animation {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            pointer-events: none;
            overflow: hidden;
        }
        
        .particle {
            position: absolute;
            width: 4px;
            height: 4px;
            background: rgba(47, 107, 255, 0.4);
            border-radius: 50%;
            animation: float 20s infinite ease-in-out;
        }
        
        .particle:nth-child(1) { left: 10%; animation-delay: 0s; animation-duration: 25s; }
        .particle:nth-child(2) { left: 20%; animation-delay: 2s; animation-duration: 22s; }
        .particle:nth-child(3) { left: 30%; animation-delay: 4s; animation-duration: 28s; }
        .particle:nth-child(4) { left: 40%; animation-delay: 1s; animation-duration: 24s; }
        .particle:nth-child(5) { left: 50%; animation-delay: 3s; animation-duration: 26s; }
        .particle:nth-child(6) { left: 60%; animation-delay: 5s; animation-duration: 23s; }
        .particle:nth-child(7) { left: 70%; animation-delay: 2s; animation-duration: 27s; }
        .particle:nth-child(8) { left: 80%; animation-delay: 4s; animation-duration: 25s; }
        .particle:nth-child(9) { left: 90%; animation-delay: 1s; animation-duration: 29s; }
        .particle:nth-child(10) { left: 15%; animation-delay: 3s; animation-duration: 21s; }
        
        @keyframes float {
            0%, 100% { transform: translateY(100vh) translateX(0) scale(0); opacity: 0; }
            10% { opacity: 1; }
            90% { opacity: 1; }
            100% { transform: translateY(-100vh) translateX(100px) scale(1); opacity: 0; }
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: rgba(17, 24, 39, 0.85);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
            overflow: hidden;
            border: 1px solid rgba(255, 255, 255, 0.1);
            position: relative;
            z-index: 1;
        }
        
        .header {
            background: linear-gradient(135deg, rgba(47, 107, 255, 0.2), rgba(30, 64, 175, 0.2));
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            color: white;
            padding: 40px 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: clamp(1.8rem, 4vw, 2.5rem);
            margin-bottom: 10px;
            font-weight: 800;
            letter-spacing: -0.02em;
            text-shadow: 0 2px 10px rgba(47, 107, 255, 0.3);
        }
        
        .header p {
            opacity: 0.8;
            font-size: clamp(0.9rem, 2vw, 1.1rem);
            font-weight: 400;
        }
        
        .content {
            padding: 30px;
        }
        
        .actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            font-family: 'Inter', sans-serif;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #2f6bff, #1e40af);
            color: white;
            box-shadow: 0 4px 15px rgba(47, 107, 255, 0.3);
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(47, 107, 255, 0.4);
        }
        
        .btn-secondary {
            background: rgba(107, 114, 128, 0.2);
            color: #e5e7eb;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .btn-secondary:hover {
            background: rgba(107, 114, 128, 0.3);
            border-color: rgba(255, 255, 255, 0.2);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
            box-shadow: 0 4px 15px rgba(239, 68, 68, 0.3);
        }
        
        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(239, 68, 68, 0.4);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
        }
        
        .btn-sm {
            padding: 8px 16px;
            font-size: 13px;
        }
        
        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 12px;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .alert-success {
            background: rgba(16, 185, 129, 0.15);
            color: #6ee7b7;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }
        
        .alert-error {
            background: rgba(239, 68, 68, 0.15);
            color: #fca5a5;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }
        
        .table-container {
            background: rgba(31, 41, 55, 0.5);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .table-wrapper {
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }
        
        th, td {
            padding: 16px;
            text-align: left;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        th {
            background: rgba(47, 107, 255, 0.1);
            font-weight: 700;
            color: #93c5fd;
            text-transform: uppercase;
            font-size: 13px;
            letter-spacing: 0.05em;
        }
        
        td {
            color: #d1d5db;
            font-size: 14px;
        }
        
        tr:hover {
            background: rgba(47, 107, 255, 0.05);
        }
        
        .badge {
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
        }
        
        .badge-success {
            background: rgba(16, 185, 129, 0.2);
            color: #6ee7b7;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }
        
        .badge-danger {
            background: rgba(239, 68, 68, 0.2);
            color: #fca5a5;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }
        
        .badge-primary {
            background: rgba(47, 107, 255, 0.2);
            color: #93c5fd;
            border: 1px solid rgba(47, 107, 255, 0.3);
        }
        
        .badge-secondary {
            background: rgba(107, 114, 128, 0.2);
            color: #9ca3af;
            border: 1px solid rgba(107, 114, 128, 0.3);
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(5px);
            z-index: 2000;
            animation: fadeIn 0.2s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .modal-content {
            background: rgba(17, 24, 39, 0.95);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            padding: 30px;
            max-width: 500px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
            animation: slideUp 0.3s ease;
        }
        
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .modal-header h2 {
            color: #f3f4f6;
            font-size: 1.5rem;
            font-weight: 700;
        }
        
        .close {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid rgba(239, 68, 68, 0.3);
            width: 36px;
            height: 36px;
            border-radius: 8px;
            font-size: 20px;
            cursor: pointer;
            color: #fca5a5;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }
        
        .close:hover {
            background: rgba(239, 68, 68, 0.3);
            transform: rotate(90deg);
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #d1d5db;
            font-size: 14px;
        }
        
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 10px;
            font-size: 15px;
            background: rgba(31, 41, 55, 0.5);
            color: #f3f4f6;
            font-family: 'Inter', sans-serif;
            transition: all 0.2s ease;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #2f6bff;
            background: rgba(31, 41, 55, 0.7);
            box-shadow: 0 0 0 3px rgba(47, 107, 255, 0.1);
        }
        
        .form-group small {
            display: block;
            margin-top: 6px;
            color: #9ca3af;
            font-size: 12px;
        }
        
        .form-checkbox {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px;
            background: rgba(31, 41, 55, 0.3);
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .form-checkbox input {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        
        .form-checkbox label {
            margin: 0;
            cursor: pointer;
        }
        
        .modal-footer {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .loading {
            text-align: center;
            padding: 40px 20px;
            color: #9ca3af;
        }
        
        .loading i {
            font-size: 24px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        /* Responsive Design */
        @media (max-width: 1024px) {
            .content {
                padding: 25px;
            }
        }
        
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .header {
                padding: 30px 20px;
            }
            
            .content {
                padding: 20px;
            }
            
            .actions {
                flex-direction: column;
                align-items: stretch;
            }
            
            .btn {
                justify-content: center;
                width: 100%;
            }
            
            .table-wrapper {
                margin: 0 -20px;
                padding: 0 20px;
            }
            
            table {
                font-size: 13px;
            }
            
            th, td {
                padding: 12px 8px;
            }
            
            th {
                font-size: 11px;
            }
            
            .btn-sm {
                padding: 6px 12px;
                font-size: 12px;
            }
            
            .modal-content {
                padding: 25px 20px;
            }
        }
        
        @media (max-width: 480px) {
            .header h1 {
                font-size: 1.5rem;
            }
            
            .header p {
                font-size: 0.85rem;
            }
            
            th:nth-child(4),
            td:nth-child(4) {
                display: none;
            }
            
            .badge {
                font-size: 10px;
                padding: 4px 10px;
            }
        }
    </style>
</head>
<body>
    <!-- Background Animation - matching dashboard -->
    <div class="bg-animation">
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
        <div class="particle"></div>
    </div>
    
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-users-cog"></i> Admin Panel</h1>
            <p>Kelola User dan Data Sistem</p>
        </div>
        
        <div class="content">
            <!-- Messages -->
            <?php if ($message): ?>
                <div class="alert alert-<?= $messageType ?>">
                    <i class="fas fa-<?= $messageType === 'success' ? 'check-circle' : 'exclamation-circle' ?>"></i>
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>
            
            <!-- Actions -->
            <div class="actions">
                <div>
                    <button class="btn btn-primary" onclick="openModal('add')">
                        <i class="fas fa-plus"></i> Tambah User
                    </button>
                </div>
                <div>
                    <a href="dashboard.html" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
                    </a>
                </div>
            </div>
            
            <!-- Users Table -->
            <div class="table-container">
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Username</th>
                                <th>Nama Lengkap</th>
                                <th>Jabatan</th>
                                <th>Status</th>
                                <th>Role</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($users)): ?>
                                <tr>
                                    <td colspan="7" class="loading">
                                        <i class="fas fa-spinner fa-spin"></i> Memuat data...
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($users as $user): ?>
                                    <tr data-user-id="<?= $user['id'] ?>">
                                        <td><?= $user['id'] ?></td>
                                        <td><?= htmlspecialchars($user['username']) ?></td>
                                        <td><?= htmlspecialchars($user['full_name']) ?></td>
                                        <td><?= htmlspecialchars($user['position_name'] ?? 'Tidak ada') ?></td>
                                        <td>
                                            <span class="badge <?= $user['is_active'] ? 'badge-success' : 'badge-danger' ?>">
                                                <?= $user['is_active'] ? 'Aktif' : 'Tidak Aktif' ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge <?= $user['is_admin'] ? 'badge-primary' : 'badge-secondary' ?>">
                                                <?= $user['is_admin'] ? 'Admin' : 'User' ?>
                                            </span>
                                        </td>
                                        <td>
                                            <button class="btn btn-success btn-sm" onclick='editUser(<?= json_encode($user) ?>)'>
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                                <button class="btn btn-danger btn-sm" onclick="deleteUser(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username']) ?>')">
                                                    <i class="fas fa-trash"></i> Hapus
                                                </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Add/Edit User Modal -->
    <div id="userModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">Tambah User</h2>
                <button class="close" onclick="closeModal()">&times;</button>
            </div>
            
            <form id="userForm" method="POST">
                <input type="hidden" name="action" id="formAction" value="add_user">
                <input type="hidden" name="user_id" id="userId" value="">
                
                <div class="form-group">
                    <label for="username">Username *</label>
                    <input type="text" id="username" name="username" required>
                </div>
                
                <div class="form-group">
                    <label for="password">Password *</label>
                    <input type="password" id="password" name="password">
                    <small style="color: #6b7280;" id="passwordHint">Wajib diisi untuk user baru. Kosongkan jika tidak ingin mengubah password (untuk edit)</small>
                </div>
                
                <div class="form-group">
                    <label for="full_name">Nama Lengkap *</label>
                    <input type="text" id="full_name" name="full_name" required>
                </div>
                
                <div class="form-group">
                    <label for="position_id">Jabatan</label>
                    <select id="position_id" name="position_id">
                        <option value="">Pilih Jabatan</option>
                        <option value="admin">Admin</option>
                        <?php foreach ($positions as $position): ?>
                            <option value="<?= $position['id'] ?>"><?= htmlspecialchars($position['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <div class="form-checkbox">
                        <input type="checkbox" id="is_admin" name="is_admin">
                        <label for="is_admin">Admin</label>
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="form-checkbox">
                        <input type="checkbox" id="is_active" name="is_active" checked>
                        <label for="is_active">Aktif</label>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Batal</button>
                    <button type="submit" class="btn btn-primary">Simpan</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Konfirmasi Hapus</h2>
                <button class="close" onclick="closeDeleteModal()">&times;</button>
            </div>
            
            <div style="padding: 20px 0;">
                <p style="margin-bottom: 20px;">
                    Apakah Anda yakin ingin menghapus user <strong id="deleteUserName"></strong>?
                </p>
                <p style="color: #ef4444; font-size: 14px;">
                    <i class="fas fa-exclamation-triangle"></i> Tindakan ini tidak dapat dibatalkan!
                </p>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeDeleteModal()">Batal</button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">Hapus</button>
            </div>
        </div>
    </div>
    
    <script>
        let currentUserId = null;
        
        function openModal(action) {
            const modal = document.getElementById('userModal');
            const form = document.getElementById('userForm');
            const modalTitle = document.getElementById('modalTitle');
            const formAction = document.getElementById('formAction');
            const userIdInput = document.getElementById('userId');
            const passwordInput = document.getElementById('password');
            const passwordHint = document.getElementById('passwordHint');
            
            modalTitle.textContent = 'Tambah User';
            formAction.value = 'add_user';
            userIdInput.value = '';
            form.reset();
            passwordInput.required = true;
            passwordHint.textContent = 'Wajib diisi untuk user baru';
            document.getElementById('is_active').checked = true;
            
            modal.classList.add('show');
        }
        
        function editUser(user) {
            const modal = document.getElementById('userModal');
            const modalTitle = document.getElementById('modalTitle');
            const formAction = document.getElementById('formAction');
            const passwordInput = document.getElementById('password');
            const passwordHint = document.getElementById('passwordHint');
            
            modalTitle.textContent = 'Edit User';
            formAction.value = 'edit_user';
            passwordInput.required = false;
            passwordHint.textContent = 'Kosongkan jika tidak ingin mengubah password';
            
            // Fill form with user data
            document.getElementById('userId').value = user.id;
            document.getElementById('username').value = user.username;
            document.getElementById('full_name').value = user.full_name;
            document.getElementById('password').value = '';
            
            // Set position
            const positionSelect = document.getElementById('position_id');
            if (user.is_admin && !user.position_id) {
                positionSelect.value = 'admin';
            } else {
                positionSelect.value = user.position_id || '';
            }
            
            // Set checkboxes
            document.getElementById('is_admin').checked = user.is_admin == 1;
            document.getElementById('is_active').checked = user.is_active == 1;
            
            modal.classList.add('show');
        }
        
        function closeModal() {
            document.getElementById('userModal').classList.remove('show');
        }
        
        function deleteUser(userId, username) {
            currentUserId = userId;
            document.getElementById('deleteUserName').textContent = username;
            document.getElementById('deleteModal').classList.add('show');
        }
        
        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.remove('show');
            currentUserId = null;
        }
        
        function confirmDelete() {
            if (currentUserId) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_id" value="${currentUserId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            const userModal = document.getElementById('userModal');
            const deleteModal = document.getElementById('deleteModal');
            
            if (event.target === userModal) {
                closeModal();
            }
            if (event.target === deleteModal) {
                closeDeleteModal();
            }
        }
    </script>
</body>
</html>
