<?php
require_once 'config/config.php';
require_once 'includes/functions.php';
startSecureSession();

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

$product = Database::fetchOne(
    "SELECT p.*, c.name as category_name, c.slug as cat_slug
     FROM products p LEFT JOIN categories c ON p.category_id=c.id
     WHERE p.slug=? AND p.is_active=1", [$slug]
);
if (!$product) { http_response_code(404); include '404.php'; exit; }

// Increment views
Database::execute("UPDATE products SET views=views+1 WHERE id=?", [$product['id']]);

// Related products
$related = Database::fetchAll(
    "SELECT p.*, c.name as cat FROM products p LEFT JOIN categories c ON p.category_id=c.id
     WHERE p.category_id=? AND p.id!=? AND p.is_active=1 LIMIT 4",
    [$product['category_id'], $product['id']]
);

// Gallery images
$gallery = $product['gallery'] ? json_decode($product['gallery'], true) : [];

$pageTitle = $product['name'] . ' | ' . ($product['category_name'] ?? 'Industrial Equipment');
$metaDesc = e(substr(strip_tags($product['description'] ?? $product['short_description'] ?? $product['name']), 0, 160));
$pageKeywords = e($product['name']) . ", " . e($product['category_name'] ?? '') . ", " . e($product['brand'] ?? '') . ", API 6A, API 6D, Industrial Pakistan";

// Breadcrumb Schema
$breadcrumbSchema = [
  "@context" => "https://schema.org",
  "@type" => "BreadcrumbList",
  "itemListElement" => [
    ["@type" => "ListItem", "position" => 1, "name" => "Home", "item" => SITE_URL],
    ["@type" => "ListItem", "position" => 2, "name" => "Products", "item" => SITE_URL . "/shop.php"]
  ]
];
if ($product['cat_slug']) {
  $breadcrumbSchema['itemListElement'][] = ["@type" => "ListItem", "position" => 3, "name" => $product['category_name'], "item" => SITE_URL . "/shop.php?category=" . $product['cat_slug']];
}

// Product Schema
$productSchema = [
  "@context" => "https://schema.org",
  "@type" => "Product",
  "name" => $product['name'],
  "description" => $metaDesc,
  "image" => SITE_URL . 'uploads/' . $product['image'],
  "sku" => $product['sku'] ?? '',
  "brand" => [
    "@type" => "Brand",
    "name" => $product['brand'] ?: 'Rig N Dig'
  ],
  "offers" => [
    "@type" => "Offer",
    "url" => SITE_URL . $_SERVER['REQUEST_URI'],
    "priceCurrency" => "PKR",
    "availability" => $product['stock_status'] === 'in_stock' ? "https://schema.org/InStock" : "https://schema.org/OutOfStock",
    "itemCondition" => "https://schema.org/NewCondition",
    "price" => "0.00",
    "priceSpecification" => [
      "@type" => "PriceSpecification",
      "price" => "0.00",
      "priceCurrency" => "PKR",
      "valueAddedTaxIncluded" => "true"
    ]
  ]
];

include 'includes/header.php';
?>
<script type="application/ld+json"><?= json_encode($breadcrumbSchema) ?></script>
<script type="application/ld+json"><?= json_encode($productSchema) ?></script>

