<?php
session_start();
include 'db.php';

// 🔐 Hanya admin yang boleh mengakses
if (!isset($_SESSION['username']) || $_SESSION['username'] !== "admin@admin.com") {
    header("Location: login.php");
    exit;
}

$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

$message = "";
$hasil = [];

/* =========================
   🔍 PENCARIAN BARANG
========================= */
if (isset($_POST['cari'])) {
    $kata = trim($_POST['kata'] ?? '');
    if ($kata === '') {
        $message = "<p style='color:red;'>❌ Masukkan minimal satu kata!</p>";
    } else {
        $like = "%" . strtolower($kata) . "%";
        $stmt = $conn->prepare("SELECT no_id, Nama_barang, Harga, Stok, Diskon, Gbr_brg FROM barang WHERE LOWER(Nama_barang) LIKE ?");
        $stmt->bind_param("s", $like);
        $stmt->execute();
        $result = $stmt->get_result();
        $hasil = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        if (count($hasil) === 0) {
            $message = "<p style='color:red;'>Tidak ada barang yang cocok dengan kata '<b>" . htmlspecialchars($kata) . "</b>'.</p>";
        }
    }
}

/* =========================
   🚮 HAPUS SATU BARANG
========================= */
if (isset($_POST['hapus_id'])) {
    $id = (int)$_POST['hapus_id'];

    // Ambil data barang
    $ambil = $conn->prepare("SELECT Nama_barang, Harga, Stok, Diskon, Gbr_brg FROM barang WHERE no_id = ?");
    $ambil->bind_param("i", $id);
    $ambil->execute();
    $result = $ambil->get_result();
    $barang = $result->fetch_assoc();
    $ambil->close();

    if ($barang) {
        $conn->begin_transaction();
        try {
            // Simpan ke Recycle Bin
            $simpan = $conn->prepare("
                INSERT INTO barang_deleted (Nama_barang, Harga, Stok, Diskon, Gbr_brg, Tanggal_dihapus)
                VALUES (?, ?, ?, ?, ?, NOW())
            ");
            $simpan->bind_param(
                "sddds",
                $barang['Nama_barang'],
                $barang['Harga'],
                $barang['Stok'],
                $barang['Diskon'],
                $barang['Gbr_brg']
            );
            $simpan->execute();
            $simpan->close();

            // Hapus dari tabel barang
            $hapus = $conn->prepare("DELETE FROM barang WHERE no_id = ?");
            $hapus->bind_param("i", $id);
            $hapus->execute();
            $hapus->close();

            // Catat ke log admin
            $ket = "Admin menghapus barang: " . $barang['Nama_barang'];
            $log = $conn->prepare("INSERT INTO admin_log (Aksi, Waktu, Keterangan) VALUES ('Hapus Barang', NOW(), ?)");
            $log->bind_param("s", $ket);
            $log->execute();
            $log->close();

            $conn->commit();
            $message = "<p style='color:green;'>✅ Barang '<b>" . htmlspecialchars($barang['Nama_barang']) . "</b>' berhasil dihapus dan dipindahkan ke Recycle Bin.</p>";
        } catch (Exception $e) {
            $conn->rollback();
            $message = "<p style='color:red;'>❌ Gagal menghapus barang: " . htmlspecialchars($e->getMessage()) . "</p>";
        }
    } else {
        $message = "<p style='color:red;'>❌ Barang tidak ditemukan!</p>";
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>🗑️ Hapus Barang Cepat</title>
<style>
    body {
        font-family: Arial, sans-serif;
        margin: 40px;
        background-color: #f9f9f9;
    }
    h2 { color: #333; }
    form {
        background: #fff;
        padding: 20px;
        width: 450px;
        border-radius: 12px;
        box-shadow: 0 0 6px rgba(0,0,0,0.1);
        margin-bottom: 30px;
    }
    input[type=text] {
        width: 95%;
        padding: 8px;
        margin-top: 6px;
        border: 1px solid #ccc;
        border-radius: 6px;
    }
    button {
        margin-top: 10px;
        padding: 8px 16px;
        background-color: #dc3545;
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
    }
    button:hover {
        background-color: #b02a37;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        background: #fff;
        box-shadow: 0 0 6px rgba(0,0,0,0.1);
    }
    th, td {
        padding: 10px;
        border: 1px solid #ddd;
        text-align: center;
    }
    th {
        background-color: #007bff;
        color: white;
    }
    img {
        max-width: 70px;
        height: auto;
        border-radius: 6px;
    }
    .msg {
        margin-top: 20px;
        font-weight: bold;
    }
    a {
        display: inline-block;
        margin-top: 20px;
        text-decoration: none;
        color: #007bff;
    }
    a:hover {
        text-decoration: underline;
    }
</style>

<script>
function konfirmasiHapus(nama) {
    return confirm("⚠️ Apakah Anda yakin ingin menghapus barang: '" + nama + "' ?\n\nTekan OK untuk YA atau Cancel untuk TIDAK.");
}
</script>
</head>
<body>

<h2>🗑️ Hapus Barang Berdasarkan Kata</h2>

<!-- Form Pencarian -->
<form method="post">
    <label for="kata">Masukkan satu kata dari nama barang:</label><br>
    <input type="text" id="kata" name="kata" placeholder="Contoh: kopi" required>
    <br>
    <button type="submit" name="cari">Cari Barang</button>
</form>

<!-- Pesan -->
<div class="msg"><?= $message ?></div>

<!-- Tabel Hasil Pencarian -->
<?php if (count($hasil) > 0): ?>
    <h3>Hasil Pencarian (<?= count($hasil) ?> barang ditemukan):</h3>
    <table>
        <tr>
            <th>No</th>
            <th>Nama Barang</th>
            <th>Harga</th>
            <th>Stok</th>
            <th>Diskon</th>
            <th>Gambar</th>
            <th>Aksi</th>
        </tr>
        <?php $no = 1; foreach ($hasil as $row): ?>
        <tr>
            <td><?= $no++ ?></td>
            <td><?= htmlspecialchars($row['Nama_barang']) ?></td>
            <td>Rp <?= number_format($row['Harga'], 0, ',', '.') ?></td>
            <td><?= $row['Stok'] ?></td>
            <td><?= $row['Diskon'] ?>%</td>
            <td>
                <?php if (!empty($row['Gbr_brg'])): ?>
                    <img src="gambar/<?= htmlspecialchars($row['Gbr_brg']) ?>" alt="">
                <?php else: ?>
                    -
                <?php endif; ?>
            </td>
            <td>
                <form method="post" onsubmit="return konfirmasiHapus('<?= htmlspecialchars($row['Nama_barang']) ?>');" style="display:inline;">
                    <input type="hidden" name="hapus_id" value="<?= $row['no_id'] ?>">
                    <button type="submit">HAPUS</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
<?php endif; ?>

<a href="admin_dashboard.php">← Kembali ke Dashboard</a>

</body>
</html>
