<?php
require __DIR__ . '/includes/site.php';

$id = (int)($_GET['id'] ?? 0);
$st = $pdo->prepare(
    'SELECT p.*, c.name AS cat_name, c.slug AS cat_slug
       FROM products p JOIN categories c ON c.id = p.category_id
      WHERE p.id = ? AND p.is_active = 1'
);
$st->execute([$id]);
$p = $st->fetch();
if (!$p) {
    http_response_code(404);
    site_header('Not found');
    echo '<p class="empty">This product is not available. <a href="' . BASE . '/category.php">See all products</a></p>';
    site_footer();
    exit;
}

try {
    $st = $pdo->prepare('SELECT file, color FROM product_images WHERE product_id = ? ORDER BY sort_order, id');
    $st->execute([$id]);
    $imgRows = $st->fetchAll();
} catch (Throwable $e) {   // color column not added yet
    $st = $pdo->prepare('SELECT file, \'\' AS color FROM product_images WHERE product_id = ? ORDER BY sort_order, id');
    $st->execute([$id]);
    $imgRows = $st->fetchAll();
}
$images = array_column($imgRows, 'file');
$imgData = array_map(fn($r) => ['url' => img_url($r['file']), 'color' => (string)$r['color']], $imgRows);

$st = $pdo->prepare('SELECT id, size, color, GREATEST(stock - reserved, 0) AS avail FROM product_variants WHERE product_id = ?');
$st->execute([$id]);
$variants = $st->fetchAll();
$rank = array_flip(size_sort(array_values(array_unique(array_column($variants, 'size')))));
usort($variants, function ($a, $b) use ($rank) {
    $c = strcmp($a['color'], $b['color']);
    return $c !== 0 ? $c : ($rank[$a['size']] <=> $rank[$b['size']]);
});
$vdata = array_map(fn($v) => [
    'id' => (int)$v['id'], 'size' => $v['size'], 'color' => $v['color'], 'avail' => (int)$v['avail'],
], $variants);
$totalAvail = array_sum(array_column($vdata, 'avail'));

$d = discount_pct((float)$p['mrp'], (float)$p['price']);
// More like this: same category first (closest price first, in stock only), then fill from other categories
$inStock = 'EXISTS (SELECT 1 FROM product_variants rv WHERE rv.product_id = p.id AND rv.stock - rv.reserved > 0)';
$related = fetch_cards($pdo, "p.category_id = ? AND p.id <> ? AND $inStock", [$p['category_id'], $id],
    'ABS(p.price - ' . (float)$p['price'] . ') ASC, p.id DESC', 8);
if (count($related) < 8) {
    $skip = array_merge([$id], array_map(fn($r) => (int)$r['id'], $related));
    $ph = implode(',', array_fill(0, count($skip), '?'));
    $more = fetch_cards($pdo, "p.id NOT IN ($ph) AND $inStock", $skip, 'p.id DESC', 8 - count($related));
    $related = array_merge($related, $more);
}
$maxItems = (int)setting('max_trial_items', '5');
$inBag = array_keys(bag());

site_header($p['name'], mb_substr(strip_tags((string)$p['description']), 0, 150), $p['cat_slug']);
?>
<p class="crumbs"><a href="<?= BASE ?>/index.php">Home</a> / <a href="<?= BASE ?>/category.php?c=<?= e($p['cat_slug']) ?>"><?= e($p['cat_name']) ?></a></p>

<div class="pdp">
  <div class="gallery">
    <div class="gmain"><img id="gmain" src="<?= e(img_url($images[0] ?? null)) ?>" alt="<?= e($p['name']) ?>"></div>
    <?php if (count($images) > 1): ?>
    <div class="gthumbs">
      <?php foreach ($images as $i => $f): ?>
        <img src="<?= e(img_url($f)) ?>" alt="" data-full="<?= e(img_url($f)) ?>" class="<?= $i === 0 ? 'on' : '' ?>">
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>

  <div class="info">
    <?php if ($p['brand']): ?><p class="brand"><?= e($p['brand']) ?></p><?php endif; ?>
    <h1><?= e($p['name']) ?></h1>
    <div class="price">
      <b><?= money($p['price']) ?></b>
      <?php if ($d): ?><s><?= money($p['mrp']) ?></s><span class="pill"><?= $d ?>% off</span><?php endif; ?>
    </div>
    <p class="hint">Inclusive of all taxes</p>

    <?php if ($totalAvail <= 0): ?>
      <div class="soldout">Sold out</div>
    <?php else: ?>
    <form method="post" action="<?= BASE ?>/cart.php" id="addForm">
      <?= csrf_field() ?>
      <input type="hidden" name="action" value="add">
      <input type="hidden" name="variant_id" id="variant_id" value="">
      <div id="colorBlock" class="opt" hidden><label>Color: <b id="colorName"></b></label><div id="colors" class="chips"></div></div>
      <div class="opt"><label>Size: <b id="sizeName">Select a size</b></label><div id="sizes" class="chips"></div></div>
      <p id="leftMsg" class="left" hidden></p>
      <button class="btn big" id="addBtn" disabled>Select a size</button>
    </form>
    <p class="hint"><?= $maxItems > 0 ? 'Add up to ' . $maxItems . ' items' : 'Add as many items as you like' ?> to your Trial Bag. We bring them home, you pay only for what you keep.</p>
    <?php endif; ?>

    <?php if (trim((string)$p['description']) !== ''): ?>
    <div class="desc"><h3>Details</h3><p><?= nl2br(e($p['description'])) ?></p></div>
    <?php endif; ?>
  </div>
</div>

<?php if ($related): ?>
<div class="sec-row"><h2 class="sec">More products like this</h2>
  <a class="hint" style="text-decoration:underline" href="<?= BASE ?>/category.php?c=<?= e($p['cat_slug']) ?>">View all <?= e($p['cat_name']) ?></a></div>
<div class="pgrid"><?php foreach ($related as $r) echo card_html($r); ?></div>
<?php endif; ?>

<script>window.PDATA = <?= json_encode(['variants' => $vdata, 'images' => $imgData, 'inBag' => array_map('intval', $inBag)], JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;</script>
<?php site_footer();