<div class="max-w-7xl mx-auto px-4 py-10">
  <!-- Breadcrumb -->
  <nav class="text-xs text-gray-400 mb-8">
    <a href="/" class="hover:text-orange-500">Home</a> /
    <a href="/shop.php" class="hover:text-orange-500">Products</a> /
    <?php if ($product['cat_slug']): ?>
    <a href="/shop.php?category=<?= e($product['cat_slug']) ?>" class="hover:text-orange-500"><?= e($product['category_name'] ?? '') ?></a> /
    <?php endif; ?>
    <span class="text-gray-200"><?= e($product['name']) ?></span>
  </nav>

  <div class="grid grid-cols-1 lg:grid-cols-2 gap-10 mb-16">
    <!-- Image Gallery -->
    <div>
      <div class="card-dark overflow-hidden mb-3">
        <?php if ($product['image']): ?>
        <img id="main-img" src="/uploads/<?= e($product['image']) ?>" class="w-full h-80 object-cover" alt="<?= e($product['name']) ?>"
             onerror="this.onerror=null;this.style.display='none';this.nextElementSibling.style.display='flex'">
        <div class="h-80 bg-navy-600 items-center justify-center text-7xl" style="display:none">⚙️</div>
        <?php else: ?>
        <div class="h-80 bg-navy-600 flex items-center justify-center text-7xl">⚙️</div>
        <?php endif; ?>
      </div>
      <?php if (!empty($gallery)): ?>
      <div class="flex gap-2 overflow-x-auto">
        <?php if ($product['image']): ?>
        <img src="/uploads/<?= e($product['image']) ?>" class="w-16 h-16 object-cover rounded-lg cursor-pointer border-2 border-orange-600" onclick="document.getElementById('main-img').src=this.src">
        <?php endif; ?>
        <?php foreach ($gallery as $img): ?>
        <img src="/uploads/<?= e($img) ?>" class="w-16 h-16 object-cover rounded-lg cursor-pointer border-2 border-transparent hover:border-orange-500" onclick="document.getElementById('main-img').src=this.src">
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

    <!-- Product Info -->
    <div>
      <div class="text-xs text-orange-500 mb-2"><?= e($product['category_name'] ?? '') ?></div>
      <h1 class="text-2xl font-bold mb-2"><?= e($product['name']) ?></h1>
      <div class="flex flex-wrap gap-3 mb-4 text-xs text-gray-400">
        <?php if ($product['sku']): ?><span>SKU: <strong class="text-white"><?= e($product['sku']) ?></strong></span><?php endif; ?>
        <?php if ($product['brand']): ?><span>Brand: <strong class="text-white"><?= e($product['brand']) ?></strong></span><?php endif; ?>
        <?php if ($product['origin']): ?><span>Origin: <strong class="text-white"><?= e($product['origin']) ?></strong></span><?php endif; ?>
      </div>
      <?= statusBadge($product['stock_status']) ?>
      <?php if ($product['standards']): ?>
      <div class="mt-3 mb-4 badge badge-orange">📋 <?= e($product['standards']) ?></div>
      <?php endif; ?>
      <?php if ($product['short_description']): ?>
      <p class="text-gray-300 text-sm leading-relaxed my-4"><?= e($product['short_description']) ?></p>
      <?php endif; ?>

      <!-- Quote Actions -->
      <div class="card-dark p-5 mb-5">
        <div class="text-sm text-orange-400 font-semibold mb-2">Price: Available on Request</div>
        <p class="text-xs text-gray-400 mb-4">All pricing is provided via formal quotation. Add to your RFQ cart and we'll send a competitive quote within 24-48 hours.</p>
        <div class="flex gap-3">
          <button onclick="addToQuote(<?= $product['id'] ?>, this)" class="btn-primary flex-1 py-3">📋 Add to RFQ Cart</button>
          <a href="/quote-cart.php" class="btn-outline py-3 px-4">View Cart</a>
        </div>
      </div>

      <!-- Quick Contact -->
      <div class="flex flex-wrap gap-3 text-sm mb-3">
        <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', setting('whatsapp')) ?>?text=I%20need%20info%20about%20<?= urlencode($product['name']) ?>" target="_blank" class="flex items-center gap-1.5 text-green-400 hover:text-green-300">💬 WhatsApp</a>
        <a href="tel:<?= e(setting('phone')) ?>" class="flex items-center gap-1.5 text-gray-300 hover:text-white">📞 Call Us</a>
        <?php $dsFile = $product['datasheet'] ?? $product['document'] ?? null; if ($dsFile): ?>
        <a href="/uploads/<?= e($dsFile) ?>" target="_blank" class="flex items-center gap-1.5 text-blue-400 hover:text-blue-300">📄 Datasheet</a>
        <?php endif; ?>
      </div>
      <!-- Wishlist + Compare -->
      <div class="flex gap-3 text-sm">
        <?php if (isCustomerLoggedIn()):
          $custId = getCurrentCustomer()['id'] ?? 0;
          $inWishlist = $custId ? (bool)Database::fetchOne("SELECT id FROM wishlist WHERE customer_id=? AND product_id=?", [$custId, $product['id']]) : false;
        ?>
        <button onclick="toggleWishlist(<?= $product['id'] ?>, this)"
          class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border <?= $inWishlist ? 'border-orange-600 text-orange-400 bg-orange-600/10' : 'border-navy-500 text-gray-400 hover:border-orange-500 hover:text-orange-400' ?> transition-colors"
          id="wishlist-btn-<?= $product['id'] ?>">
          <?= $inWishlist ? '❤️ Saved' : '🤍 Save' ?>
        </button>
        <?php endif; ?>
        <button onclick="addToCompare(<?= $product['id'] ?>, '<?= addslashes(e($product['name'])) ?>')"
          class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-navy-500 text-gray-400 hover:border-blue-500 hover:text-blue-400 transition-colors">
          ⚖️ Compare
        </button>
      </div>
    </div>
  </div>

  <!-- Tabs: Description / Specs -->
  <div class="mb-16">
    <div class="flex gap-1 border-b border-navy-500 mb-6">
      <?php foreach (['description'=>'Description','specifications'=>'Specifications'] as $tab=>$label): if (!$product[$tab]) continue; ?>
      <button onclick="showTab('<?= $tab ?>')" id="tab-<?= $tab ?>"
              class="tab-btn px-5 py-2.5 text-sm font-medium -mb-px border-b-2 border-transparent hover:text-orange-400">
        <?= $label ?>
      </button>
      <?php endforeach; ?>
    </div>
    <?php if ($product['description']): ?>
    <div id="panel-description" class="tab-panel prose-sm text-gray-300 leading-relaxed">
      <?= nl2br(e($product['description'])) ?>
    </div>
    <?php endif; ?>
    <?php if ($product['specifications']): ?>
    <div id="panel-specifications" class="tab-panel hidden">
      <?php
      $specs = json_decode($product['specifications'], true);
      if ($specs && is_array($specs)): ?>
      <table class="data-table">
        <tbody>
        <?php foreach ($specs as $k=>$v): ?>
        <tr><td class="text-gray-400 text-sm w-1/3"><?= e($k) ?></td><td class="text-sm font-medium"><?= e($v) ?></td></tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      <?php else: ?>
      <div class="text-gray-300 text-sm"><?= nl2br(e($product['specifications'])) ?></div>
      <?php endif; ?>
    </div>
    <?php endif; ?>
  </div>

  <!-- Related Products -->
  <?php if (!empty($related)): ?>
  <div>
    <h2 class="text-xl font-bold mb-6">Related Products</h2>
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
      <?php foreach ($related as $r): ?>
      <a href="/product-detail.php?slug=<?= e($r['slug']) ?>" class="product-card">
        <?php if ($r['image']): ?>
        <img src="/uploads/<?= e($r['image']) ?>" class="w-full h-36 object-cover">
        <?php else: ?>
        <div class="h-36 bg-navy-600 flex items-center justify-center text-3xl">⚙️</div>
        <?php endif; ?>
        <div class="p-3">
          <div class="text-xs text-orange-500 mb-0.5"><?= e($r['cat'] ?? '') ?></div>
          <div class="text-sm font-medium line-clamp-2 hover:text-orange-400"><?= e($r['name']) ?></div>
        </div>
      </a>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>
</div>

<script>
function showTab(id) {
  document.querySelectorAll('.tab-panel').forEach(p => p.classList.add('hidden'));
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('border-orange-600','text-orange-500'));
  document.getElementById('panel-'+id).classList.remove('hidden');
  document.getElementById('tab-'+id).classList.add('border-orange-600','text-orange-500');
}
// Activate first tab
const firstTab = document.querySelector('.tab-btn');
if (firstTab) firstTab.click();
</script>

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