<?php

declare(strict_types=1);

require __DIR__ . '/includes/cart.php';
require __DIR__ . '/includes/analytics.php';

$cartCount = tap_cart_count();
$handle = trim((string) ($_GET['handle'] ?? ''));
$requestPath = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);

if ($handle === '' && preg_match('#^/products/([^/]+)/?$#', $requestPath, $matches)) {
    $handle = rawurldecode((string) $matches[1]);
}

if ($handle !== '' && str_starts_with($requestPath, '/product.php')) {
    $target = '/products/' . rawurlencode($handle);
    if ((string) ($_GET['added'] ?? '') === '1') {
        $target .= '?added=1';
    }
    header('Location: ' . $target, true, 301);
    exit;
}
$added = (string) ($_GET['added'] ?? '') === '1';
$pdo = tap_storefront_pdo();
$salesPaused = tap_sales_paused($pdo);
$product = $handle !== '' ? tap_storefront_product($pdo, $handle) : null;

if ($product === null) {
    http_response_code(404);
} else {
    tap_analytics_record($pdo, 'product_view', [
        'entity_type' => 'product',
        'entity_id' => (int) $product['id'],
        'entity_name' => (string) $product['title'],
        'metadata' => [
            'handle' => (string) $product['handle'],
            'kind' => (string) ($product['product_kind'] ?? ''),
        ],
    ]);
}

$variants = $product ? tap_storefront_variants($pdo, (int) $product['id']) : [];
$images = $product ? tap_storefront_images($pdo, (int) $product['id']) : [];
$mainImage = $images[0] ?? null;
$singleDefaultVariant = count($variants) === 1 && tap_storefront_variant_name($variants[0]) === 'Default';
$optionGroups = $product ? tap_storefront_option_groups($variants) : [];
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?php echo $product ? tap_e((string) $product['title']) : 'Product not found'; ?> - The Aroma Pixies</title>
  <link rel="stylesheet" href="/assets/storefront.css?v=0.9.15">
