<?php
$page_title = 'Your Cart';
require __DIR__ . '/_guard.php';

function cents_to_rand(int $cents): string {
    return 'R ' . number_format($cents / 100, 2, '.', ' ');
}

// Find or create the member's "cart" order (at most one cart per member).
function get_or_create_cart(int $member_id): array {
    $cart = db_row(
        'SELECT * FROM orders WHERE member_id = :m AND status = "cart" LIMIT 1',
        ['m' => $member_id]
    );
    if ($cart) return $cart;

    $id = db_insert('orders', [
        'member_id' => $member_id,
        'status'    => 'cart',
    ]);
    return db_row('SELECT * FROM orders WHERE id = :id', ['id' => $id]);
}

// Recompute totals after any cart change.
function recompute_cart(int $order_id): void {
    $subtotal = (int)db_value(
        'SELECT COALESCE(SUM(line_total_cents), 0) FROM order_items WHERE order_id = :o',
        ['o' => $order_id]
    );
    db_exec(
        'UPDATE orders SET subtotal_cents = :s, total_cents = :s WHERE id = :id',
        ['s' => $subtotal, 'id' => $order_id]
    );
}

$cart = get_or_create_cart((int)$member['id']);

// Handle POST: update qty or remove
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? '';

    if ($action === 'update') {
        foreach (($_POST['qty'] ?? []) as $item_id => $qty) {
            $qty = max(0, (int)$qty);
            $row = db_row(
                'SELECT oi.*, bi.price_cents FROM order_items oi
                    JOIN branding_items bi ON bi.id = oi.branding_item_id
                    WHERE oi.id = :id AND oi.order_id = :o',
                ['id' => (int)$item_id, 'o' => $cart['id']]
            );
            if (!$row) continue;

            if ($qty === 0) {
                db_exec('DELETE FROM order_items WHERE id = :id', ['id' => $item_id]);
            } else {
                $line = (int)$row['price_cents'] * $qty;
                db_exec(
                    'UPDATE order_items SET quantity = :q, line_total_cents = :lt WHERE id = :id',
                    ['q' => $qty, 'lt' => $line, 'id' => $item_id]
                );
            }
        }
        recompute_cart((int)$cart['id']);
        header('Location: cart.php?updated=1'); exit;
    }

    if ($action === 'checkout') {
        // Phase 2b: real PayFast flow. For Phase 2a: just mark pending_payment
        // and generate an invoice + pending transaction.
        $subtotal = (int)$cart['subtotal_cents'];
        if ($subtotal <= 0) {
            header('Location: cart.php?error=empty'); exit;
        }

        db_exec(
            'UPDATE orders SET status = "pending_payment" WHERE id = :id',
            ['id' => $cart['id']]
        );

        // Create invoice
        $inv_number = 'ORD-' . date('Y') . '-' . str_pad((string)$cart['id'], 4, '0', STR_PAD_LEFT);
        $inv_id = db_insert('invoices', [
            'member_id'    => $member['id'],
            'type'         => 'order',
            'order_id'     => $cart['id'],
            'number'       => $inv_number,
            'description'  => 'Branding order',
            'amount_cents' => $subtotal,
            'status'       => 'unpaid',
            'issued_at'    => date('Y-m-d'),
            'due_at'       => date('Y-m-d', strtotime('+14 days')),
        ]);

        db_insert('transactions', [
            'member_id'    => $member['id'],
            'invoice_id'   => $inv_id,
            'type'         => 'charge',
            'amount_cents' => $subtotal,
            'description'  => "Branding order $inv_number",
        ]);

        header('Location: welcome.php?checkout=pending'); exit;
    }
}

// Load cart items for display
$items = db_all(
    'SELECT oi.*, bi.name, bi.slug, bi.price_display
       FROM order_items oi
       JOIN branding_items bi ON bi.id = oi.branding_item_id
       WHERE oi.order_id = :o
       ORDER BY oi.id ASC',
    ['o' => $cart['id']]
);
?>

<section class="section">
    <div class="container" style="max-width:900px;">

        <h1>Your Cart</h1>

        <?php if (isset($_GET['updated'])): ?>
            <div class="alert alert-success" data-autohide>Cart updated.</div>
        <?php endif; ?>
        <?php if (isset($_GET['added'])): ?>
            <div class="alert alert-success" data-autohide>
                Added <?= htmlspecialchars($_GET['added']) ?> to your cart.
            </div>
        <?php endif; ?>
        <?php if (($_GET['error'] ?? '') === 'empty'): ?>
            <div class="alert alert-error">Your cart is empty.</div>
        <?php endif; ?>

        <?php if (empty($items)): ?>
            <div class="card">
                <p>Your cart is empty.</p>
                <p><a href="../additional-branding.php" class="btn">Browse branding options</a></p>
            </div>
        <?php else: ?>
            <form method="post" action="cart.php">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="update">

                <div class="card">
                    <table>
                        <tr>
                            <th>Item</th>
                            <th>Price</th>
                            <th style="width:100px;">Quantity</th>
                            <th style="text-align:right;">Line total</th>
                        </tr>
                        <?php foreach ($items as $it): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($it['name']) ?></strong></td>
                                <td><?= htmlspecialchars($it['price_display']) ?></td>
                                <td>
                                    <input type="number" name="qty[<?= $it['id'] ?>]" value="<?= (int)$it['quantity'] ?>" min="0" style="width:70px;">
                                </td>
                                <td style="text-align:right;"><?= cents_to_rand((int)$it['line_total_cents']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <tr style="font-weight:700;background:var(--surface-alt);">
                            <td colspan="3" style="text-align:right;">Total:</td>
                            <td style="text-align:right;"><?= cents_to_rand((int)$cart['total_cents']) ?></td>
                        </tr>
                    </table>

                    <p class="muted mt-2" style="font-size:.85rem;">
                        Set quantity to 0 to remove an item. Click "Update cart" to save changes.
                    </p>

                    <div class="mt-3">
                        <button type="submit" class="btn btn-outline">Update cart</button>
                        <a href="../additional-branding.php" class="btn btn-outline">Keep shopping</a>
                    </div>
                </div>
            </form>

            <div class="card mt-3">
                <h2 style="margin-top:0;">Checkout</h2>
                <p class="muted">
                    Pay securely via PayFast. After payment, your order will be produced
                    and shipped within 10 business days.
                </p>
                <p style="font-size:.85rem;" class="muted">
                    Prefer EFT? Generate an invoice first and use the banking details on your
                    <a href="view-statement.php">Statement</a> page. An admin will mark it paid once received.
                </p>
                <div class="mt-2">
                    <a href="checkout-cart.php" class="btn">Pay with PayFast &rarr;</a>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>
