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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$db = getDBConnection();

$stmt = $db->prepare("SELECT p.*, c.name as category_name, v.store_name, v.store_slug, v.store_logo, v.description as vendor_desc, v.contact_phone as vendor_phone 
                    FROM products p 
                    JOIN categories c ON p.category_id = c.id 
                    LEFT JOIN vendors v ON p.vendor_id = v.id 
                    WHERE p.id = ? AND p.status = 'active'");
$stmt->execute([$id]);
$product = $stmt->fetch();

if (!$product) {
    header('Location: ' . SITE_URL . '/index.php');
    exit;
}

// Fetch Gallery Images
$imgStmt = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY sort_order ASC");
$imgStmt->execute([$id]);
$gallery = $imgStmt->fetchAll();

// Fetch Variants (Size/Color)
$varStmt = $db->prepare("SELECT * FROM product_variants WHERE product_id = ? AND stock > 0");
$varStmt->execute([$id]);
$variants = $varStmt->fetchAll();

// Fetch Related Products
$relStmt = $db->prepare("SELECT * FROM products WHERE category_id = ? AND id != ? AND status = 'active' LIMIT 4");
$relStmt->execute([$product['category_id'], $id]);
$related = $relStmt->fetchAll();

$pageTitle = sanitize($product['name']);
require_once __DIR__ . '/../includes/header.php';
?>

<nav aria-label="breadcrumb" class="my-3">
  <ol class="breadcrumb bg-light p-3 rounded-3 shadow-sm">
    <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none">หน้าหลัก</a></li>
    <li class="breadcrumb-item"><a href="index.php?category=<?php echo $product['category_id']; ?>" class="text-decoration-none"><?php echo sanitize($product['category_name']); ?></a></li>
    <li class="breadcrumb-item active" aria-current="page"><?php echo sanitize($product['name']); ?></li>
  </ol>
</nav>

<div class="row g-4 mb-5">
  <!-- Image Gallery Section -->
  <div class="col-md-6">
    <div class="card card-custom p-3 text-center">
      <img id="mainProductImg" src="<?php echo sanitize(formatImageUrl($product['main_image'])); ?>" onerror="this.onerror=null; this.src='<?php echo SITE_URL; ?>/assets/images/no-image.png';" class="img-fluid rounded" style="max-height: 450px; object-fit: contain;" alt="<?php echo sanitize($product['name']); ?>">
      
      <?php if (!empty($gallery)): ?>
        <div class="d-flex gap-2 mt-3 overflow-auto justify-content-center">
          <img src="<?php echo sanitize(formatImageUrl($product['main_image'])); ?>" onerror="this.onerror=null; this.src='<?php echo SITE_URL; ?>/assets/images/no-image.png';" class="img-thumbnail cursor-pointer" style="width: 70px; height: 70px; object-fit: cover;" onclick="document.getElementById('mainProductImg').src=this.src;">
          <?php foreach ($gallery as $g): ?>
            <img src="<?php echo sanitize(formatImageUrl($g['image_path'])); ?>" onerror="this.onerror=null; this.src='<?php echo SITE_URL; ?>/assets/images/no-image.png';" class="img-thumbnail cursor-pointer" style="width: 70px; height: 70px; object-fit: cover;" onclick="document.getElementById('mainProductImg').src=this.src;">
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Product Details Section -->
  <div class="col-md-6">
    <div class="card card-custom p-4 h-100 d-flex flex-column justify-content-between">
      <div>
        <div class="d-flex align-items-center justify-content-between mb-2">
          <span class="badge bg-secondary badge-tag"><?php echo sanitize($product['category_name']); ?></span>
          <?php if (!empty($product['store_name'])): ?>
            <a href="shop.php?slug=<?php echo htmlspecialchars($product['store_slug']); ?>" class="text-decoration-none">
              <span class="badge bg-light text-primary border px-3 py-2 rounded-pill">
                🏪 จำหน่ายโดย: <strong><?php echo htmlspecialchars($product['store_name']); ?></strong> ❯
              </span>
            </a>
          <?php endif; ?>
        </div>

        <h2 class="fw-bold mb-2"><?php echo sanitize($product['name']); ?></h2>
        
        <div class="mb-3">
          <span class="price-current fs-2">฿<?php echo number_format($product['price'], 2); ?></span>
          <?php if ($product['normal_price'] > $product['price']): ?>
            <span class="price-strike fs-5">฿<?php echo number_format($product['normal_price'], 2); ?></span>
            <span class="badge bg-danger ms-2">ลดราคาพิเศษ</span>
          <?php endif; ?>
        </div>

        <p class="text-muted"><?php echo nl2br(sanitize($product['description'])); ?></p>
        <hr>

        <!-- Variants Selector (Size / Color) -->
        <?php
        // 1. รวบรวมข้อมูลไซส์ (Sizes)
        $allSizes = [];
        if (!empty($variants)) {
            $allSizes = array_unique(array_filter(array_column($variants, 'size')));
        }
        if (empty($allSizes) && !empty($product['sizes'])) {
            $allSizes = array_map('trim', explode(',', $product['sizes']));
            $allSizes = array_filter($allSizes);
        }
        $allSizes = array_values($allSizes);
        $firstSize = !empty($allSizes) ? $allSizes[0] : 'Free Size';

        // 2. รวบรวมข้อมูลสี (Colors)
        $allColors = [];
        if (!empty($variants)) {
            $allColors = array_unique(array_filter(array_column($variants, 'color')));
        }
        if (empty($allColors) && !empty($product['colors'])) {
            $allColors = array_map('trim', explode(',', $product['colors']));
            $allColors = array_filter($allColors);
        }
        ?>

        <!-- แสดงตัวเลือกไซส์ (ถ้ามี) -->
        <?php if (!empty($allSizes)): ?>
          <div class="mb-3">
            <label class="form-label fw-bold mb-2">📏 เลือกไซส์ (Size):</label>
            <div class="d-flex flex-wrap gap-2" id="sizeOptions">
              <?php foreach ($allSizes as $idx => $sz): ?>
                <button type="button" class="btn-size <?php echo $idx === 0 ? 'active' : ''; ?>" data-size="<?php echo sanitize($sz); ?>" onclick="selectSize(this)">
                  <?php echo sanitize($sz); ?>
                </button>
              <?php endforeach; ?>
            </div>
          </div>
        <?php endif; ?>

        <!-- แสดงตัวเลือกสี (ถ้ามี) -->
        <?php if (!empty($allColors)): ?>
          <div class="mb-4">
            <label class="form-label fw-bold">🎨 เลือกสี (Color):</label>
            <select id="colorOption" class="form-select rounded-3" style="max-width: 220px;">
              <?php foreach ($allColors as $cl): ?>
                <option value="<?php echo sanitize($cl); ?>"><?php echo sanitize($cl); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        <?php endif; ?>
      </div>

      <div>
        <button type="button" onclick="addSelectedToCart(<?php echo $product['id']; ?>)" class="btn btn-primary-custom w-100 py-3 fs-5 rounded-pill shadow-sm">
          🛒 หยิบใส่ตะกร้าสินค้า
        </button>
        <div class="mt-3 small text-muted text-center">
          🚚 จัดส่งด่วนภายใน 1-3 วันทำการ | 📦 มีบริการเก็บเงินปลายทาง (COD)
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Related Products -->
<?php if (!empty($related)): ?>
  <div class="mt-5">
    <h4 class="fw-bold mb-3">👕 สินค้าที่เกี่ยวข้อง</h4>
    <div class="row g-3">
      <?php foreach ($related as $rel): ?>
        <div class="col-6 col-md-3">
          <div class="card card-custom h-100 p-2">
            <a href="product_detail.php?id=<?php echo $rel['id']; ?>">
              <img src="<?php echo sanitize(formatImageUrl($rel['main_image'])); ?>" class="card-img-top rounded" style="height: 180px; object-fit: cover;">
            </a>
            <div class="card-body p-2">
              <h6 class="fw-bold mb-1 small text-truncate"><?php echo sanitize($rel['name']); ?></h6>
              <div class="price-current fs-6">฿<?php echo number_format($rel['price'], 2); ?></div>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
<?php endif; ?>

<script>
let selectedSize = '<?php echo sanitize($firstSize); ?>';
function selectSize(btn) {
    document.querySelectorAll('.btn-size').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    selectedSize = btn.getAttribute('data-size');
}

function addSelectedToCart(productId) {
    const colorEl = document.getElementById('colorOption');
    const color = colorEl ? colorEl.value : 'Default';
    addToCart(productId, selectedSize || 'Free Size', color);
}
</script>

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