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

$page_title = t('cart_header');

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

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;

        $stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
        $stmt->execute($product_ids);
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

        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;
        }
    } catch (PDOException $e) {
        die(t('db_connection_error') . $e->getMessage());
    }
}

$user_role = get_user_role();

?>

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

    <?php if (empty($cart_products)): ?>
        <div class="alert alert-info" role="alert">
            <?= t('empty_cart_message') ?>
        </div>
        <a href="index.php" class="btn btn-primary"><?= t('back_to_shop') ?></a>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th><?= t('product') ?></th>
                        <th><?= t('price_net') ?></th>
                        <th><?= t('price_gross') ?></th>
                        <th><?= t('quantity') ?></th>
                        <th><?= t('total') ?></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($cart_products as $item): ?>
                        <tr>
                            <td><?= htmlspecialchars($item['name']) ?></td>
                            <td><?= format_money($item['price_net'], $_SESSION['lang'] ?? 'pl', $pdo) ?> <?= t('net') ?></td>
                            <td><?= format_money($item['price_gross'], $_SESSION['lang'] ?? 'pl', $pdo) ?> <?= t('gross') ?></td>
                            <td>
                                <form action="cart_actions.php" method="POST" class="d-inline-flex align-items-center">
                                    <input type="hidden" name="action" value="update">
                                    <input type="hidden" name="product_id" value="<?= $item['id'] ?>">
                                    <input type="hidden" name="redirect_to" value="cart.php">
                                    <label for="quantity-<?= $item['id'] ?>" class="visually-hidden"><?= t('quantity') ?></label>
                                    <input type="number" id="quantity-<?= $item['id'] ?>" name="quantity" value="<?= $item['quantity'] ?>" min="1" class="form-control form-control-sm" style="width: 70px;" aria-label="<?= t('quantity') ?>">
                                    <button type="submit" class="btn btn-secondary ms-2"><?= t('update_button') ?></button>
                                </form>
                            </td>
                            <td><?= format_money($item['line_total'], $_SESSION['lang'] ?? 'pl', $pdo) ?></td>
                            <td>
                                <form action="cart_actions.php" method="POST" class="d-inline">
                                    <input type="hidden" name="action" value="remove">
                                    <input type="hidden" name="product_id" value="<?= $item['id'] ?>">
                                    <input type="hidden" name="redirect_to" value="cart.php">
                                    <button type="submit" class="btn btn-sm btn-danger" aria-label="<?= t('remove_button') ?>"><i class="bi bi-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" class="text-end"><strong><?= ($lang === 'en') ? t('total_net_label') : t('total_gross_label') ?></strong></td>
                        <td colspan="2"><strong><?= format_money($total_price, $_SESSION['lang'] ?? 'pl', $pdo) ?></strong></td>
                    </tr>
                </tfoot>
            </table>
        </div>

        <div class="d-flex justify-content-between mt-4">
            <a href="index.php" class="btn btn-outline-secondary"><?= t('back_to_shop') ?></a>
            <a href="checkout.php" class="btn btn-primary"><?= t('proceed_to_checkout') ?></a>
        </div>
    <?php endif; ?>
</main>

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