<?php
/**
 * Checkout — Order confirmation & payment creation
 */
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';
requireMember();

$userId = $_SESSION['user_id'];

// Handle POST → create transaction
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrf()) {
        setFlash('error', 'Token CSRF tidak valid.');
        header('Location: ' . url('/member/checkout.php'));
        exit;
    }

    // Get cart items
    $stmt = $pdo->prepare("
        SELECT kr.kelas_id, k.harga 
        FROM keranjang kr JOIN kelas k ON kr.kelas_id = k.id 
        WHERE kr.user_id = ?
    ");
    $stmt->execute([$userId]);
    $items = $stmt->fetchAll();

    if (empty($items)) {
        setFlash('error', 'Keranjang kosong.');
        header('Location: ' . url('/member/katalog.php'));
        exit;
    }

    $total = array_sum(array_column($items, 'harga'));

    try {
        $pdo->beginTransaction();

        // Insert transaksi
        $stmt = $pdo->prepare("INSERT INTO transaksi (user_id, total_harga, status) VALUES (?, ?, 'pending')");
        $stmt->execute([$userId, $total]);
        $transaksiId = $pdo->lastInsertId();

        // Insert detail_transaksi
        $stmt = $pdo->prepare("INSERT INTO detail_transaksi (transaksi_id, kelas_id, harga_satuan) VALUES (?, ?, ?)");
        foreach ($items as $item) {
            $stmt->execute([$transaksiId, $item['kelas_id'], $item['harga']]);
        }

        // Clear cart
        $stmt = $pdo->prepare("DELETE FROM keranjang WHERE user_id = ?");
        $stmt->execute([$userId]);

        $pdo->commit();

        setFlash('success', 'Order berhasil dibuat! Silakan upload bukti pembayaran.');
        header("Location: " . url("/member/upload_bukti.php?transaksi_id={$transaksiId}"));
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('error', 'Terjadi kesalahan saat memproses order.');
        header('Location: ' . url('/member/checkout.php'));
        exit;
    }
}

// GET → show checkout summary
$stmt = $pdo->prepare("
    SELECT kr.kelas_id, k.nama_kelas, k.jenis_olahraga, k.instruktur, 
           k.hari, k.jam_mulai, k.jam_selesai, k.harga
    FROM keranjang kr JOIN kelas k ON kr.kelas_id = k.id 
    WHERE kr.user_id = ?
    ORDER BY kr.created_at
");
$stmt->execute([$userId]);
$items = $stmt->fetchAll();

if (empty($items)) {
    setFlash('error', 'Keranjang kosong. Pilih kelas terlebih dahulu.');
    header('Location: ' . url('/member/katalog.php'));
    exit;
}

$total = array_sum(array_column($items, 'harga'));

require_once __DIR__ . '/../includes/header.php';
?>

<div class="max-w-3xl mx-auto px-4 py-8">
    <div class="mb-8" style="opacity:0;animation:fadeUp 0.5s ease forwards;">
        <h1 class="text-3xl font-black mb-2">Checkout</h1>
        <p class="text-muted text-sm">Periksa pesanan Anda sebelum melanjutkan pembayaran</p>
    </div>

    <!-- Order Summary -->
    <div class="card mb-6" style="opacity:0;animation:fadeUp 0.5s ease 0.1s forwards;">
        <h2 class="text-lg font-bold mb-4 text-volt">Ringkasan Pesanan</h2>
        <div class="space-y-4">
            <?php foreach ($items as $item): ?>
            <div class="flex items-center justify-between py-3 border-b border-border last:border-0">
                <div>
                    <p class="font-bold text-white"><?= htmlspecialchars($item['nama_kelas']) ?></p>
                    <p class="text-xs text-muted"><?= htmlspecialchars($item['instruktur']) ?> · <?= htmlspecialchars($item['hari']) ?> <?= date('H:i', strtotime($item['jam_mulai'])) ?>-<?= date('H:i', strtotime($item['jam_selesai'])) ?></p>
                </div>
                <span class="font-bold text-white">Rp <?= number_format($item['harga'], 0, ',', '.') ?></span>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="mt-6 pt-4 border-t border-border flex items-center justify-between">
            <span class="text-lg font-bold text-muted">Total</span>
            <span class="text-2xl font-black text-volt">Rp <?= number_format($total, 0, ',', '.') ?></span>
        </div>
    </div>

    <!-- Confirm -->
    <form method="POST" action="" style="opacity:0;animation:fadeUp 0.5s ease 0.2s forwards;">
        <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
        <button type="submit" class="btn-volt w-full text-center text-base py-4 pulse" id="btn-confirm">
            Konfirmasi & Bayar →
        </button>
        <a href="<?= BASE_URL ?>/member/keranjang.php" class="block text-center text-sm text-muted mt-4 hover:text-white transition-colors">
            ← Kembali ke Keranjang
        </a>
    </form>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
