<?php
require_once __DIR__ . '/includes/config.php';

$slug = $_GET['slug'] ?? '';
if (!$slug) { header('Location: /'); exit; }

$product = getProductBySlug($slug);
if (!$product) { http_response_code(404); echo '404 Not Found'; exit; }

$fitments = getProductFitments($product['id']);

// ── SEO ─────────────────────────────────────────────────────────────────────────
$pageTitle       = $product['name'] . ' by ' . $product['brand_name'] . ' | ' . SITE_NAME;
$metaDescription = 'Buy the ' . $product['name'] . ' by ' . $product['brand_name'] . ' at ' . SITE_NAME . '. ' . substr($product['description'] ?? '', 0, 140) . ' Exact fitment guaranteed. SKU: ' . $product['sku'] . '. Free shipping on orders over $99.';
$canonicalUrl    = siteUrl('product.php?slug=' . urlencode($slug));
$ogType          = 'product';

$ogExtra = '';
if ($product['image_url']) {
    $ogExtra = '<meta property="og:image" content="' . siteUrl($product['image_url']) . '">';
    $ogExtra .= '<meta property="product:price:amount" content="' . number_format($product['discount_price'], 2, '.', '') . '">';
    $ogExtra .= '<meta property="product:price:currency" content="USD">';
}

