<?php
require_once __DIR__ . '/../includes/auth.php';
require_customer();
require_once __DIR__ . '/../includes/header_customer.php';
require_once __DIR__ . '/../includes/cart.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$cartId = get_or_create_cart($pdo, (int) current_user()['id']);
$items = get_cart_items($pdo, $cartId);

if (!$items) {
    flash_message('error', 'Keranjang kosong.');
    redirect(base_url('public/index.php?page=products'));
}

// Fetch shipping rates
$shippingRates = $pdo->query('SELECT * FROM shipping_rates ORDER BY is_default DESC, location_name ASC')->fetchAll();
$methods = $pdo->query('SELECT id, name, account_name, account_number, instructions FROM payment_methods WHERE is_active = 1 ORDER BY name')->fetchAll();

$errors = [];
$shippingAddress = trim($_POST['shipping_address'] ?? (current_user()['address'] ?? ''));
$shippingRateId = (int) ($_POST['shipping_rate_id'] ?? 0);
$paymentMethodId = (int) ($_POST['payment_method_id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($shippingAddress === '') {
        $errors['shipping_address'] = 'Alamat pengiriman wajib diisi.';
    }

    $selectedRate = null;
    foreach ($shippingRates as $rate) {
        if ((int)$rate['id'] === $shippingRateId) {
            $selectedRate = $rate;
            break;
        }
    }

    if (!$selectedRate) {
        $errors['shipping_rate_id'] = 'Pilih lokasi pengiriman.';
    }

    $methodIds = array_map(fn($m) => (int) $m['id'], $methods);
    if (!in_array($paymentMethodId, $methodIds, true)) {
        $errors['payment_method_id'] = 'Pilih metode pembayaran.';
    }

    if (!$errors) {
        $subtotal = 0;
        foreach ($items as $item) {
            $subtotal += $item['price'] * $item['qty'];
        }
        $shippingCost = (float) $selectedRate['cost'];
        $total = $subtotal + $shippingCost;

        $code = 'ORD' . date('YmdHis') . rand(100, 999);

        $pdo->beginTransaction();
        try {
            // Append Shipping Location Name to Address for clarity
            $fullAddress = $shippingAddress . "\n(Lokasi: " . $selectedRate['location_name'] . ")";

            $orderStmt = $pdo->prepare('INSERT INTO orders (code, user_id, shipping_address, shipping_cost, subtotal, total, status, payment_method_id) VALUES (?, ?, ?, ?, ?, ?, "pending", ?)');
            $orderStmt->execute([
                $code,
                current_user()['id'],
                $fullAddress,
                $shippingCost,
                $subtotal,
                $total,
                $paymentMethodId,
            ]);
            $orderId = (int) $pdo->lastInsertId();

            $itemStmt = $pdo->prepare('INSERT INTO order_items (order_id, product_id, qty, price, subtotal) VALUES (?, ?, ?, ?, ?)');
            $stockStmt = $pdo->prepare('UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?');

            foreach ($items as $item) {
                $itemSubtotal = $item['price'] * $item['qty'];
                $itemStmt->execute([$orderId, $item['product_id'], $item['qty'], $item['price'], $itemSubtotal]);

                $stockStmt->execute([$item['qty'], $item['product_id'], $item['qty']]);
                if ($stockStmt->rowCount() === 0) {
                    throw new RuntimeException('Stok tidak mencukupi untuk ' . $item['name']);
                }
            }

            clear_cart($pdo, $cartId);
            $pdo->commit();

            flash_message('success', 'Order berhasil dibuat.');
            redirect(base_url('public/index.php?page=payment_info&order_id=' . $orderId));
        } catch (Throwable $e) {
            $pdo->rollBack();
            flash_message('error', 'Gagal membuat order: ' . $e->getMessage());
            redirect(base_url('public/index.php?page=checkout'));
        }
    }
}
?>

<h2 class="fw-bold mb-3">Checkout</h2>