</head>
<body>
  <?php echo tap_storefront_header(isset($cartCount) ? $cartCount : null); ?>

  <main class="page">
    <?php if ($product === null): ?>
      <section class="empty-state">
        <h1>Product not found</h1>
        <p class="muted">This product is not currently available.</p>
        <a class="button" href="/shop.php">Back to shop</a>
      </section>
    <?php else: ?>
      <div class="product-layout">
        <section class="gallery" aria-label="Product images">
          <?php if ($mainImage && ($mainImage['source_url'] ?? '') !== ''): ?>
            <div class="image-main panel">
              <img id="main-product-image" src="<?php echo tap_e((string) $mainImage['source_url']); ?>" alt="<?php echo tap_e((string) ($mainImage['alt_text'] ?: $product['title'])); ?>">
            </div>
          <?php endif; ?>

          <?php if (count($images) > 1): ?>
            <div class="thumbs">
              <?php foreach ($images as $index => $image): ?>
                <?php if (($image['source_url'] ?? '') !== ''): ?>
                  <button class="thumb-button<?php echo $index === 0 ? ' is-active' : ''; ?>" type="button" data-image-url="<?php echo tap_e((string) $image['source_url']); ?>" data-image-alt="<?php echo tap_e((string) ($image['alt_text'] ?: $product['title'])); ?>">
                    <img src="<?php echo tap_e((string) $image['source_url']); ?>" alt="<?php echo tap_e((string) ($image['alt_text'] ?: $product['title'])); ?>">
                  </button>
                <?php endif; ?>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </section>

        <section class="product-summary">
          <a href="/shop.php">&larr; Back to shop</a>
          <?php if ($added && !$salesPaused): ?>
            <p class="notice ok">Added to basket.</p>
          <?php endif; ?>
          <h1><?php echo tap_e((string) $product['title']); ?></h1>
          <?php if ($salesPaused): ?>
            <p class="notice warn">The shop is not taking new orders at present. This page remains here for reference.</p>
          <?php endif; ?>
          <div class="price">
            <?php
            $prices = array_map('floatval', array_filter(array_column($variants, 'price'), static fn ($value): bool => $value !== null && $value !== ''));
            echo tap_e(tap_storefront_price_range($prices ? (string) min($prices) : null, $prices ? (string) max($prices) : null));
            ?>
          </div>

          <?php if ($variants && !$salesPaused): ?>
            <form class="panel" method="post" action="/add-to-cart.php">
              <input type="hidden" name="csrf_token" value="<?php echo tap_e(tap_cart_token()); ?>">
              <input type="hidden" name="handle" value="<?php echo tap_e((string) $product['handle']); ?>">
              <?php if ($singleDefaultVariant): ?>
                <?php $variant = $variants[0]; ?>
                <input type="hidden" name="variant_id" value="<?php echo tap_e((string) $variant['id']); ?>">
                <p class="small muted">SKU <?php echo tap_e((string) ($variant['sku'] ?? '')); ?> - <?php echo tap_e(tap_storefront_stock_label($product, $variant)); ?></p>
              <?php else: ?>
                <h2>Options</h2>
                <?php $defaultVariantId = tap_storefront_default_variant_id($variants); ?>
                <?php $defaultVariant = $variants[0] ?? []; ?>
                <input id="variant_id" type="hidden" name="variant_id" value="<?php echo tap_e((string) $defaultVariantId); ?>">
                <div class="variant-option-grid">
                  <?php $optionPosition = 0; ?>
                  <?php foreach ($optionGroups as $group): ?>
                    <?php $optionPosition++; ?>
                    <?php $valueKey = 'option' . (int) $group['index'] . '_value'; ?>
                    <label class="variant-select-label" for="variant_option_<?php echo tap_e((string) $group['index']); ?>">
                      <?php echo tap_e(tap_storefront_option_label($product, $group, $optionPosition)); ?>
                    </label>
                    <select
                      id="variant_option_<?php echo tap_e((string) $group['index']); ?>"
                      class="variant-select variant-option-select"
                      data-option-index="<?php echo tap_e((string) $group['index']); ?>"
                      required
                    >
                      <?php foreach ($group['values'] as $value): ?>
                        <option value="<?php echo tap_e((string) $value); ?>" <?php echo (string) ($defaultVariant[$valueKey] ?? '') === (string) $value ? 'selected' : ''; ?>>
                          <?php echo tap_e((string) $value); ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  <?php endforeach; ?>
                </div>
                <p id="variant-selected-summary" class="variant-selected-summary small muted"></p>
              <?php endif; ?>
              <div class="quantity-row">
                <label for="quantity">Quantity</label>
                <input id="quantity" type="number" name="quantity" value="1" min="1" max="99" step="1">
              </div>
              <button class="button" type="submit">Add to basket</button>
            </form>
          <?php endif; ?>

          <?php if (!$salesPaused): ?><a class="button secondary" href="/cart.php">View basket</a><?php endif; ?>
        </section>
      </div>

      <section class="panel description" style="margin-top: 24px;">
        <h2>Description</h2>
        <?php echo tap_storefront_safe_html((string) ($product['body_html'] ?? '')); ?>
      </section>
    <?php endif; ?>
  </main>

  <?php echo tap_storefront_footer(); ?>
  <script>
    const mainProductImage = document.getElementById('main-product-image');
    const thumbnailButtons = document.querySelectorAll('.thumb-button');
    const variantIdInput = document.getElementById('variant_id');
    const variantOptionSelects = document.querySelectorAll('.variant-option-select');
    const variantSelectedSummary = document.getElementById('variant-selected-summary');
    const addToBasketButton = document.querySelector('button[type="submit"]');
    const variants = <?php echo json_encode(array_map(static function (array $variant) use ($product): array {
        return [
            'id' => (int) $variant['id'],
            'option1' => (string) ($variant['option1_value'] ?? ''),
            'option2' => (string) ($variant['option2_value'] ?? ''),
            'option3' => (string) ($variant['option3_value'] ?? ''),
            'sku' => (string) ($variant['sku'] ?? ''),
            'price' => tap_storefront_money((string) $variant['price']),
            'stock' => tap_storefront_stock_label($product, $variant),
            'imageUrl' => (string) ($variant['variant_image_url'] ?? ''),
            'imageAlt' => (string) ($variant['variant_image_alt'] ?: $product['title']),
        ];
    }, $variants), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?>;

    thumbnailButtons.forEach((button) => {
      button.addEventListener('click', () => {
        if (!mainProductImage) {
          return;
        }

        mainProductImage.src = button.dataset.imageUrl || mainProductImage.src;
        mainProductImage.alt = button.dataset.imageAlt || mainProductImage.alt;
        thumbnailButtons.forEach((item) => item.classList.remove('is-active'));
        button.classList.add('is-active');
      });
    });

    const updateSelectedVariant = () => {
      if (!variantIdInput || !variantOptionSelects.length) {
        return;
      }

      const selectedOptions = {};
      variantOptionSelects.forEach((select) => {
        selectedOptions[`option${select.dataset.optionIndex}`] = select.value;
      });

      const selected = variants.find((variant) => (
        (!selectedOptions.option1 || variant.option1 === selectedOptions.option1)
        && (!selectedOptions.option2 || variant.option2 === selectedOptions.option2)
        && (!selectedOptions.option3 || variant.option3 === selectedOptions.option3)
      ));

      if (variantSelectedSummary) {
        if (selected) {
          const sku = selected.sku ? `SKU ${selected.sku} - ` : '';
          variantSelectedSummary.textContent = `${sku}${selected.stock || ''} - ${selected.price || ''}`;
        } else {
          variantSelectedSummary.textContent = 'That option combination is not available.';
        }
      }

      if (addToBasketButton) {
        addToBasketButton.disabled = !selected;
        addToBasketButton.classList.toggle('disabled', !selected);
      }

      if (!selected) {
        variantIdInput.value = '';
        return;
      }

      variantIdInput.value = selected.id;

      if (!mainProductImage || !selected.imageUrl) {
        return;
      }

      mainProductImage.src = selected.imageUrl;
      mainProductImage.alt = selected.imageAlt || mainProductImage.alt;
      thumbnailButtons.forEach((item) => item.classList.remove('is-active'));
    };

    if (variantOptionSelects.length) {
      variantOptionSelects.forEach((select) => select.addEventListener('change', updateSelectedVariant));
      updateSelectedVariant();
    }
  </script>
  <?php echo tap_analytics_consent_banner(); ?>
</body>
</html>
