<?php
/**
 * TechShop Perú - Detalle de Pedido con Order Tracker Visual de 5 Etapas
 */
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

require_login();

$db = db();
$pedido_id = (int)($_GET['pedido'] ?? 0);
$usuario_id = (int)$_SESSION['usuario_id'];

$stmt = $db->prepare('SELECT * FROM pedidos WHERE id = ? AND usuario_id = ?');
$stmt->execute([$pedido_id, $usuario_id]);
$pedido = $stmt->fetch();

if (!$pedido) {
    set_flash('error', 'Pedido no encontrado.');
    redirect('pages/cuenta.php?tab=pedidos');
}

$stmt = $db->prepare('SELECT * FROM detalles_pedido WHERE pedido_id = ?');
$stmt->execute([$pedido_id]);
$detalles = $stmt->fetchAll();

// Etapa del Tracker (1 a 5)
$estadoActual = strtolower($pedido['estado']);
$etapa = match($estadoActual) {
    'pendiente' => 1,
    'confirmado' => 2,
    'enviado' => 4,
    'entregado' => 5,
    default => 1
};

$page_title = 'Detalle de Pedido #' . $pedido['numero_pedido'];
require_once __DIR__ . '/../includes/header.php';
?>

<section class="page-header"><div class="container"><h1>Detalle de Pedido</h1><nav aria-label="breadcrumb"><ol class="breadcrumb mb-0"><li class="breadcrumb-item"><a href="<?= url('') ?>">Inicio</a></li><li class="breadcrumb-item"><a href="<?= url('pages/cuenta.php?tab=pedidos') ?>">Mis pedidos</a></li><li class="breadcrumb-item active">#<?= e($pedido['numero_pedido']) ?></li></ol></nav></div></section>