ob_start(); ?>
<script type="application/ld+json">
{
  "@context": "https://schema.org/",
  "@type": "Product",
  "name": "<?= e($product['name']) ?>",
  "image": ["<?= siteUrl($product['image_url'] ?? '') ?>"],
  "description": "<?= e($product['description'] ?? '') ?>",
  "sku": "<?= e($product['sku']) ?>",
  "brand": {"@type": "Brand", "name": "<?= e($product['brand_name']) ?>"},
  "category": "<?= e($product['category_name']) ?>",
  "offers": {
    "@type": "Offer",
    "url": "<?= e($canonicalUrl) ?>",
    "priceCurrency": "USD",
    "price": "<?= number_format($product['discount_price'], 2, '.', '') ?>",
    "priceValidUntil": "<?= date('Y-m-d', strtotime('+1 year')) ?>",
    "itemCondition": "https://schema.org/NewCondition",
    "availability": "<?= $product['stock'] > 0 ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock' ?>",
    "seller": {"@type": "Organization", "name": "<?= SITE_NAME ?>"}
  }
}
</script>
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [
    {"@type": "ListItem", "position": 1, "name": "Home", "item": "<?= SITE_URL ?>"},
    {"@type": "ListItem", "position": 2, "name": "<?= e($product['category_name']) ?>", "item": "<?= siteUrl('catalog.php?category=' . urlencode($product['category_slug'])) ?>"},
    {"@type": "ListItem", "position": 3, "name": "<?= e($product['name']) ?>"}
  ]
}
</script>
<?php $schemaMarkup = ob_get_clean();

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

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
    <!-- Breadcrumbs -->
    <nav class="flex mb-8" aria-label="Breadcrumb">
      <ol class="inline-flex items-center space-x-1 md:space-x-3 text-sm font-semibold text-gray-400">
        <li><a href="/" class="hover:text-white transition-colors">Home</a></li>
        <li><div class="flex items-center"><svg class="w-4 h-4 mx-1" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg><a href="/catalog.php?category=<?= urlencode($product['category_slug']) ?>" class="hover:text-white transition-colors"><?= e($product['category_name']) ?></a></div></li>
        <li><div class="flex items-center text-gray-500"><svg class="w-4 h-4 mx-1" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg><span class="ml-1 md:ml-2" aria-current="page"><?= e($product['name']) ?></span></div></li>
      </ol>
    </nav>

    <article class="lg:grid lg:grid-cols-2 lg:gap-16 items-start">
        <!-- Image Gallery -->
        <div class="flex flex-col gap-4">
            <div class="relative bg-black border border-gray-800 rounded-2xl overflow-hidden shadow-2xl flex items-center justify-center p-8 min-h-[500px]">
                <img src="<?= e($product['image_url'] ?: 'https://placehold.co/800x600/111/333?text=No+Image') ?>" alt="<?= e($product['name']) ?> by <?= e($product['brand_name']) ?>" class="object-contain w-full h-full max-h-[500px] drop-shadow-[0_20px_20px_rgba(0,0,0,0.9)]" width="800" height="600">
                <div class="absolute top-6 right-6 bg-brand-orange text-white text-sm font-black px-3 py-1 rounded shadow-lg uppercase tracking-widest transform -rotate-2">20% OFF MSRP</div>
            </div>
        </div>

        <!-- Product Info -->
        <div class="mt-10 lg:mt-0">
            <div class="flex items-center gap-3 mb-2">
                <span class="px-2 py-1 bg-gray-800 text-gray-300 rounded text-xs font-bold uppercase tracking-widest"><?= e($product['brand_name']) ?></span>
                <span class="text-sm text-brand-orange font-bold">SKU: <?= e($product['sku']) ?></span>
            </div>
            <h1 class="text-4xl sm:text-5xl font-black text-white tracking-tight uppercase leading-none mb-6"><?= e($product['name']) ?></h1>

            <div class="flex items-center gap-4 mb-8 border-b border-gray-800 pb-8">
                <div>
                    <p class="text-gray-500 font-semibold line-through text-lg">MSRP: $<?= number_format($product['msrp_price'], 2) ?></p>
                    <p class="text-5xl font-black text-white">$<?= number_format($product['discount_price'], 2) ?></p>
                </div>
                <?php if ($product['stock'] > 0): ?>
                <div class="ml-auto inline-flex items-center gap-2 px-4 py-2 bg-green-500/10 text-green-400 font-bold rounded-lg border border-green-500/20">
                    <div class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>IN STOCK (<?= $product['stock'] ?>)
                </div>
                <?php else: ?>
                <div class="ml-auto inline-flex items-center gap-2 px-4 py-2 bg-red-500/10 text-red-500 font-bold rounded-lg border border-red-500/20">OUT OF STOCK</div>
                <?php endif; ?>
            </div>

            <!-- Fitment -->
            <?php if (!empty($fitments)): ?>
            <div class="bg-gray-900 border border-gray-800 rounded-xl p-6 mb-8 shadow-inner">
                <h2 class="text-lg font-bold text-white mb-4 flex items-center gap-2 uppercase tracking-wide">
                    <svg class="w-5 h-5 text-brand-orange" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 002-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
                    Exact Fitment Guarantee
                </h2>
                <div class="flex flex-wrap gap-2">
                    <?php foreach (array_slice($fitments, 0, 8) as $f): ?>
                        <span class="inline-flex items-center px-3 py-1 bg-black border border-gray-700 text-gray-300 text-xs font-semibold rounded-full"><?= e($f['year'] . ' ' . $f['brand_name'] . ' ' . $f['model_name']) ?></span>
                    <?php endforeach; ?>
                    <?php if (count($fitments) > 8): ?>
                        <span class="inline-flex items-center px-3 py-1 bg-brand-orange text-white text-xs font-bold rounded-full">+<?= count($fitments) - 8 ?> More</span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="prose prose-invert prose-lg max-w-none mb-10 text-gray-400">
                <p><?= e($product['description'] ?? '') ?></p>
                <p>Designed to deliver race-ready performance and legendary durability under the most extreme motocross and enduro conditions. This <?= e($product['brand_name']) ?> component features precision engineering with bolt-on installation that requires no major modifications.</p>
                <ul class="font-semibold">
                    <li>Factory-level performance upgrades sourced directly from <?= e($product['brand_name']) ?>.</li>
                    <li>Built for specific year/make/model tolerance constraints with exact OEM cross-referencing.</li>
                    <li>Premium materials tested and proven in competitive motocross environments.</li>
                    <li>Free shipping on orders over $99 within the continental US.</li>
                </ul>
            </div>

            <form action="/cart-action.php" method="POST">
                <input type="hidden" name="action" value="add">
                <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                <button type="submit" class="w-full bg-brand-orange hover:bg-[#ff5511] text-white font-black text-lg py-5 px-8 rounded-xl transition-all shadow-[0_0_20px_rgba(255,69,0,0.3)] hover:shadow-[0_0_30px_rgba(255,69,0,0.6)] uppercase tracking-wider flex items-center justify-center gap-3 disabled:opacity-50 disabled:cursor-not-allowed" <?= $product['stock'] <= 0 ? 'disabled' : '' ?>>
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
                    Add To Cart
                </button>
            </form>
            <div class="mt-6 flex items-center justify-center gap-6 text-sm text-gray-500 font-semibold uppercase tracking-widest">
                <div class="flex items-center gap-2"><svg class="w-5 h-5 text-brand-light" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg> 100% Secure</div>
                <div class="flex items-center gap-2"><svg class="w-5 h-5 text-brand-light" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4"></path></svg> Fast Delivery</div>
            </div>
        </div>
    </article>
</div>

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