<?php
// ============================================================
//  Add a branding item to the logged-in member's cart
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
auth_require_login();

$member = auth_user();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../additional-branding.php');
    exit;
}

csrf_verify();

$slug = $_POST['item_slug'] ?? '';
$qty  = max(1, (int)($_POST['quantity'] ?? 1));

$item = db_row(
    'SELECT * FROM branding_items WHERE slug = :s AND active = 1',
    ['s' => $slug]
);
if (!$item) {
    header('Location: ../additional-branding.php?error=notfound');
    exit;
}

// Find or create the cart
$cart = db_row(
    'SELECT * FROM orders WHERE member_id = :m AND status = "cart" LIMIT 1',
    ['m' => $member['id']]
);
if (!$cart) {
    $cart_id = db_insert('orders', [
        'member_id' => $member['id'],
        'status'    => 'cart',
    ]);
} else {
    $cart_id = (int)$cart['id'];
}

// Merge with existing line if it's already in the cart
$existing = db_row(
    'SELECT * FROM order_items WHERE order_id = :o AND branding_item_id = :i',
    ['o' => $cart_id, 'i' => $item['id']]
);

$price = (int)$item['price_cents'];

if ($existing) {
    $new_qty  = (int)$existing['quantity'] + $qty;
    $new_line = $new_qty * $price;
    db_exec(
        'UPDATE order_items SET quantity = :q, line_total_cents = :lt WHERE id = :id',
        ['q' => $new_qty, 'lt' => $new_line, 'id' => $existing['id']]
    );
} else {
    db_insert('order_items', [
        'order_id'         => $cart_id,
        'branding_item_id' => $item['id'],
        'quantity'         => $qty,
        'unit_price_cents' => $price,
        'line_total_cents' => $price * $qty,
    ]);
}

// Recompute cart totals
$subtotal = (int)db_value(
    'SELECT COALESCE(SUM(line_total_cents), 0) FROM order_items WHERE order_id = :o',
    ['o' => $cart_id]
);
db_exec(
    'UPDATE orders SET subtotal_cents = :s, total_cents = :s WHERE id = :id',
    ['s' => $subtotal, 'id' => $cart_id]
);

header('Location: cart.php?added=' . urlencode($item['name']));
exit;
