<?php
require_once __DIR__ . '/../config.php';
$db = getDB();
$slug = trim($_GET['slug'] ?? '');
if (!$slug) {
  redirect(SITE_URL . '/pages/products.php');
}

$stmt = $db->prepare("SELECT p.*, c.name AS cat_name, c.slug AS cat_slug FROM products p LEFT JOIN categories c ON p.category_id=c.id WHERE p.slug=? AND p.status='active'");
$stmt->execute([$slug]);
$p = $stmt->fetch();
if (!$p) {
  redirect(SITE_URL . '/pages/products.php');
}

// Related
$related = $db->prepare("SELECT * FROM products WHERE category_id=? AND slug!=? AND status='active' LIMIT 3");
$related->execute([$p['category_id'], $slug]);
$related = $related->fetchAll();

// Handle inquiry
$form_msg = '';
$form_type = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['inquiry_form'])) {
  $name = trim($_POST['name'] ?? '');
  $phone = trim($_POST['phone'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $msg = trim($_POST['message'] ?? '');
  if ($name && $phone) {
    $stmt2 = $db->prepare("INSERT INTO inquiries (name,email,phone,product_id,message) VALUES (?,?,?,?,?)");
    $stmt2->execute([$name, $email, $phone, $p['id'], $msg]);
    $form_msg = '✅ Inquiry sent! We will contact you shortly.';
    $form_type = 'success';
  } else {
    $form_msg = '⚠ Name and phone are required.';
    $form_type = 'error';
  }
}

$page_title = h($p['name']) . ' | Balimeen Private Limited';
include __DIR__ . '/../includes/header.php';
?>

<div class="page-hero">
  <div class="container">
    <h1><?= h($p['name']) ?></h1>
    <p><?= h($p['short_desc']) ?></p>
    <div class="breadcrumb"><a href="<?= SITE_URL ?>">Home</a> → <a href="products.php">Products</a> →
      <?= h($p['name']) ?></div>
  </div>
</div>

<section class="section-pad">
  <div class="container">
    <div class="product-detail-grid">
      <!-- Image -->
      <div>
        <div class="product-img-main">
          <img src="<?= SITE_URL ?>/assets/images/<?= h($p['image']) ?>" alt="<?= h($p['name']) ?>">
        </div>
      </div>
      <!-- Details -->
      <div>
        <?php if ($p['cat_name']): ?>
          <div class="section-label"><?= h($p['cat_name']) ?></div>
        <?php endif; ?>
        <h2
          style="font-family:'Outfit',sans-serif;font-size:1.9rem;font-weight:800;color:var(--blue-dark);margin-bottom:12px;">
          <?= h($p['name']) ?></h2>
        <p style="color:var(--text-light);margin-bottom:20px;font-size:.95rem;"><?= h($p['description']) ?></p>
        <div
          style="font-size:1.5rem;font-weight:800;font-family:'Outfit',sans-serif;color:var(--blue-main);margin-bottom:24px;">
          ₹<?= number_format($p['price']) ?> <span style="font-size:.75rem;font-weight:500;color:var(--text-light);">per
            unit (factory price)</span>
        </div>

        <!-- Specs -->
        <div class="product-specs">
          <h4 style="font-weight:700;color:var(--blue-dark);margin-bottom:14px;">Product Specifications</h4>
          <?php
          $specs = [
            'Material' => $p['material'],
            'Finish' => $p['finish'],
            'Dimensions' => $p['dimensions'],
            'Basin Depth' => explode('×', $p['dimensions'])[2] ?? '-',
            'Weight' => $p['weight'],
            'Thickness' => $p['thickness'],
          ];
          foreach ($specs as $k => $v):
            if (!$v)
              continue; ?>
            <div class="spec-row"><span class="spec-key"><?= h($k) ?></span><span class="spec-val"><?= h($v) ?></span>
            </div>
          <?php endforeach; ?>
        </div>

        <!-- Cart & Actions -->
        <form method="POST" action="cart.php" style="margin-bottom:16px;">
          <input type="hidden" name="action" value="add">
          <input type="hidden" name="pid" value="<?= $p['id'] ?>">
          <div style="display:flex;align-items:center;gap:12px;margin-bottom:14px;flex-wrap:wrap;">
            <label style="font-size:.82rem;font-weight:600;color:var(--text-mid);">Quantity:</label>
            <div class="qty-control">
              <button type="button" class="qty-btn" onclick="changeQty(-1)">−</button>
              <input type="number" name="qty" id="qtyInput" value="1" min="1"
                style="width:52px;text-align:center;border:1.5px solid #e2e8f0;border-radius:7px;padding:6px;font-weight:700;font-size:.95rem;font-family:inherit;">
              <button type="button" class="qty-btn" onclick="changeQty(1)">+</button>
            </div>
          </div>
          <div style="display:flex;gap:12px;flex-wrap:wrap;">
            <button type="submit" class="btn btn-primary" style="flex:1;justify-content:center;">🛒 Add to Cart</button>
            <a href="cart.php" class="btn btn-outline" style="color:var(--blue-main);border-color:var(--blue-main);">🛒
              View Cart</a>
            <a href="tel:+917870626467" class="btn btn-gold">📞 Call</a>
          </div>
        </form>
      </div>
    </div>

    <!-- Inquiry Form -->
    <div id="product-inquiry" style="max-width:640px;margin:50px auto 0;">
      <div class="contact-form">
        <?php if ($form_msg): ?>
          <div class="alert alert-<?= $form_type ?>"><?= $form_msg ?></div>
        <?php endif; ?>
        <h3 style="font-family:'Outfit',sans-serif;font-weight:700;color:var(--blue-dark);margin-bottom:20px;">Inquire
          About: <?= h($p['name']) ?></h3>
        <form method="POST">
          <input type="hidden" name="inquiry_form" value="1">
          <div class="form-row">
            <div class="form-group"><label>Name *</label><input type="text" name="name" required
                placeholder="Your Name"></div>
            <div class="form-group"><label>Phone *</label><input type="tel" name="phone" required
                placeholder="+91 XXXXX XXXXX"></div>
          </div>
          <div class="form-group"><label>Email</label><input type="email" name="email" placeholder="your@email.com">
          </div>
          <div class="form-group"><label>Message / Quantity</label><textarea name="message"
              placeholder="How many units? Any customization?"></textarea></div>
          <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;">📨 Send
            Inquiry</button>
        </form>
      </div>
    </div>

    <!-- Related Products -->
    <?php if ($related): ?>
      <div style="margin-top:60px;">
        <h3
          style="font-family:'Outfit',sans-serif;font-size:1.4rem;font-weight:800;color:var(--blue-dark);margin-bottom:24px;">
          Related Products</h3>
        <div class="products-grid">
          <?php foreach ($related as $r): ?>
            <div class="product-card" onclick="window.location='product.php?slug=<?= h($r['slug']) ?>'">
              <div class="product-card-img">
                <img src="<?= SITE_URL ?>/assets/images/<?= h($r['image']) ?>" alt="<?= h($r['name']) ?>" loading="lazy">
              </div>
              <div class="product-card-body">
                <h3><?= h($r['name']) ?></h3>
                <p><?= h($r['short_desc']) ?></p>
                <div class="product-card-meta">
                  <div class="product-price">₹<?= number_format($r['price']) ?></div>
                  <a href="product.php?slug=<?= h($r['slug']) ?>" class="btn btn-primary btn-sm">View →</a>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>
</section>

<script>
  function changeQty(delta) {
    const inp = document.getElementById('qtyInput');
    const cur = parseInt(inp.value) || 1;
    inp.value = Math.max(1, cur + delta);
  }
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>