<?php
ob_start();
include 'config.php';
checkLogin(); 
onlyAdmin(); 

// --- 1. LOGIKA PROSES (DI ATAS SEGALANYA) ---

// Logika Tambah User
if(isset($_POST['add_user'])) {
    $nama = mysqli_real_escape_string($conn, $_POST['nama_operator']);
    $user = mysqli_real_escape_string($conn, $_POST['username']);
    $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = $_POST['role'];

    // Cek Username Double
    $cek = mysqli_query($conn, "SELECT id FROM users WHERE username = '$user'");
    if(mysqli_num_rows($cek) > 0) {
        header("Location: users.php?status=exists");
        exit;
    }

    $sql = "INSERT INTO users (nama_operator, username, password, role, created_at) VALUES ('$nama', '$user', '$pass', '$role', NOW())";
    if(mysqli_query($conn, $sql)) {
        write_log($conn, "TAMBAH USER", "Menambahkan operator baru: $nama ($role)");
        header("Location: users.php?status=success");
        exit;
    }
}

// Logika Hapus User
if(isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    if($id == $_SESSION['user_id']) {
        header("Location: users.php?status=error_self");
        exit;
    } else {
        mysqli_query($conn, "DELETE FROM users WHERE id='$id'");
        write_log($conn, "HAPUS USER", "Menghapus user ID: $id");
        header("Location: users.php?status=deleted");
        exit;
    }
}

// --- 2. AMBIL DATA ---
$users = mysqli_query($conn, "SELECT * FROM users ORDER BY role ASC, nama_operator ASC");
$count_q = mysqli_query($conn, "SELECT role, COUNT(*) as jml FROM users GROUP BY role");
$stats = ['admin' => 0, 'pegawai' => 0];
while($c = mysqli_fetch_assoc($count_q)) { $stats[$c['role']] = $c['jml']; }

$page_title = "Operator Management";
$active_page = "users";
include 'layout.php';
?>

