<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'includes/lang.php';
require_once 'includes/auth.php';
require_login();
require_once 'includes/helpers.php';

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

$cart = $_SESSION['cart'] ?? [];
if (empty($cart)) {
    header('Location: index.php');
    exit;
}

$pdo = db();

try {
    $pdo->beginTransaction();

    // 1. Get product details from the database
    $product_ids = array_keys($cart);
    $placeholders = implode(',', array_fill(0, count($product_ids), '?'));
    $stmt = $pdo->prepare("SELECT id, price, units_per_pallet FROM products WHERE id IN ($placeholders)");
    $stmt->execute($product_ids);
    $products_by_id = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC);


    // 2. Calculate total amount
    $total_amount_gross = 0;
    $client_id = $_SESSION['client_id'] ?? null;
    
    $order_items_data = [];

    $is_supplier_delivery = false;
    foreach ($cart as $product_id => $quantity) {
        if (isset($products_by_id[$product_id])) {
            $product = $products_by_id[$product_id];
            
            $price_info = getEffectivePrice($pdo, $product_id, $client_id);
            $price_gross = $price_info['gross'];

            $total_amount_gross += $price_gross * $quantity;

            $order_items_data[] = [
                'product_id' => $product_id,
                'quantity' => $quantity,
                'unit_price' => $price_gross, // Save gross price
                'line_total' => $price_gross * $quantity,
            ];

            $units_per_pallet = $product['units_per_pallet'];
            if (isset($units_per_pallet) && $units_per_pallet > 0) {
                if ($quantity >= $units_per_pallet) {
                    $is_supplier_delivery = true;
                }
            }
        }
    }
    
    $delivery_source = $is_supplier_delivery ? 'supplier' : 'cs';

    if ($_POST['payment_method'] === 'credit') {
        $stmt = $pdo->prepare('SELECT credit_balance, credit_enabled FROM clients WHERE id = ? FOR UPDATE');
        $stmt->execute([$client_id]);
        $credit_info = $stmt->fetch();

        if (!$credit_info || !$credit_info['credit_enabled'] || $credit_info['credit_balance'] < $total_amount_gross) {
            throw new Exception('Invalid payment method or insufficient credit.');
        }

        $new_balance = $credit_info['credit_balance'] - $total_amount_gross;
        $stmt = $pdo->prepare('UPDATE clients SET credit_balance = ? WHERE id = ?');
        $stmt->execute([$new_balance, $client_id]);
    }

    // 3. Create the order
    $stmt = $pdo->prepare(
        'INSERT INTO orders (client_id, total_amount, payment_method, delivery_source, notes, status) VALUES (?, ?, ?, ?, ?, ?)'
    );
    $stmt->execute([
        $client_id,
        $total_amount_gross,
        $_POST['payment_method'],
        $delivery_source,
        $_POST['notes'],
        $_POST['payment_method'] === 'credit' ? 'in_progress' : 'pending_payment'
    ]);
    $order_id = $pdo->lastInsertId();

    // 4. Insert order items
    $stmt = $pdo->prepare(
        'INSERT INTO order_items (order_id, product_id, quantity, unit_price, line_total) VALUES (?, ?, ?, ?, ?)'
    );
    foreach ($order_items_data as $item) {
        $stmt->execute([
            $order_id,
            $item['product_id'],
            $item['quantity'],
            $item['unit_price'],
            $item['line_total'],
        ]);
    }

    // 5. Commit the transaction
    $pdo->commit();

    // 6. Clear the cart and store order ID in session for the confirmation page
    unset($_SESSION['cart']);
    $_SESSION['latest_order_id'] = $order_id;

    // 7. Redirect to confirmation page
    header('Location: order_confirmation.php');
    exit;

} catch (PDOException $e) {
    $pdo->rollBack();
    // In a real application, log this error
    die("Błąd podczas przetwarzania zamówienia: " . $e->getMessage());
}
