<?php
/**
 * Demo data seeder — inserts sample wallet transactions and orders for the
 * logged-in customer so the redesigned Transactions / Order History / receipt
 * screens can be viewed with content. Visit this page, tap "Add demo data".
 * Safe to remove later with "Remove demo data". Everything is tagged
 * (transactions: reference LIKE 'DEMO-%', orders: note = 'DEMO') so it never
 * touches real data.
 */
session_start();
$page_title = 'Demo Data';
$active_nav = 'profile';
include("includes/header.php");
$uid = (int)$_SESSION['user_id'];

$msg = $err = "";

// Already seeded?
function demo_count($conn, $uid) {
    $n = 0;
    if ($s = $conn->prepare("SELECT COUNT(*) c FROM wallet_transactions WHERE user_id=? AND reference LIKE 'DEMO-%'")) {
        $s->bind_param("i", $uid); $s->execute(); $n += (int)$s->get_result()->fetch_assoc()['c'];
    }
    return $n;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'clear') {
        // remove demo orders' items, demo orders, demo transactions
        if ($q = $conn->prepare("SELECT id FROM orders WHERE user_id=? AND note='DEMO'")) {
            $q->bind_param("i", $uid); $q->execute();
            $ids = array_column($q->get_result()->fetch_all(MYSQLI_ASSOC), 'id');
            foreach ($ids as $oid) {
                $conn->query("DELETE FROM order_items WHERE order_id=" . (int)$oid);
            }
        }
        $conn->query("DELETE FROM orders WHERE user_id=" . $uid . " AND note='DEMO'");
        $conn->query("DELETE FROM wallet_transactions WHERE user_id=" . $uid . " AND reference LIKE 'DEMO-%'");
        $msg = "Demo data removed.";
    }

    if ($action === 'seed') {
        if (demo_count($conn, $uid) > 0) {
            $err = "Demo data already exists. Remove it first to re-seed.";
        } else {
            // restaurants to attach orders to (any available)
            $rests = $conn->query("SELECT id, name FROM restaurants ORDER BY id ASC LIMIT 3")->fetch_all(MYSQLI_ASSOC);

            // ---- wallet transactions ----
            $txns = [
                ['credit', 12000.00, 'Bank Transfer',  2],
                ['credit', 18000.00, 'USSD Funding',   5],
                ['debit',    999.00, 'Fish pie',       1],
                ['debit',   1000.00, 'Cardbury Tea',   3],
                ['debit',  11000.00, 'Shawarma',       9],
            ];
            $tstmt = $conn->prepare(
                "INSERT INTO wallet_transactions (user_id, wallet_type, amount, type, reference, description, status, created_at)
                 VALUES (?, 'customer', ?, ?, ?, ?, 'success', (NOW() - INTERVAL ? DAY))"
            );
            $i = 0;
            foreach ($txns as $tx) {
                [$type, $amt, $desc, $daysAgo] = $tx;
                $ref = 'DEMO-' . strtoupper(bin2hex(random_bytes(4))) . $i;
                $tstmt->bind_param("idsssi", $uid, $amt, $type, $ref, $desc, $daysAgo);
                $tstmt->execute();
                $i++;
            }

            // ---- orders + items (spread across months via day offsets) ----
            $orders = [
                ['status' => 'completed', 'days' => 6,  'service' => 200.00,
                 'items' => [['Cheeseburger', 1, 2500.00], ['Truffle Fries', 1, 1500.00], ['Vanilla Shake', 1, 1200.00]]],
                ['status' => 'completed', 'days' => 25, 'service' => 150.00,
                 'items' => [['Pepperoni Pizza', 1, 5000.00], ['Garlic Bread', 1, 1200.00]]],
                ['status' => 'ready',     'days' => 48, 'service' => 250.00,
                 'items' => [['Salmon Nigiri', 2, 2000.00], ['Miso Soup', 1, 1500.00]]],
            ];

            $ostmt = $conn->prepare(
                "INSERT INTO orders (user_id, restaurant_id, table_number, note, total_amount, payment_method, payment_status, order_status, created_at)
                 VALUES (?, ?, ?, 'DEMO', ?, 'wallet', 'paid', ?, (NOW() - INTERVAL ? DAY))"
            );
            $istmt = $conn->prepare(
                "INSERT INTO order_items (order_id, item_name, quantity, price, created_at)
                 VALUES (?, ?, ?, ?, (NOW() - INTERVAL ? DAY))"
            );

            $oi = 0;
            foreach ($orders as $o) {
                $subtotal = 0;
                foreach ($o['items'] as $it) { $subtotal += $it[1] * $it[2]; }
                $total = $subtotal + $o['service'];
                $rid     = $rests ? (int)$rests[$oi % count($rests)]['id'] : null;
                $table   = 'T' . (5 + $oi);
                $days    = $o['days'];
                $ostatus = $o['status'];
                $ostmt->bind_param("iisdsi", $uid, $rid, $table, $total, $ostatus, $days);
                $ostmt->execute();
                $order_id = $conn->insert_id;
                foreach ($o['items'] as $it) {
                    $name = $it[0]; $qty = $it[1]; $price = $it[2];
                    $istmt->bind_param("isidi", $order_id, $name, $qty, $price, $days);
                    $istmt->execute();
                }
                $oi++;
            }

            $msg = "Demo data added — 5 transactions and 3 orders. Open Wallet or Orders to view.";
        }
    }
}

