<?php
require_once __DIR__ . '/includes/db.php';

// Menghapus item dari keranjang
if (isset($_GET['action']) && $_GET['action'] === 'remove' && isset($_GET['id'])) {
    $id_to_remove = intval($_GET['id']);
    if (isset($_SESSION['cart'][$id_to_remove])) {
        unset($_SESSION['cart'][$id_to_remove]);
    }
    header("Location: cart.php");
    exit();
}

$cart_items = [];
$total_price = 0;

// Jika keranjang ada isinya, ambil datanya dari database
if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
    $product_ids = array_keys($_SESSION['cart']);
    // Buat placeholder ?,?,? sesuai jumlah produk
    $placeholders = implode(',', array_fill(0, count($product_ids), '?'));
    
    $stmt = $db->prepare("SELECT * FROM products WHERE id IN ($placeholders) AND is_active = 1");
    $stmt->execute($product_ids);
    $products = $stmt->fetchAll();
    
    foreach ($products as $p) {
        $qty = $_SESSION['cart'][$p['id']];
        $subtotal = $p['price'] * $qty;
        $total_price += $subtotal;
        
        $cart_items[] = [
            'id' => $p['id'],
            'name' => $p['name'],
            'price' => $p['price'],
            'image_url' => $p['image_url'],
            'qty' => $qty,
            'subtotal' => $subtotal,
            'available_stock' => $p['stock']
        ];
    }
}

$error_msg = '';

// Proses Checkout Form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'checkout') {
    $customer_name = trim($_POST['customer_name']);
    $customer_phone = trim($_POST['customer_phone']);
    $customer_address = trim($_POST['customer_address']);
    $payment_method = isset($_POST['payment_method']) ? trim($_POST['payment_method']) : 'Transfer Bank (BCA)';
    if ($payment_method !== 'QRIS') {
        $payment_method = 'Transfer Bank (BCA)';
    }
    
    if (empty($customer_name) || empty($customer_phone) || empty($customer_address)) {
        $error_msg = "Semua bidang formulir pemesanan wajib diisi.";
    } elseif (empty($cart_items)) {
        $error_msg = "Keranjang belanja Anda kosong.";
    } else {
        // Mulai database transaction untuk konsistensi data
        $db->beginTransaction();
        try {
            // 1. Verifikasi stok kembali sebelum melakukan checkout
            foreach ($cart_items as $item) {
                // Ambil stok terbaru langsung dari database
                $stmt = $db->prepare("SELECT stock, name FROM products WHERE id = ?");
                $stmt->execute([$item['id']]);
                $latest_prod = $stmt->fetch();
                
                if ($latest_prod['stock'] < $item['qty']) {
                    throw new Exception("Stok untuk '" . $latest_prod['name'] . "' tidak mencukupi. Sisa stok saat ini: " . $latest_prod['stock'] . " pcs.");
                }
            }
            
            // 2. Insert data pesanan utama ke tabel orders
            $insert_order = $db->prepare("INSERT INTO orders (customer_name, customer_phone, customer_address, total_price, status, payment_method) VALUES (?, ?, ?, ?, 'pending', ?)");
            $insert_order->execute([$customer_name, $customer_phone, $customer_address, $total_price, $payment_method]);
            $order_id = $db->lastInsertId();
            
            // 3. Insert detail barang pesanan ke tabel order_items & update stok
            $insert_item = $db->prepare("INSERT INTO order_items (order_id, product_id, quantity, price_at_purchase) VALUES (?, ?, ?, ?)");
            $update_stock = $db->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
            $insert_stock_log = $db->prepare("INSERT INTO stock_logs (product_id, quantity_change, type, notes) VALUES (?, ?, 'out', ?)");
            
            foreach ($cart_items as $item) {
                // Catat item pesanan
                $insert_item->execute([$order_id, $item['id'], $item['qty'], $item['price']]);
                
                // Kurangi stok produk
                $update_stock->execute([$item['qty'], $item['id']]);
                
                // Catat mutasi stok keluar
                $note = "Pengurangan stok otomatis untuk transaksi pemesanan #" . str_pad($order_id, 5, '0', STR_PAD_LEFT);
                $insert_stock_log->execute([$item['id'], -$item['qty'], $note]);
            }
            
            // Commit transaction
            $db->commit();
            
            // Kosongkan keranjang belanja
            $_SESSION['cart'] = [];
            
            // Arahkan ke halaman sukses
            header("Location: order_success.php?id=" . $order_id);
            exit();
            
        } catch (Exception $e) {
            // Rollback jika terjadi kegagalan
            $db->rollBack();
            $error_msg = "Gagal memproses pesanan: " . $e->getMessage();
        }
    }
}

$page_title = "Keranjang Belanja - Toko Kue Edelys";
require_once __DIR__ . '/includes/header.php';
?>

