<?php
require_once __DIR__ . '/includes/init.php';
require_login();

$cart = $_SESSION['cart'] ?? [];
$cart_products = [];
$total_price = 0;

if (empty($cart)) {
    header('Location: index.php');
    exit;
}

if (!empty($cart)) {
    $product_ids = array_keys($cart);
    $placeholders = implode(',', array_fill(0, count($product_ids), '?'));

    try {
        $pdo = db();
        
        $client_id = $_SESSION['client_id'] ?? null;
        $credit_info = null;
        if ($client_id) {
            $stmt = $pdo->prepare('SELECT credit_limit, credit_balance, credit_enabled FROM clients WHERE id = ?');
            $stmt->execute([$client_id]);
            $credit_info = $stmt->fetch(PDO::FETCH_ASSOC);
        }

        $sql = "SELECT p.id, p.name, p.units_per_pallet FROM products p WHERE p.id IN ($placeholders)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($product_ids);
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $lang = $_SESSION['lang'] ?? 'pl';
        $is_supplier_delivery = false;

        foreach ($products as $product) {
            $quantity = $cart[$product['id']];

            $price_info = getEffectivePrice($pdo, $product['id'], $client_id);
            $price_net = $price_info['net'];
            $price_gross = $price_info['gross'];

            $line_total = ($lang === 'en') ? ($price_net * $quantity) : ($price_gross * $quantity);
            
            $cart_products[] = [
                'id' => $product['id'],
                'name' => $product['name'],
                'price_net' => $price_net,
                'price_gross' => $price_gross,
                'quantity' => $quantity,
                'line_total' => $line_total,
            ];
            $total_price += $line_total;

            // Check for full pallets only if units_per_pallet is set and positive
            if (isset($product['units_per_pallet']) && $product['units_per_pallet'] > 0) {
                if ($quantity >= $product['units_per_pallet']) {
                    $is_supplier_delivery = true;
                }
            }
        }

        $delivery_source = $is_supplier_delivery ? 'supplier' : 'cs';

    } catch (PDOException $e) {
        die(t('db_error_generic') . $e->getMessage());
    }
}

$page_title = t('checkout_title');

require_once __DIR__ . '/includes/html_head.php';
require_once __DIR__ . '/includes/header.php';

?>

<main class="container my-5">
    <h1 class="mb-4"><?= t('checkout_title') ?></h1>

    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header"><?= t('your_order') ?></div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th><?= t('product') ?></th>
                                <th><?= t('quantity') ?></th>
                                <th><?= t('price_net') ?></th>
                                <th><?= t('price_gross') ?></th>
                                <th><?= ($lang === 'en') ? t('total_net') : t('total_gross') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($cart_products as $item): ?>
                                <tr>
                                    <td><?= htmlspecialchars($item['name']) ?></td>
                                    <td><?= $item['quantity'] ?></td>
                                    <td><?= format_money($item['price_net'], $_SESSION['lang'] ?? 'pl', $pdo) ?></td>
                                    <td><?= format_money($item['price_gross'], $_SESSION['lang'] ?? 'pl', $pdo) ?></td>
                                    <td><?= format_money($item['line_total'], $_SESSION['lang'] ?? 'pl', $pdo) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="4" class="text-end"><strong><?= ($lang === 'en') ? t('total_net') : t('total_gross') ?>:</strong></td>
                                <td><strong><?= format_money($total_price, $_SESSION['lang'] ?? 'pl', $pdo) ?></strong></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-header"><?= t('delivery_payment_options') ?></div>
                <div class="card-body">
                    <div class="alert alert-secondary">
                        <?= t('delivery_source') ?>: <strong><?= ($delivery_source === 'cs') ? t('central_warehouse') : t('external_supplier') ?></strong>
                    </div>
                    <?php if ($credit_info && $credit_info['credit_enabled']): ?>
                    <div class="alert alert-info">
                        <?= t('available_trade_credit') ?>: <strong><?= format_money($credit_info['credit_balance'], $_SESSION['lang'] ?? 'pl', $pdo) ?></strong>
                    </div>
                    <?php endif; ?>
                    <form action="order_process.php" method="POST">
                        <div class="mb-3">
                            <label for="payment_method" class="form-label"><?= t('payment_method') ?></label>
                            <select class="form-select" id="payment_method" name="payment_method" required>
                                <option value="bank_transfer"><?= t('payment_bank_transfer') ?></option>
                                <option value="online"><?= t('payment_online') ?></option>
                                <?php if ($credit_info && $credit_info['credit_enabled'] && $credit_info['credit_balance'] >= $total_price): ?>
                                <option value="credit"><?= t('payment_trade_credit') ?></option>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="notes" class="form-label"><?= t('order_notes') ?></label>
                            <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                        </div>
                        <input type="hidden" name="total_amount" value="<?= $total_price ?>">
                        <button type="submit" class="btn btn-primary w-100"><?= t('confirm_order') ?></button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>

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