<?php
// pages/users.php
if (session_status() === PHP_SESSION_NONE) session_start();
include "koneksi.php";

// Cek login
if (!isset($_SESSION['user_id'])) {
    echo "<div class='alert alert-warning'>Silakan <a href='login.php'>login</a> terlebih dahulu.</div>";
    return;
}

// Cek role admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo "<div class='alert alert-danger'>Akses hanya untuk admin!</div>";
    return;
}

// ===== Inisialisasi variabel form =====
$id_edit = 0;
$username_edit = '';
$nama_edit = '';
$role_edit = 'kasir';
$password_edit = '';

// ===== Proses CRUD =====

// Tambah user
if (isset($_POST['tambah'])) {
    $username = trim($_POST['username']);
    $nama = trim($_POST['nama']);
    $role = $_POST['role'] ?? 'kasir';
    $password_raw = $_POST['password'] ?? '';

    if ($username === '' || $password_raw === '') {
        $error = "Username dan password wajib diisi.";
    } else {
        $cek = $conn->prepare("SELECT id FROM users WHERE username = ?");
        $cek->bind_param("s", $username);
        $cek->execute();
        $res = $cek->get_result();
        if ($res->num_rows > 0) {
            $error = "Username sudah dipakai.";
        } else {
            $password = password_hash($password_raw, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO users (username,password,role,nama_lengkap) VALUES (?,?,?,?)");
            $stmt->bind_param("ssss", $username, $password, $role, $nama);
            if ($stmt->execute()) {
                $success = "User berhasil ditambahkan!";
            } else {
                $error = "Gagal tambah user: " . htmlspecialchars($stmt->error);
            }
        }
    }
}

// Edit user (ambil data)
if (isset($_GET['edit'])) {
    $id_edit = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT id, username, nama_lengkap, role FROM users WHERE id=?");
    $stmt->bind_param("i", $id_edit);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        $username_edit = $row['username'];
        $nama_edit = $row['nama_lengkap'];
        $role_edit = $row['role'];
    } else {
        $id_edit = 0;
    }
}

// Update user
if (isset($_POST['edit'])) {
    $id = intval($_POST['id']);
    $username = trim($_POST['username']);
    $nama = trim($_POST['nama']);
    $role = $_POST['role'] ?? 'kasir';
    $password_raw = $_POST['password'] ?? '';

    $cek = $conn->prepare("SELECT id FROM users WHERE username=? AND id<>?");
    $cek->bind_param("si", $username, $id);
    $cek->execute();
    $res = $cek->get_result();
    if ($res->num_rows > 0) {
        $error = "Username sudah dipakai oleh user lain.";
    } else {
        if ($password_raw !== '') {
            $password = password_hash($password_raw, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET username=?, nama_lengkap=?, role=?, password=? WHERE id=?");
            $stmt->bind_param("ssssi", $username, $nama, $role, $password, $id);
        } else {
            $stmt = $conn->prepare("UPDATE users SET username=?, nama_lengkap=?, role=? WHERE id=?");
            $stmt->bind_param("sssi", $username, $nama, $role, $id);
        }
        if ($stmt->execute()) {
            $success = "User berhasil diperbarui!";
            // Reset form
            $id_edit = 0;
            $username_edit = '';
            $nama_edit = '';
            $role_edit = 'kasir';
        } else {
            $error = "Gagal update user: " . htmlspecialchars($stmt->error);
        }
    }
}

// Hapus user
if (isset($_GET['hapus'])) {
    $id = intval($_GET['hapus']);
    if ($id === (int)$_SESSION['user_id']) {
        $error = "Anda tidak dapat menghapus akun sendiri.";
    } else {
        $stmt = $conn->prepare("DELETE FROM users WHERE id=?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $success = "User dihapus!";
        } else {
            $error = "Gagal hapus user: " . htmlspecialchars($stmt->error);
        }
    }
}

// Ambil semua user
$users = $conn->query("SELECT id, username, nama_lengkap, role FROM users ORDER BY id DESC");
?>

<div class="container">
    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-users me-2"></i> Manajemen User</h5>
        </div>
        <div class="card-body">
            <?php if (!empty($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>
            <?php if (!empty($success)) echo "<div class='alert alert-success'>$success</div>"; ?>

            <!-- FORM TAMBAH/EDIT -->
            <form method="post" class="mb-4">
                <input type="hidden" name="id" value="<?= $id_edit ?>">
                <div class="row g-3 align-items-end">
                    <div class="col-md-3">
                        <label>Username</label>
                        <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($username_edit) ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label>Nama Lengkap</label>
                        <input type="text" name="nama" class="form-control" value="<?= htmlspecialchars($nama_edit) ?>">
                    </div>
                    <div class="col-md-2">
                        <label>Password</label>
                        <input type="text" name="password" class="form-control" placeholder="<?= $id_edit ? 'Kosongkan jika tidak diubah' : '' ?>">
                    </div>
                    <div class="col-md-2">
                        <label>Role</label>
                        <select name="role" class="form-select">
                            <option value="admin" <?= $role_edit=='admin'?'selected':'' ?>>Admin</option>
                            <option value="kasir" <?= $role_edit=='kasir'?'selected':'' ?>>Kasir</option>
                            <option value="owner" <?= $role_edit=='owner'?'selected':'' ?>>Owner</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" name="<?= $id_edit?'edit':'tambah' ?>" class="btn btn-success w-100">
                            <?= $id_edit ? 'Update User' : 'Tambah User' ?>
                        </button>
                    </div>
                </div>
            </form>

            <!-- TABEL USER -->
            <div class="table-responsive">
                <table class="table table-bordered table-striped align-middle">
                    <thead class="table-dark">
                        <tr>
                            <th>ID</th>
                            <th>Username</th>
                            <th>Nama Lengkap</th>
                            <th>Role</th>
                            <th width="140">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if ($users && $users->num_rows > 0): ?>
                        <?php while ($u = $users->fetch_assoc()): ?>
                        <tr>
                            <td><?= (int)$u['id'] ?></td>
                            <td><?= htmlspecialchars($u['username']) ?></td>
                            <td><?= htmlspecialchars($u['nama_lengkap']) ?></td>
                            <td>
                                <span class="badge bg-<?= $u['role']=='admin' ? 'danger' : ($u['role']=='owner' ? 'success' : 'secondary') ?>">
                                    <?= htmlspecialchars($u['role']) ?>
                                </span>
                            </td>
                            <td>
                                <a href="index.php?page=users&edit=<?= (int)$u['id'] ?>" class="btn btn-sm btn-warning">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php if ((int)$_SESSION['user_id'] !== (int)$u['id']): ?>
                                    <a href="index.php?page=users&hapus=<?= (int)$u['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin hapus user ini?')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                <?php else: ?>
                                    <button class="btn btn-sm btn-secondary" disabled title="Tidak bisa hapus diri sendiri">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="text-center">Belum ada user</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
