<?php
/**
 * TechShop Perú - API Quick View (Vista Rápida de Producto)
 */
define('SECURE_ACCESS', true);
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID de producto no válido']);
    exit;
}

try {
    $db = db();
    $stmt = $db->prepare('
        SELECT p.*, c.nombre AS categoria_nombre, m.nombre AS marca_nombre 
        FROM productos p
        JOIN categorias c ON p.categoria_id = c.id
        JOIN marcas m ON p.marca_id = m.id
        WHERE p.id = ? AND p.activo = 1
    ');
    $stmt->execute([$id]);
    $p = $stmt->fetch();

    if (!$p) {
        echo json_encode(['success' => false, 'message' => 'Producto no disponible']);
        exit;
    }

    $precioFinal = precio_final($p);
    $tieneOferta = tiene_oferta($p);
    $imagen = !empty($p['imagen_principal']) ? UPLOADS_URL . '/products/' . $p['imagen_principal'] : ASSETS_URL . '/images/placeholder-product.svg';

    ob_start();
    ?>
    <div class="row align-items-center">
        <div class="col-md-6 text-center">
            <img src="<?= $imagen ?>" alt="<?= e($p['nombre']) ?>" class="img-fluid rounded p-2" style="max-height:280px; object-fit:contain;">
        </div>
        <div class="col-md-6">
            <span class="badge bg-secondary mb-2"><?= e($p['marca_nombre']) ?></span>
            <h5 class="fw-bold mb-2"><?= e($p['nombre']) ?></h5>
            <div class="mb-2"><?= render_estrellas((float)$p['calificacion']) ?></div>
            <div class="fs-4 fw-bold text-primary mb-2">
                <?= format_precio($precioFinal) ?>
                <?php if ($tieneOferta): ?>
                <span class="text-muted fs-6 text-decoration-line-through ms-2"><?= format_precio((float)$p['precio']) ?></span>
                <?php endif; ?>
            </div>
            <p class="small text-muted mb-3"><?= e($p['descripcion_corta'] ?? 'Producto tecnológico con garantía oficial TechShop Perú.') ?></p>
            <div class="mb-3">
                <?php if ($p['stock'] > 0): ?>
                <span class="text-success small fw-semibold"><i class="bi bi-check-circle-fill me-1"></i>En stock (<?= $p['stock'] ?> uds.)</span>
                <?php else: ?>
                <span class="text-danger small fw-semibold"><i class="bi bi-x-circle-fill me-1"></i>Agotado</span>
                <?php endif; ?>
            </div>
            <div class="d-flex gap-2">
                <?php if ($p['stock'] > 0): ?>
                <button class="btn btn-primary add-to-cart-btn flex-grow-1" data-producto-id="<?= $p['id'] ?>">
                    <i class="bi bi-cart-plus me-1"></i>Agregar al carrito
                </button>
                <?php endif; ?>
                <a href="<?= url('pages/detalle.php?slug='.$p['slug']) ?>" class="btn btn-outline-secondary">Ver Detalle Completo</a>
            </div>
        </div>
    </div>
    <?php
    $html = ob_get_clean();

    echo json_encode(['success' => true, 'html' => $html]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error al cargar vista rápida']);
}