<section class="py-5">
    <div class="container">
        <!-- 📍 SEGUIMIENTO VISUAL DE PEDIDO (ORDER TRACKER) -->
        <div class="card border-0 shadow-sm p-4 mb-4">
            <h5 class="fw-bold mb-4"><i class="bi bi-geo-alt-fill text-primary me-2"></i>Seguimiento de tu Pedido en Tiempo Real</h5>
            
            <?php if ($estadoActual === 'cancelado'): ?>
                <div class="alert alert-danger mb-0"><i class="bi bi-x-circle-fill me-2"></i>Este pedido fue cancelado.</div>
            <?php else: ?>
                <div class="row text-center g-2 position-relative">
                    <div class="col">
                        <div class="rounded-circle d-inline-flex align-items-center justify-content-center <?= $etapa >= 1 ? 'bg-primary text-white' : 'bg-light text-muted' ?>" style="width: 46px; height: 46px; font-size: 1.2rem;">
                            <i class="bi bi-clock-history"></i>
                        </div>
                        <div class="fw-bold small mt-2">1. En Verificación</div>
                        <small class="text-muted d-none d-md-block">Pago registrado</small>
                    </div>
                    <div class="col">
                        <div class="rounded-circle d-inline-flex align-items-center justify-content-center <?= $etapa >= 2 ? 'bg-primary text-white' : 'bg-light text-muted' ?>" style="width: 46px; height: 46px; font-size: 1.2rem;">
                            <i class="bi bi-box-seam"></i>
                        </div>
                        <div class="fw-bold small mt-2">2. En Preparación</div>
                        <small class="text-muted d-none d-md-block">Empacando productos</small>
                    </div>
                    <div class="col">
                        <div class="rounded-circle d-inline-flex align-items-center justify-content-center <?= $etapa >= 3 ? 'bg-primary text-white' : 'bg-light text-muted' ?>" style="width: 46px; height: 46px; font-size: 1.2rem;">
                            <i class="bi bi-building"></i>
                        </div>
                        <div class="fw-bold small mt-2">3. En Agencia Courier</div>
                        <small class="text-muted d-none d-md-block">Olva / Shalom</small>
                    </div>
                    <div class="col">
                        <div class="rounded-circle d-inline-flex align-items-center justify-content-center <?= $etapa >= 4 ? 'bg-primary text-white' : 'bg-light text-muted' ?>" style="width: 46px; height: 46px; font-size: 1.2rem;">
                            <i class="bi bi-truck"></i>
                        </div>
                        <div class="fw-bold small mt-2">4. En Camino</div>
                        <small class="text-muted d-none d-md-block">Reparto a domicilio</small>
                    </div>
                    <div class="col">
                        <div class="rounded-circle d-inline-flex align-items-center justify-content-center <?= $etapa >= 5 ? 'bg-success text-white' : 'bg-light text-muted' ?>" style="width: 46px; height: 46px; font-size: 1.2rem;">
                            <i class="bi bi-house-check-fill"></i>
                        </div>
                        <div class="fw-bold small mt-2">5. Entregado</div>
                        <small class="text-muted d-none d-md-block">Recibido</small>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <div class="card border-0 shadow-sm">
            <div class="card-body p-4">
                <div class="row g-4">
                    <div class="col-md-7">
                        <h4 class="fw-bold mb-3">Pedido #<?= e($pedido['numero_pedido']) ?></h4>
                        <p class="text-muted mb-2"><strong>Fecha:</strong> <?= format_fecha($pedido['fecha_pedido']) ?></p>
                        <p class="text-muted mb-2"><strong>Comprobante:</strong> <?= strtoupper(e($pedido['tipo_comprobante'])) ?> (Doc: <?= e($pedido['num_documento']) ?>)</p>
                        <p class="text-muted mb-2"><strong>Método de Pago:</strong> <?= strtoupper(str_replace('_', ' ', e($pedido['metodo_pago']))) ?></p>
                        <p class="text-muted mb-3"><strong>Dirección de Envío:</strong> <?= e($pedido['direccion_envio']) ?>, <?= e($pedido['ciudad_envio']) ?>, <?= e($pedido['departamento_envio']) ?></p>
                        <a href="<?= url('pages/comprobante.php?pedido_id=' . $pedido['id']) ?>" target="_blank" class="btn btn-outline-primary btn-sm">
                            <i class="bi bi-file-earmark-pdf me-1"></i> Ver / Imprimir Comprobante Electrónico
                        </a>
                    </div>
                    <div class="col-md-5">
                        <div class="bg-light rounded p-3">
                            <div class="d-flex justify-content-between mb-2"><span>Subtotal</span><span><?= format_precio((float)$pedido['subtotal']) ?></span></div>
                            <?php if ($pedido['descuento'] > 0): ?>
                            <div class="d-flex justify-content-between mb-2 text-success"><span>Descuento</span><span>- <?= format_precio((float)$pedido['descuento']) ?></span></div>
                            <?php endif; ?>
                            <div class="d-flex justify-content-between mb-2"><span>Envío</span><span><?= format_precio((float)$pedido['envio']) ?></span></div>
                            <hr>
                            <div class="d-flex justify-content-between fw-bold fs-5"><span>Total</span><span><?= format_precio((float)$pedido['total']) ?></span></div>
                        </div>
                    </div>
                </div>
                <hr class="my-4">
                <div class="table-responsive">
                    <table class="table align-middle">
                        <thead class="table-light"><tr><th>Producto</th><th class="text-center">Cantidad</th><th class="text-end">Precio unitario</th><th class="text-end">Subtotal</th></tr></thead>
                        <tbody>
                            <?php foreach ($detalles as $detalle): ?>
                            <tr>
                                <td class="fw-medium"><?= e($detalle['nombre_producto']) ?></td>
                                <td class="text-center"><?= (int)$detalle['cantidad'] ?></td>
                                <td class="text-end"><?= format_precio((float)$detalle['precio_unitario']) ?></td>
                                <td class="text-end fw-bold"><?= format_precio((float)$detalle['subtotal']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</section>

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