<?php
/**
 * TechShop Perú - Carrito de Compras
 */
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

$page_title = 'Carrito de Compras';
$db = db();

$items = [];
$subtotal = 0;

try {
    if (is_logged_in()) {
        $stmt = $db->prepare('SELECT c.id, c.cantidad, p.id AS producto_id, p.nombre, p.slug, p.imagen_principal, p.precio, p.precio_oferta, p.stock, p.activo FROM carrito c JOIN productos p ON c.producto_id = p.id WHERE c.usuario_id = ? ORDER BY c.id');
        $stmt->execute([$_SESSION['usuario_id']]);
    } else {
        $stmt = $db->prepare('SELECT c.id, c.cantidad, p.id AS producto_id, p.nombre, p.slug, p.imagen_principal, p.precio, p.precio_oferta, p.stock, p.activo FROM carrito c JOIN productos p ON c.producto_id = p.id WHERE c.sesion_id = ? ORDER BY c.id');
        $stmt->execute([$_SESSION['carrito_sesion_id']]);
    }
    $items = $stmt->fetchAll();
} catch (PDOException $e) {
    $items = [];
}

foreach ($items as &$item) {
    $item['precio_final'] = precio_final($item);
    $item['total'] = $item['precio_final'] * $item['cantidad'];
    $subtotal += $item['total'];
}
unset($item);

// Cálculo de cupón de descuento
$cuponDescuento = 0;
$cuponInfo = $_SESSION['cupon'] ?? null;
if ($cuponInfo && $subtotal > 0) {
    if ($cuponInfo['tipo'] === 'porcentaje') {
        $cuponDescuento = round(($subtotal * $cuponInfo['valor']) / 100, 2);
    } else {
        $cuponDescuento = min((float)$cuponInfo['valor'], $subtotal);
    }
}

$subtotalConDescuento = max(0, $subtotal - $cuponDescuento);
$envio = $subtotal > 0 ? 15.00 : 0;
$total = $subtotalConDescuento + $envio;

require_once __DIR__ . '/../includes/header.php';
?>

<section class="page-header"><div class="container"><h1>Carrito de Compras</h1><nav aria-label="breadcrumb"><ol class="breadcrumb mb-0"><li class="breadcrumb-item"><a href="<?= url('') ?>">Inicio</a></li><li class="breadcrumb-item active">Carrito</li></ol></nav></div></section>

<section class="py-5">
    <div class="container">
        <?= flash_message() ?>
        <?php if (empty($items)): ?>
        <div class="empty-state"><i class="bi bi-cart-x"></i><h4>Tu carrito está vacío</h4><p class="text-muted">Agrega productos desde nuestro catálogo.</p><a href="<?= url('pages/productos.php') ?>" class="btn btn-primary"><i class="bi bi-grid me-2"></i>Explorar Productos</a></div>
        <?php else: ?>
        <div class="checkout-steps">
            <div class="step-item active"><span class="step-dot"><i class="bi bi-cart-fill"></i></span>Carrito</div>
            <div class="step-sep"></div>
            <div class="step-item"><span class="step-dot"><i class="bi bi-credit-card-fill"></i></span>Datos y Pago</div>
            <div class="step-sep"></div>
            <div class="step-item"><span class="step-dot"><i class="bi bi-check-lg"></i></span>Confirmación</div>
        </div>
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table align-middle mb-0">
                                <thead class="table-light"><tr><th>Producto</th><th class="text-center">Cantidad</th><th class="text-end">Precio</th><th class="text-end">Subtotal</th><th></th></tr></thead>
                                <tbody>
                                    <?php foreach ($items as $item):
                                        $img = !empty($item['imagen_principal']) ? UPLOADS_URL.'/products/'.$item['imagen_principal'] : ASSETS_URL.'/images/placeholder-product.svg';
                                    ?>
                                    <tr class="cart-item-row" data-cart-id="<?= $item['id'] ?>">
                                        <td class="d-flex align-items-center gap-3">
                                            <a href="<?= url('pages/detalle.php?slug='.$item['slug']) ?>"><img src="<?= $img ?>" alt="<?= e($item['nombre']) ?>" class="cart-item-img" style="width:70px;height:70px;object-fit:contain;"></a>
                                            <div><a href="<?= url('pages/detalle.php?slug='.$item['slug']) ?>" class="fw-medium text-decoration-none text-dark"><?= e($item['nombre']) ?></a></div>
                                        </td>
                                        <td class="text-center" style="width:130px;">
                                            <div class="input-group input-group-sm"><button class="btn btn-outline-secondary qty-btn qty-minus" type="button">-</button><input type="number" class="form-control text-center cart-qty-input" value="<?= $item['cantidad'] ?>" min="1" max="<?= $item['stock'] ?>" style="width:45px;"><button class="btn btn-outline-secondary qty-btn qty-plus" type="button">+</button></div>
                                        </td>
                                        <td class="text-end fw-medium"><?= format_precio((float)$item['precio_final']) ?></td>
                                        <td class="text-end fw-bold"><?= format_precio((float)$item['total']) ?></td>
                                        <td class="text-center"><button class="btn btn-sm text-danger cart-remove-btn" data-cart-id="<?= $item['id'] ?>" title="Eliminar"><i class="bi bi-trash"></i></button></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <a href="<?= url('pages/productos.php') ?>" class="btn btn-outline-primary"><i class="bi bi-arrow-left me-2"></i>Seguir Comprando</a>
            </div>
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm p-4 mb-3">
                    <h5 class="fw-bold mb-3"><i class="bi bi-ticket-perforated text-primary me-2"></i>¿Tienes un cupón?</h5>
                    <form id="coupon-form" class="d-flex gap-2">
                        <input type="text" id="coupon-code-input" class="form-control text-uppercase" placeholder="Ej: VERANO2026" value="<?= e($cuponInfo['codigo'] ?? '') ?>">
                        <button type="submit" class="btn btn-dark text-nowrap">Aplicar</button>
                    </form>
                    <?php if ($cuponInfo): ?>
                        <div class="mt-2 text-success small d-flex align-items-center justify-content-between">
                            <span><i class="bi bi-check-circle-fill me-1"></i>Cupón <b><?= e($cuponInfo['codigo']) ?></b> activo (<?= e($cuponInfo['descripcion']) ?>)</span>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="cart-summary p-4">
                    <h5 class="fw-bold mb-3"><i class="bi bi-receipt-cutoff text-primary me-2"></i>Resumen del Pedido</h5>
                    <div class="d-flex justify-content-between mb-2"><span>Subtotal</span><span><?= format_precio($subtotal) ?></span></div>
                    <?php if ($cuponDescuento > 0): ?>
                        <div class="d-flex justify-content-between mb-2 text-success"><span>Descuento (<?= e($cuponInfo['codigo']) ?>)</span><span>- <?= format_precio($cuponDescuento) ?></span></div>
                    <?php endif; ?>
                    <div class="d-flex justify-content-between mb-2"><span>Envío estimado (Lima)</span><span><?= format_precio($envio) ?></span></div>
                    <hr class="my-3">
                    <div class="summary-total-row d-flex justify-content-between align-items-center fw-bold fs-5 mb-3"><span>Total</span><span class="text-primary"><?= format_precio($total) ?></span></div>
                    <small class="text-muted d-block mb-3"><i class="bi bi-info-circle me-1"></i>* Precios incluyen IGV (18%).</small>
                    <a href="<?= url('pages/checkout.php') ?>" class="btn btn-primary btn-lg w-100"><i class="bi bi-credit-card me-2"></i>Proceder al Pago</a>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

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