<?php
session_start();

include 'db.php';

if ($_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 = "";

// 🔁 Aksi tombol
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action = $_POST['action'] ?? '';
    $nama_barang = trim($_POST['nama_barang'] ?? '');

    // ♻️ Pulihkan satu barang
    if ($action === "restore_one" && $nama_barang !== "") {
        $cek = $conn->prepare("SELECT Nama_barang, Harga, Stok, Diskon, Gbr_brg 
                               FROM barang_deleted WHERE Nama_barang = ?");
        $cek->bind_param("s", $nama_barang);
        $cek->execute();
        $cek->bind_result($nama_brg, $harga, $stok, $diskon, $gbr_brg);

        if ($cek->fetch()) {
            $cek->close();

            // 🚫 Cegah duplikasi
            $duplikat = $conn->prepare("SELECT COUNT(*) FROM barang WHERE Nama_barang = ?");
            $duplikat->bind_param("s", $nama_brg);
            $duplikat->execute();
            $duplikat->bind_result($jumlah);
            $duplikat->fetch();
            $duplikat->close();

            if ($jumlah > 0) {
                $message = "<p style='color:orange;'>Barang <b>$nama_brg</b> sudah ada di tabel utama.</p>";
            } else {
                // 🔙 Masukkan ke tabel utama
                $ins = $conn->prepare("INSERT INTO barang (Nama_barang, Harga, Stok, Diskon, Gbr_brg)
                                       VALUES (?, ?, ?, ?, ?)");
                $ins->bind_param("siiis", $nama_brg, $harga, $stok, $diskon, $gbr_brg);
                $ins->execute();
                $ins->close();

                // 🗑️ Hapus dari recycle bin
                $del = $conn->prepare("DELETE FROM barang_deleted WHERE Nama_barang = ? LIMIT 1");
                $del->bind_param("s", $nama_brg);
                $del->execute();
                $del->close();

                // 🧾 Catat log admin
                $ket = "Admin memulihkan barang: $nama_brg";
                $log = $conn->prepare("INSERT INTO admin_log (Aksi, Waktu, Keterangan)
                                       VALUES ('Pulihkan Barang', NOW(), ?)");
                $log->bind_param("s", $ket);
                $log->execute();
                $log->close();

                $message = "<p style='color:green;'>Barang <b>$nama_brg</b> berhasil dipulihkan.</p>";
            }
        } else {
            $message = "<p style='color:red;'>Barang <b>$nama_barang</b> tidak ditemukan di recycle bin.</p>";
            $cek->close();
        }
    }

    // ♻️ Pulihkan semua barang
    elseif ($action === "restore_all") {
        $cekJumlah = $conn->query("SELECT COUNT(*) AS jml FROM barang_deleted")->fetch_assoc()['jml'];
        if ($cekJumlah > 0) {
            $sql_restore = "INSERT INTO barang (Nama_barang, Harga, Stok, Diskon, Gbr_brg)
                            SELECT d.Nama_barang, d.Harga, d.Stok, d.Diskon, d.Gbr_brg
                            FROM barang_deleted d
                            WHERE d.Nama_barang NOT IN (SELECT Nama_barang FROM barang)";
            if ($conn->query($sql_restore)) {
                $conn->query("DELETE FROM barang_deleted");
                $conn->query("INSERT INTO admin_log (Aksi, Waktu, Keterangan)
                              VALUES ('Pulihkan Semua', NOW(), 'Admin memulihkan semua barang dari recycle bin')");
                $message = "<p style='color:green;'>Semua barang berhasil dipulihkan ke tabel utama.</p>";
            } else {
                $message = "<p style='color:red;'>Terjadi kesalahan saat memulihkan semua barang.</p>";
            }
        } else {
            $message = "<p style='color:gray;'>Tidak ada barang di recycle bin.</p>";
        }
    }
}

// 🔍 Ambil semua barang dari recycle bin
$result = $conn->query("SELECT Nama_barang, Harga, Stok, Diskon, Gbr_brg, Tanggal_dihapus 
                        FROM barang_deleted ORDER BY Tanggal_dihapus DESC");
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>♻️ Recycle Bin - Barang Terhapus</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
            background-color: #f5f5f5;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            background: #fff;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        th, td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
        }
        th {
            background: #007BFF;
            color: white;
        }
        tr:hover { background-color: #eef; }
        button {
            background: #007BFF;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover { background: #0056b3; }
        .restore-all {
            background: #28a745;
            padding: 8px 16px;
            margin-bottom: 10px;
            border-radius: 5px;
        }
        .restore-all:hover { background: #1e7e34; }
        img {
            max-width: 100px;
            border-radius: 8px;
        }
        .msg {
            margin: 20px 0;
            font-weight: bold;
        }
        .back {
            display: inline-block;
            padding: 8px 12px;
            background: #6c757d;
            color: white;
            border-radius: 5px;
            text-decoration: none;
        }
        .back:hover { background: #5a6268; }
    </style>
</head>
<body>

<h2>♻️ Recycle Bin - Barang Terhapus</h2>

<div class="msg"><?= $message ?></div>

<form method="post">
    <button class="restore-all" type="submit" name="action" value="restore_all"
        onclick="return confirm('Yakin ingin memulihkan semua barang?')">Pulihkan Semua Barang</button>
    <a class="back" href="hapus_brg.php">⬅️ Kembali ke Menu Hapus</a>
</form>

<br>

<table>
    <tr>
        <th>Nama Barang</th>
        <th>Harga</th>
        <th>Stok</th>
        <th>Diskon</th>
        <th>Gambar</th>
        <th>Tanggal Dihapus</th>
        <th>Aksi</th>
    </tr>
    <?php if ($result && $result->num_rows > 0): ?>
        <?php while ($row = $result->fetch_assoc()): ?>
            <tr>
                <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="Gambar">
                    <?php else: ?>
                        <i>-</i>
                    <?php endif; ?>
                </td>
                <td><?= $row['Tanggal_dihapus'] ?></td>
                <td>
                    <form method="post" style="display:inline;" 
                          onsubmit="return confirm('Pulihkan barang ini?')">
                        <input type="hidden" name="nama_barang" 
                               value="<?= htmlspecialchars($row['Nama_barang']) ?>">
                        <button type="submit" name="action" value="restore_one">Pulihkan</button>
                    </form>
                </td>
            </tr>
        <?php endwhile; ?>
    <?php else: ?>
        <tr><td colspan="7" style="text-align:center;">Tidak ada barang di Recycle Bin.</td></tr>
    <?php endif; ?>
</table>

</body>
</html>
