<?php
require_once __DIR__ . '/config/database.php';

$productId = (int)($_GET['product_id'] ?? 0);
$variationId = (int)($_GET['variation_id'] ?? 0);
$qty = max(1, (int)($_GET['qty'] ?? 1));

if (!$productId) redirect(BASE_URL . '/index.php');

// Get product
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$productId]);
$product = $stmt->fetch();

if (!$product) redirect(BASE_URL . '/index.php');
if ($product['stock'] <= 0) redirect(BASE_URL . '/product.php?id=' . $productId . '&error=out_of_stock');

// Get variation
$variation = null;
$extraPrice = 0;
$varInfo = '';
if ($variationId) {
    $vs = $pdo->prepare("SELECT * FROM product_variations WHERE id = ? AND product_id = ?");
    $vs->execute([$variationId, $productId]);
    $variation = $vs->fetch();
    if ($variation) {
        $extraPrice = (float)$variation['extra_price'];
        $varInfo = $variation['variation_name'] . ': ' . $variation['variation_value'];
    }
}

$price = (float)$product['price'] + $extraPrice;

// Initialize checkout session
if (!isset($_SESSION['checkout_items'])) {
    $_SESSION['checkout_items'] = [];
}

// Check if same product+variation already in cart - if yes, increase qty
$found = false;
foreach ($_SESSION['checkout_items'] as &$item) {
    if ($item['product_id'] == $productId && $item['variation_id'] == $variationId) {
        $item['quantity'] += $qty;
        $found = true;
        break;
    }
}
unset($item);

if (!$found) {
    $_SESSION['checkout_items'][] = [
        'product_id'   => $productId,
        'variation_id' => $variationId,
        'variation_info' => $varInfo,
        'quantity'     => $qty,
        'price'        => $price,
        'product_name' => $product['name'],
        'product_image'=> $product['image'],
    ];
}

redirect(BASE_URL . '/checkout.php');