<div class="row g-4">
    <div class="col-lg-7">
        <div class="card shadow-sm">
            <div class="card-body">
                <h5 class="fw-bold">Alamat Pengiriman</h5>
                <form method="post" id="checkoutForm">
                    <label>Alamat Lengkap</label>
                    <textarea class="form-control" name="shipping_address" rows="3" required placeholder="Jalan, No Rumah, RT/RW..."><?= sanitize($shippingAddress); ?></textarea>
                    <?php if (!empty($errors['shipping_address'])): ?><small class="error"><?= sanitize($errors['shipping_address']); ?></small><?php endif; ?>

                    <label class="mt-3">Area Pengiriman (Menentukan Ongkir)</label>
                    <select class="form-select" name="shipping_rate_id" id="shippingRate" onchange="updateTotal()" required>
                        <option value="" data-cost="0">-- Pilih Area --</option>
                        <?php foreach ($shippingRates as $rate): ?>
                            <option value="<?= (int) $rate['id']; ?>" data-cost="<?= (float) $rate['cost']; ?>" <?= $shippingRateId === (int) $rate['id'] ? 'selected' : ''; ?>>
                                <?= sanitize($rate['location_name']); ?> - <?= format_currency($rate['cost']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!empty($errors['shipping_rate_id'])): ?><small class="error"><?= sanitize($errors['shipping_rate_id']); ?></small><?php endif; ?>

                    <label class="mt-3">Metode Pembayaran</label>
                    <select class="form-select" name="payment_method_id" required>
                        <option value="">-- Pilih Metode --</option>
                        <?php foreach ($methods as $method): ?>
                            <option value="<?= (int) $method['id']; ?>" <?= $paymentMethodId === (int) $method['id'] ? 'selected' : ''; ?>>
                                <?= sanitize($method['name']); ?> - <?= sanitize($method['account_number']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!empty($errors['payment_method_id'])): ?><small class="error"><?= sanitize($errors['payment_method_id']); ?></small><?php endif; ?>

                    <button class="btn btn-primary mt-4 w-100 py-2" type="submit" style="background: var(--primary-end);">Buat Pesanan</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="card shadow-sm sticky-top" style="top: 20px;">
            <div class="card-body">
                <h5 class="fw-bold">Ringkasan Order</h5>
                <?php $subtotal = 0; ?>
                <?php foreach ($items as $item): ?>
                    <?php $line = $item['price'] * $item['qty']; $subtotal += $line; ?>
                    <div class="d-flex justify-content-between mb-2">
                        <span><?= sanitize($item['name']); ?> <small class="text-muted">x<?= (int) $item['qty']; ?></small></span>
                        <span><?= format_currency($line); ?></span>
                    </div>
                <?php endforeach; ?>
                <hr>
                <div class="d-flex justify-content-between mb-2">
                    <span class="text-muted">Subtotal</span>
                    <span class="fw-bold" id="subtotalDisplay" data-value="<?= $subtotal; ?>"><?= format_currency($subtotal); ?></span>
                </div>
                 <div class="d-flex justify-content-between mb-2">
                    <span class="text-muted">Ongkir</span>
                    <span class="fw-bold" id="shippingDisplay">Rp 0</span>
                </div>
                <div class="d-flex justify-content-between mt-3 pt-3 border-top">
                    <span class="fs-5 fw-bold">Total Bayar</span>
                    <span class="fs-5 fw-bold text-primary" id="totalDisplay"><?= format_currency($subtotal); ?></span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function formatRupiah(angka) {
    return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(angka);
}

function updateTotal() {
    const select = document.getElementById('shippingRate');
    const selectedOption = select.options[select.selectedIndex];
    const shippingCost = parseFloat(selectedOption.getAttribute('data-cost')) || 0;
    
    const subtotal = parseFloat(document.getElementById('subtotalDisplay').getAttribute('data-value'));
    const total = subtotal + shippingCost;

    document.getElementById('shippingDisplay').innerText = formatRupiah(shippingCost);
    document.getElementById('totalDisplay').innerText = formatRupiah(total);
}

// Run on load in case of re-submission
updateTotal();
</script>

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