<main style="margin-top: 2rem;">
    <h2 class="section-title" style="margin-bottom: 2rem;">Keranjang Belanja</h2>

    <?php if (!empty($error_msg)): ?>
        <div style="background-color: rgba(178, 83, 62, 0.1); color: var(--danger-color); padding: 1rem; border-radius: var(--radius-sm); border: 1px solid var(--danger-color); margin-bottom: 1.5rem;">
            <i class="fa-solid fa-triangle-exclamation"></i> <?php echo htmlspecialchars($error_msg); ?>
        </div>
    <?php endif; ?>

    <?php if (empty($cart_items)): ?>
        <div class="cart-items-container" style="text-align: center; padding: 4rem 2rem;">
            <i class="fa-solid fa-basket-shopping" style="font-size: 4rem; color: var(--accent-color); margin-bottom: 1.5rem;"></i>
            <h3>Keranjang Anda Kosong</h3>
            <p style="color: var(--text-secondary); margin-top: 0.5rem; margin-bottom: 1.5rem;">Silakan jelajahi katalog kue lezat kami dan masukkan pesanan Anda.</p>
            <a href="index.php" class="btn"><i class="fa-solid fa-shop"></i> Belanja Sekarang</a>
        </div>
    <?php else: ?>
        <div class="cart-layout">
            <!-- Daftar Belanja -->
            <div class="cart-items-container">
                <h3 class="cart-title">Detail Kue Yang Dipesan</h3>
                
                <?php foreach ($cart_items as $item): ?>
                    <div class="cart-item">
                        <div class="cart-item-image">
                            <img src="<?php echo htmlspecialchars($item['image_url']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>">
                        </div>
                        <div class="cart-item-details">
                            <h4 class="cart-item-name"><?php echo htmlspecialchars($item['name']); ?></h4>
                            <div class="cart-item-price">
                                Rp <?php echo number_format($item['price'], 0, ',', '.'); ?> x <?php echo $item['qty']; ?> pcs
                            </div>
                        </div>
                        <div class="cart-item-actions">
                            <div style="font-weight: 700; color: var(--text-primary);">
                                Rp <?php echo number_format($item['subtotal'], 0, ',', '.'); ?>
                            </div>
                            <a href="cart.php?action=remove&id=<?php echo $item['id']; ?>" class="cart-item-remove" onclick="return confirm('Apakah Anda yakin ingin menghapus kue ini dari keranjang?')">
                                <i class="fa-regular fa-trash-can"></i> Hapus
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Form Pemesanan & Checkout -->
            <div class="checkout-form-container">
                <h3 class="cart-title">Informasi Pengiriman</h3>
                
                <form action="cart.php" method="POST">
                    <input type="hidden" name="action" value="checkout">
                    
                    <div class="form-group">
                        <label for="customer_name">Nama Lengkap Penerima</label>
                        <input type="text" name="customer_name" id="customer_name" class="form-control" placeholder="Contoh: Budi Santoso" required value="<?php echo isset($_POST['customer_name']) ? htmlspecialchars($_POST['customer_name']) : ''; ?>">
                    </div>

                    <div class="form-group">
                        <label for="customer_phone">Nomor HP / WhatsApp</label>
                        <input type="tel" name="customer_phone" id="customer_phone" class="form-control" placeholder="Contoh: 0812XXXXXXXX" required value="<?php echo isset($_POST['customer_phone']) ? htmlspecialchars($_POST['customer_phone']) : ''; ?>">
                    </div>

                    <div class="form-group">
                        <label for="customer_address">Alamat Lengkap Pengiriman</label>
                        <textarea name="customer_address" id="customer_address" class="form-control" placeholder="Tuliskan nama jalan, nomor rumah, RT/RW, kelurahan, kecamatan, dan kota..." required><?php echo isset($_POST['customer_address']) ? htmlspecialchars($_POST['customer_address']) : ''; ?></textarea>
                    </div>

                    <div class="form-group" style="margin-top: 1.5rem;">
                        <label style="display: block; margin-bottom: 0.6rem; font-weight: 600;">Metode Pembayaran</label>
                        <div class="payment-methods">
                            <label class="payment-option">
                                <input type="radio" name="payment_method" value="Transfer Bank (BCA)" checked>
                                <span class="payment-box">
                                    <i class="fa-solid fa-building-columns"></i>
                                    <strong>Transfer Bank BCA</strong>
                                    <small>7895254879 a.n. Edelys</small>
                                </span>
                            </label>
                            
                            <label class="payment-option">
                                <input type="radio" name="payment_method" value="QRIS">
                                <span class="payment-box">
                                    <i class="fa-solid fa-qrcode"></i>
                                    <strong>QRIS (Kode QR)</strong>
                                    <small>Bayar Instan & Aman</small>
                                </span>
                            </label>
                        </div>
                    </div>

                    <!-- Rincian Biaya -->
                    <div style="margin-top: 2rem; border-top: 1px solid var(--border-color); padding-top: 1.5rem;">
                        <div class="summary-row">
                            <span>Subtotal Kue:</span>
                            <span>Rp <?php echo number_format($total_price, 0, ',', '.'); ?></span>
                        </div>
                        <div class="summary-row">
                            <span>Biaya Pengiriman:</span>
                            <span style="color: var(--success-color); font-weight: 500;">Gratis Ongkir</span>
                        </div>
                        <div class="summary-row summary-total">
                            <span>Total Pembayaran:</span>
                            <span>Rp <?php echo number_format($total_price, 0, ',', '.'); ?></span>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-full" style="margin-top: 1.5rem;">
                        <i class="fa-solid fa-file-invoice-dollar"></i> Proses & Selesaikan Pemesanan
                    </button>
                </form>
            </div>
        </div>
    <?php endif; ?>
</main>

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