<?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("<p style='color:red;'>Koneksi gagal: " . htmlspecialchars($conn->connect_error) . "</p>");
}

$message = "";

// 🧾 Proses aksi form
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action = $_POST['action'] ?? '';
    $email  = trim($_POST['email'] ?? '');

    if ($action === "restore_one" && !empty($email)) {
        $cek = $conn->prepare("SELECT Nama, Alamat, Email, No_hape, Gbr_plg FROM pelanggan_deleted WHERE Email = ?");
        $cek->bind_param("s", $email);
        $cek->execute();
        $data = $cek->get_result()->fetch_assoc();
        $cek->close();

        if ($data) {
            $ins = $conn->prepare("INSERT INTO pelanggan (Nama, Alamat, Email, No_hape, Gbr_plg) VALUES (?, ?, ?, ?, ?)");
            $ins->bind_param("sssss", $data['Nama'], $data['Alamat'], $data['Email'], $data['No_hape'], $data['Gbr_plg']);
            if ($ins->execute()) {
                $del = $conn->prepare("DELETE FROM pelanggan_deleted WHERE Email = ?");
                $del->bind_param("s", $email);
                $del->execute();
                $message = "<p style='color:green;'>✅ Pelanggan <b>" . htmlspecialchars($data['Nama']) . "</b> berhasil dipulihkan (foto ikut dikembalikan).</p>";
            } else {
                $message = "<p style='color:red;'>❌ Gagal memulihkan data: " . htmlspecialchars($ins->error) . "</p>";
            }
        } else {
            $message = "<p style='color:red;'>⚠️ Data tidak ditemukan di Recycle Bin.</p>";
        }

    } elseif ($action === "restore_all") {
        $conn->query("
            INSERT INTO pelanggan (Nama, Alamat, Email, No_hape, Gbr_plg)
            SELECT Nama, Alamat, Email, No_hape, Gbr_plg FROM pelanggan_deleted
        ");
        $conn->query("DELETE FROM pelanggan_deleted");
        $message = "<p style='color:green;'>✅ Semua pelanggan berhasil dipulihkan (termasuk foto).</p>";

    } elseif ($action === "delete_permanent" && !empty($email)) {
        $del = $conn->prepare("DELETE FROM pelanggan_deleted WHERE Email = ?");
        $del->bind_param("s", $email);
        if ($del->execute()) {
            $message = "<p style='color:orange;'>🗑️ Pelanggan dengan email <b>" . htmlspecialchars($email) . "</b> dihapus permanen.</p>";
        } else {
            $message = "<p style='color:red;'>❌ Gagal menghapus data: " . htmlspecialchars($del->error) . "</p>";
        }
    }
}

// 🔍 Ambil daftar pelanggan di recycle bin
$result = $conn->query("SELECT Nama, Alamat, Email, No_hape, Gbr_plg, Tanggal_dihapus FROM pelanggan_deleted ORDER BY Tanggal_dihapus DESC");
$pelanggan = $result->fetch_all(MYSQLI_ASSOC);
$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Recycle Bin Pelanggan</title>
<style>
    body { font-family: Arial, sans-serif; margin: 40px; background: #f4f4f4; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; background: #fff; }
    th, td { padding: 10px; border: 1px solid #ddd; text-align: left; }
    th { background: #0074D9; color: white; }
    tr:nth-child(even) { background: #f9f9f9; }
    button { padding: 4px 10px; margin: 2px; border: none; border-radius: 4px; cursor: pointer; }
    .restore { background: #2ECC40; color: white; }
    .delete { background: #FF4136; color: white; }
    .restore_all { background: #0074D9; color: white; padding: 8px 20px; margin-top: 10px; }
    img.thumb { width: 60px; height: 60px; object-fit: cover; border-radius: 8px; }
    .msg { margin-top: 15px; }
</style>
</head>

<body>
    <h2>♻️ Recycle Bin Pelanggan</h2>
    <?= $message ?>

    <?php if (count($pelanggan) > 0): ?>
    <form method="post">
        <button type="submit" name="action" value="restore_all" class="restore_all">Pulihkan Semua</button>
    </form>

    <table>
        <tr>
            <th>Foto</th>
            <th>Nama</th>
            <th>Alamat</th>
            <th>Email</th>
            <th>No. HP</th>
            <th>Tanggal Dihapus</th>
            <th>Aksi</th>
        </tr>

        <?php foreach ($pelanggan as $p): 
            $foto_path = "gambar/" . htmlspecialchars($p['Gbr_plg']);
            $foto_exists = file_exists($foto_path) && !empty($p['Gbr_plg']);
        ?>
        <tr>
            <td>
                <?php if ($foto_exists): ?>
                    <img src="<?= $foto_path ?>" alt="Foto" class="thumb">
                <?php else: ?>
                    <span style="color:gray;">(tidak ada)</span>
                <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($p['Nama']) ?></td>
            <td><?= htmlspecialchars($p['Alamat']) ?></td>
            <td><?= htmlspecialchars($p['Email']) ?></td>
            <td><?= htmlspecialchars($p['No_hape']) ?></td>
            <td><?= htmlspecialchars($p['Tanggal_dihapus']) ?></td>
            <td>
                <form method="post" style="display:inline;">
                    <input type="hidden" name="email" value="<?= htmlspecialchars($p['Email']) ?>">
                    <button type="submit" name="action" value="restore_one" class="restore">Pulihkan</button>
                </form>
                <form method="post" style="display:inline;">
                    <input type="hidden" name="email" value="<?= htmlspecialchars($p['Email']) ?>">
                    <button type="submit" name="action" value="delete_permanent" class="delete" onclick="return confirm('Hapus permanen pelanggan ini?')">Hapus Permanen</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>

    <?php else: ?>
        <p>Tidak ada data pelanggan di recycle bin.</p>
    <?php endif; ?>
</body>
</html>