$has_demo = demo_count($conn, $uid) > 0;
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.sd-wrap { max-width: 600px; margin: 0 auto; }
.sub-topbar { display: flex; align-items: center; gap: 12px; padding: 4px 2px 18px; }
.sub-topbar .sub-back { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); flex-shrink: 0; }
.sub-topbar .sub-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }
.sd-card { background: #fff; border: 1px solid var(--border); border-radius: 18px; box-shadow: 0 4px 18px rgba(15,23,42,.06); padding: 20px; margin-bottom: 14px; }
.sd-card p { font-size: .88rem; color: var(--text-muted); line-height: 1.55; }
.sd-btn { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; height: 52px; border-radius: 14px; font-weight: 700; font-size: .95rem; border: none; cursor: pointer; font-family: var(--font); margin-top: 14px; }
.sd-btn.primary { background: var(--primary); color: #fff; box-shadow: 0 8px 22px rgba(34,90,227,.3); }
.sd-btn.danger { background: var(--error-bg); color: var(--error); border: 1.5px solid #FECACA; }
.sd-links { display: flex; gap: 12px; margin-top: 14px; }
.sd-links a { flex: 1; text-align: center; padding: 13px; border-radius: 12px; border: 1.5px solid var(--border); background: #fff; color: var(--primary); font-weight: 700; font-size: .9rem; text-decoration: none; }
</style>

<div class="sd-wrap">

  <div class="sub-topbar">
    <a href="profile.php" class="sub-back" aria-label="Back" onclick="return goBack(event)">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
    </a>
    <span class="sub-title">Demo Data</span>
  </div>

  <?php if ($msg): ?>
  <div class="alert alert-success" style="margin-bottom:16px">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
    <?php echo htmlspecialchars($msg); ?>
  </div>
  <?php endif; ?>
  <?php if ($err): ?><div class="alert alert-error" style="margin-bottom:16px"><?php echo htmlspecialchars($err); ?></div><?php endif; ?>

  <div class="sd-card">
    <p>This adds sample wallet transactions and orders to <strong>your</strong> account so you can preview the new Transactions, Order History and Receipt screens. It's clearly tagged and easy to remove — it won't affect any real data.</p>

    <?php if (!$has_demo): ?>
    <form method="POST"><input type="hidden" name="action" value="seed">
      <button class="sd-btn primary" type="submit">Add demo data</button>
    </form>
    <?php else: ?>
    <div class="sd-links">
      <a href="wallet.php">View Wallet</a>
      <a href="orders.php">View Orders</a>
    </div>
    <form method="POST"><input type="hidden" name="action" value="clear">
      <button class="sd-btn danger" type="submit">Remove demo data</button>
    </form>
    <?php endif; ?>
  </div>

</div>

<?php include("includes/footer.php"); ?>