<style>
    :root {
        --glass: rgba(30, 41, 59, 0.7);
        --border: rgba(255, 255, 255, 0.08);
        --accent-p: #8b5cf6;
        --accent-c: #06b6d4;
    }

    .users-layout { display: grid; grid-template-columns: 380px 1fr; gap: 30px; }

    /* Stats Section */
    .stats-row { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 25px; }
    .stat-card {
        background: var(--glass); border: 1px solid var(--border); padding: 20px; border-radius: 20px;
        display: flex; align-items: center; gap: 15px; backdrop-filter: blur(10px);
    }
    .icon-box { width: 50px; height: 50px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; }

    /* Component Glass */
    .glass-panel {
        background: var(--glass); border: 1px solid var(--border); border-radius: 24px; padding: 30px;
        position: relative; overflow: hidden; backdrop-filter: blur(12px);
    }
    .glass-panel::before { content: ''; position: absolute; top:0; left:0; width: 100%; height: 4px; background: linear-gradient(90deg, var(--accent-p), var(--accent-c)); }

    /* Form Styles */
    .form-group { margin-bottom: 18px; }
    .form-group label { display: block; color: #94a3b8; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; margin-bottom: 8px; letter-spacing: 1px; }
    .input-modern {
        width: 100%; background: rgba(15, 23, 42, 0.6); border: 1px solid var(--border);
        padding: 12px 15px; border-radius: 12px; color: #fff; font-size: 0.95rem; outline: none; transition: 0.3s;
    }
    .input-modern:focus { border-color: var(--accent-p); box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.1); }
    
    .pass-container { position: relative; }
    .btn-eye { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #64748b; cursor: pointer; font-size: 1.2rem; }

    /* Table Styles */
    .custom-table { width: 100%; border-collapse: collapse; }
    .custom-table th { text-align: left; padding: 15px; color: #64748b; font-size: 0.75rem; text-transform: uppercase; border-bottom: 1px solid var(--border); }
    .custom-table td { padding: 15px; border-bottom: 1px solid rgba(255,255,255,0.03); vertical-align: middle; transition: 0.2s; }
    .custom-table tr:hover td { background: rgba(255,255,255,0.02); }

    .user-avatar {
        width: 42px; height: 42px; border-radius: 12px; font-weight: 800; color: #fff;
        display: flex; align-items: center; justify-content: center;
        background: linear-gradient(135deg, #334155, #1e293b); border: 1px solid var(--border);
    }
    
    .role-badge { padding: 4px 10px; border-radius: 8px; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; }
    .badge-admin { background: rgba(139, 92, 246, 0.15); color: #a78bfa; border: 1px solid rgba(139, 92, 246, 0.3); }
    .badge-pegawai { background: rgba(6, 182, 212, 0.15); color: #22d3ee; border: 1px solid rgba(6, 182, 212, 0.3); }

    .btn-del {
        width: 38px; height: 38px; border-radius: 10px; background: rgba(244, 63, 94, 0.1); color: #f43f5e;
        display: flex; align-items: center; justify-content: center; font-size: 1.2rem; transition: 0.3s; border: none; cursor: pointer;
    }
    .btn-del:hover { background: #f43f5e; color: #fff; transform: scale(1.1) rotate(10deg); }

    @media (max-width: 1024px) { .users-layout { grid-template-columns: 1fr; } }
</style>

<!-- STATS CARDS -->
<div class="stats-row">
    <div class="stat-card">
        <div class="icon-box" style="background: rgba(139, 92, 246, 0.15); color: var(--accent-p);"><i class='bx bxs-crown'></i></div>
        <div><div style="color:#64748b; font-size:0.75rem;">ADMINISTRATOR</div><div style="color:#fff; font-weight:800; font-size:1.4rem;"><?= $stats['admin'] ?></div></div>
    </div>
    <div class="stat-card">
        <div class="icon-box" style="background: rgba(6, 182, 212, 0.15); color: var(--accent-c);"><i class='bx bxs-user-account'></i></div>
        <div><div style="color:#64748b; font-size:0.75rem;">TOTAL OPERATOR</div><div style="color:#fff; font-weight:800; font-size:1.4rem;"><?= $stats['pegawai'] ?></div></div>
    </div>
</div>

<div class="users-layout">
    <!-- LEFT: REGISTRATION -->
    <div class="glass-panel">
        <h3 style="color:#fff; margin-bottom:25px; display:flex; align-items:center; gap:10px;"><i class='bx bxs-user-plus'></i> Tambah Operator</h3>
        <form method="POST">
            <div class="form-group">
                <label>Nama Lengkap</label>
                <input type="text" name="nama_operator" class="input-modern" placeholder="Nama Asli Pegawai" required>
            </div>
            <div class="form-group">
                <label>Username Login</label>
                <input type="text" name="username" class="input-modern" placeholder="Contoh: agus_escobar" required autocomplete="off">
            </div>
            <div class="form-group">
                <label>Password</label>
                <div class="pass-container">
                    <input type="password" name="password" id="passInput" class="input-modern" placeholder="Min 6 Karakter" required>
                    <i class='bx bx-show btn-eye' id="eyeIcon" onclick="togglePass()"></i>
                </div>
            </div>
            <div class="form-group">
                <label>Role Akses</label>
                <select name="role" class="input-modern">
                    <option value="pegawai">Pegawai / Operator</option>
                    <option value="admin">Administrator (Owner)</option>
                </select>
            </div>
            <button type="submit" name="add_user" class="btn btn-primary" style="width:100%; margin-top:10px;">DAFTARKAN SEKARANG</button>
        </form>
    </div>

    <!-- RIGHT: LIST -->
    <div class="glass-panel">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:25px;">
            <h3 style="color:#fff; margin:0;"><i class='bx bxs-group'></i> Database User</h3>
            <input type="text" id="searchOp" class="input-modern" placeholder="Cari operator..." style="width:200px; padding:8px 15px; font-size:0.8rem;">
        </div>

        <div style="overflow-x: auto;">
            <table class="custom-table" id="opTable">
                <thead>
                    <tr>
                        <th>Operator</th>
                        <th>ID Login</th>
                        <th>Role</th>
                        <th style="text-align:right;">Opsi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($u = mysqli_fetch_assoc($users)): 
                        $init = strtoupper(substr($u['nama_operator'], 0, 1));
                    ?>
                    <tr>
                        <td>
                            <div style="display:flex; align-items:center; gap:12px;">
                                <div class="user-avatar"><?= $init ?></div>
                                <div>
                                    <div style="color:#fff; font-weight:700;"><?= htmlspecialchars($u['nama_operator']) ?></div>
                                    <div style="color:#475569; font-size:0.65rem;">DIBUAT: <?= isset($u['created_at']) ? date('d/m/y', strtotime($u['created_at'])) : '-' ?></div>
                                </div>
                            </div>
                        </td>
                        <td><code style="color:var(--accent-c); background:rgba(6,182,212,0.05); padding:3px 7px; border-radius:5px;"><?= htmlspecialchars($u['username']) ?></code></td>
                        <td>
                            <span class="role-badge <?= $u['role'] == 'admin' ? 'badge-admin' : 'badge-pegawai' ?>">
                                <?= $u['role'] ?>
                            </span>
                        </td>
                        <td style="text-align:right;">
                            <?php if($u['id'] != $_SESSION['user_id']): ?>
                                <div style="display:flex; justify-content:flex-end;">
                                    <button class="btn-del" onclick="confirmDel(<?= $u['id'] ?>, '<?= htmlspecialchars($u['nama_operator']) ?>')">
                                        <i class='bx bxs-trash-alt'></i>
                                    </button>
                                </div>
                            <?php else: ?>
                                <span style="font-size:0.7rem; color:var(--accent-p); font-weight:800; letter-spacing:1px;">YOU</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// Toggle Password
function togglePass() {
    const input = document.getElementById('passInput');
    const eye = document.getElementById('eyeIcon');
    if(input.type === 'password') {
        input.type = 'text';
        eye.classList.replace('bx-show', 'bx-hide');
    } else {
        input.type = 'password';
        eye.classList.replace('bx-hide', 'bx-show');
    }
}

// Live Search
document.getElementById('searchOp').addEventListener('keyup', function() {
    let filter = this.value.toUpperCase();
    let tr = document.getElementById('opTable').getElementsByTagName('tr');
    for (let i = 1; i < tr.length; i++) {
        let td = tr[i].getElementsByTagName('td')[0];
        if (td) {
            let text = td.textContent || td.innerText;
            tr[i].style.display = text.toUpperCase().indexOf(filter) > -1 ? "" : "none";
        }
    }
});

// SweetAlert Delete
function confirmDel(id, name) {
    Swal.fire({
        title: 'Hapus Operator?',
        text: "Akun " + name + " tidak akan bisa login lagi!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#f43f5e',
        cancelButtonColor: '#334155',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal',
        background: '#1e293b',
        color: '#fff'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = '?delete=' + id;
        }
    })
}

// SweetAlert Auto Notifications
document.addEventListener('DOMContentLoaded', function() {
    const params = new URLSearchParams(window.location.search);
    const status = params.get('status');
    if(status === 'success') {
        Swal.fire({ icon: 'success', title: 'Berhasil!', text: 'Operator baru telah aktif.', timer: 2000, showConfirmButton: false, background: '#1e293b', color: '#fff' });
    } else if(status === 'deleted') {
        Swal.fire({ icon: 'info', title: 'Dihapus', text: 'Akses operator telah dicabut.', timer: 2000, showConfirmButton: false, background: '#1e293b', color: '#fff' });
    } else if(status === 'exists') {
        Swal.fire({ icon: 'error', title: 'Gagal!', text: 'Username sudah digunakan orang lain.', background: '#1e293b', color: '#fff' });
    } else if(status === 'error_self') {
        Swal.fire({ icon: 'error', title: 'Ditolak!', text: 'Anda tidak bisa menghapus diri sendiri.', background: '#1e293b', color: '#fff' });
    }
});
</script>

<?php 
echo "</div></body></html>"; 
ob_end_flush();
?>