<?php
declare(strict_types=1);

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='index-2.php';</script></body></html>";
    exit;
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid product id.');window.location.href='index-2.php';</script></body></html>";
    exit;
}

$stmt = $pdo->prepare('SELECT * FROM products WHERE id = :id');
$stmt->execute([':id' => $id]);
$p = $stmt->fetch();
if (!$p) {
    http_response_code(404);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Product not found.');window.location.href='index-2.php';</script></body></html>";
    exit;
}

$images = [];
for ($i = 1; $i <= 5; $i++) {
    $k = 'image' . $i;
    if (!empty($p[$k])) { $images[] = (string)$p[$k]; }
}
if (!$images) { $images[] = 'assets/img/listing/listing-1-1.png'; }

?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
   <meta charset="utf-8">
   <meta http-equiv="x-ua-compatible" content="ie=edge">
   <title><?php echo htmlspecialchars($p['product_title'], ENT_QUOTES); ?> - ListBnb</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="shortcut icon" type="image/x-icon" href="assets/img/logo/favicon.png">
   <link rel="stylesheet" href="assets/css/bootstrap.css">
   <link rel="stylesheet" href="assets/css/animate.css">
   <link rel="stylesheet" href="assets/css/swiper-bundle.css">
   <link rel="stylesheet" href="assets/css/slick.css">
   <link rel="stylesheet" href="assets/css/magnific-popup.css">
   <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
   <link rel="stylesheet" href="assets/css/spacing.css">
   <link rel="stylesheet" href="assets/css/custom-animation.css">
   <link rel="stylesheet" href="assets/css/main.css">
   <style>
     .pd-wrap{padding:60px 0}
     .pd-grid{display:grid;grid-template-columns:1.2fr 1fr;gap:30px}
     .thumbs{display:flex;flex-direction:column;gap:10px;width:90px}
    .thumbs img{width:90px;height:90px;object-fit:cover;border-radius:8px;border:1px solid #e5e7eb;cursor:pointer;background:#fff}
    .viewer{background:#fff;border:1px solid #e5e7eb;border-radius:16px;display:flex;gap:20px;padding:20px}
    .main-img{flex:1;min-height:420px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;display:flex;align-items:center;justify-content:center}
     .main-img img{width:100%;height:100%;object-fit:contain;border-radius:12px}
    .pd-title{font-size:26px;font-weight:700;color:#1f2937;margin:0 0 6px}
    .pd-price{font-size:20px;font-weight:700;color:#00e676;margin-bottom:16px}
    .pd-meta{color:#6b7280;font-size:14px;margin-bottom:14px}
   .pd-box{background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:16px;margin-bottom:24px}
     .pd-actions{margin-top:20px}
     .pd-actions .tp-btn-border-sm{margin-right:10px}
     .pd-desc{color:#374151}
    .pd-size-table{width:100%;border-collapse:separate;border-spacing:0;background:#fff;border:1px solid #e5e7eb;border-radius:12px;overflow:hidden}
    .pd-size-table th,.pd-size-table td{padding:12px 14px;border-bottom:1px solid #e5e7eb;color:#374151}
    .pd-size-table thead th{background:#f8fafc;color:#1f2937;font-weight:600}
     .pd-size-table tbody tr:last-child td{border-bottom:none}
    .pd-size-table td:first-child{color:#6b7280;width:28%}
     .pd-generic-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
    .pd-generic-grid div{display:flex;align-items:center;justify-content:space-between;background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:10px 12px}
    .pd-generic-grid label{color:#6b7280;margin-right:8px}
    .pd-generic-grid span{color:#374151}
   </style>
</head>
<body>
   <header class="tp-header-height">
      <div id="header-sticky" class="tp-header-area tp-header-inner-style">
         <div class="container">
            <div class="row align-items-center">
               <div class="col-xl-3 col-lg-6 col-md-6 col-6">
                  <div class="tp-header-logo">
                     <a href="index-2.php" class="brand-text">ReWear</a>
                  </div>
               </div>
               <div class="col-xl-6 col-lg-4 d-none d-xl-block">
                  <div class="tp-header-menu">
                     <nav class="tp-main-menu-content">
                        <ul>
                           <li class="has-dropdown"><a href="index-2.php">Home</a></li>
                           <li class="has-dropdown">
                              <a href="#">Categories</a>
                              <ul class="submenu tp-submenu">
                                 <li><a href="category.php?category=Summer%20Clothing">Summer Clothing</a></li>
                                 <li><a href="category.php?category=Winter%20Clothing">Winter Clothing</a></li>
                                 <li><a href="category.php?category=Party%20%26%20Formal%20Wear">Party & Formal Wear</a></li>
                                 <li><a href="category.php?category=Active%20Wear%20%2F%20Gym%20Wear">Active Wear / Gym Wear</a></li>
                                 <li><a href="category.php?category=Nightwear%20%2F%20Sleepwear">Nightwear / Sleepwear</a></li>
                                 <li><a href="category.php?category=Modest%20Wear">Modest Wear</a></li>
                                 <li><a href="category.php?category=Casual%20Wear">Casual Wear</a></li>
                              </ul>
                           </li>
                           <li><a href="about-us.html">About Us</a></li>
                           <li class="has-dropdown"><a href="#site-contact">Contact</a></li>
                        </ul>
                     </nav>
                  </div>
               </div>
               <div class="col-xl-3 col-lg-6 col-md-6 col-6">
                  <div class="tp-header-right d-flex align-items-center justify-content-end">
                     <div class="tp-header-btn d-none d-xl-block">
                        <a class="tp-btn-theme" href="listing-ads.html"><span>Post Your Ad <i class="fa-sharp fa-regular fa-arrow-right-long"></i></span></a>
                     </div>
                     <div class="tp-header-bar d-xl-none">
                        <button class="tp-menu-bar"><i class="fa-sharp fa-regular fa-bars-staggered"></i></button>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </header>

   <main>
     <section class="pd-wrap">
       <div class="container">
         <div class="pd-grid">
           <div>
             <div class="viewer">
               <div class="thumbs">
                 <?php foreach ($images as $i => $src): ?>
                   <img data-idx="<?php echo (int)$i; ?>" src="<?php echo htmlspecialchars($src, ENT_QUOTES); ?>" alt="thumb">
                 <?php endforeach; ?>
               </div>
               <div class="main-img">
                 <img id="mainImage" src="<?php echo htmlspecialchars($images[0], ENT_QUOTES); ?>" alt="main">
               </div>
             </div>
           </div>
           <div>
             <div class="pd-box">
               <h1 class="pd-title"><?php echo htmlspecialchars($p['product_title'], ENT_QUOTES); ?></h1>
               <div class="pd-meta">#<?php echo (int)$p['id']; ?> • <?php echo htmlspecialchars($p['product_type'], ENT_QUOTES); ?> • <?php echo htmlspecialchars($p['condition'], ENT_QUOTES); ?></div>
               <div class="pd-price">$<?php echo number_format((float)$p['price'], 2); ?></div>
               <div class="pd-meta">Category: <?php echo htmlspecialchars($p['category'], ENT_QUOTES); ?><?php if(!empty($p['brand'])): ?> • Brand: <?php echo htmlspecialchars($p['brand'], ENT_QUOTES); ?><?php endif; ?></div>
               <div class="pd-meta">Size: <?php echo htmlspecialchars($p['product_size'], ENT_QUOTES); ?></div>
             </div>
             <div class="pd-box pd-desc">
               <h5 class="mb-10">Description</h5>
               <p class="mb-0"><?php echo nl2br(htmlspecialchars($p['description'], ENT_QUOTES)); ?></p>
             </div>
            <?php
              $hasGeneric = !empty($p['chart_chest']) || !empty($p['chart_waist']) || !empty($p['chart_hip']) || !empty($p['chart_shoulder']) || !empty($p['chart_sleeve']) || !empty($p['chart_length']) || !empty($p['chart_shirt_length']) || !empty($p['chart_trouser_length']);
              $sizes = ['XS' => 'xs','Small' => 's','Medium' => 'm','Large' => 'l','XL' => 'xl'];
              $rows = [
                'Chest' => 'chest',
                'Waist' => 'waist',
                'Hip' => 'hip',
                'Length' => 'length',
                'Shoulder' => 'shoulder',
                'Sleeve Length' => 'sleeve',
                'Shirt/Jacket Length' => 'shirt_length',
                'Trouser/Inseam' => 'trouser_length',
              ];
              $hasSizeData = false;
              foreach ($sizes as $label => $code) {
                foreach ($rows as $rKey) {
                  $k = 'size_' . $code . '_' . $rKey;
                  if (!empty($p[$k])) { $hasSizeData = true; break 2; }
                }
              }
              if ($hasGeneric || $hasSizeData):
            ?>
            <div class="pd-box">
              <h5 class="mb-10">Size Chart</h5>
              <p class="text-muted" style="font-size:12px;margin-bottom:14px">Measurements are provided by the seller. Use as a guide.</p>
              <?php if ($hasSizeData): ?>
              <div class="pd-size-table-wrap">
                <table class="pd-size-table">
                  <thead>
                    <tr>
                      <th>Measurement</th>
                      <th>XS</th>
                      <th>S</th>
                      <th>M</th>
                      <th>L</th>
                      <th>XL</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php foreach ($rows as $rowLabel => $rKey): ?>
                      <tr>
                        <td><?php echo htmlspecialchars($rowLabel, ENT_QUOTES); ?></td>
                        <?php foreach (['xs','s','m','l','xl'] as $code): $k = 'size_' . $code . '_' . $rKey; ?>
                          <td><?php echo !empty($p[$k]) ? htmlspecialchars($p[$k], ENT_QUOTES) : '-'; ?></td>
                        <?php endforeach; ?>
                      </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              </div>
              <?php endif; ?>
              <?php if ($hasGeneric): ?>
              <div class="pd-generic-chart mt-15">
                <div class="pd-generic-grid">
                  <?php if (!empty($p['chart_chest'])): ?><div><label>Chest</label><span><?php echo htmlspecialchars($p['chart_chest'], ENT_QUOTES); ?></span></div><?php endif; ?>
                  <?php if (!empty($p['chart_waist'])): ?><div><label>Waist</label><span><?php echo htmlspecialchars($p['chart_waist'], ENT_QUOTES); ?></span></div><?php endif; ?>
                  <?php if (!empty($p['chart_hip'])): ?><div><label>Hip</label><span><?php echo htmlspecialchars($p['chart_hip'], ENT_QUOTES); ?></span></div><?php endif; ?>
                  <?php if (!empty($p['chart_shoulder'])): ?><div><label>Shoulder</label><span><?php echo htmlspecialchars($p['chart_shoulder'], ENT_QUOTES); ?></span></div><?php endif; ?>
                  <?php if (!empty($p['chart_sleeve'])): ?><div><label>Sleeve</label><span><?php echo htmlspecialchars($p['chart_sleeve'], ENT_QUOTES); ?></span></div><?php endif; ?>
                  <?php if (!empty($p['chart_length'])): ?><div><label>Length</label><span><?php echo htmlspecialchars($p['chart_length'], ENT_QUOTES); ?></span></div><?php endif; ?>
                  <?php if (!empty($p['chart_shirt_length'])): ?><div><label>Shirt/Jacket Length</label><span><?php echo htmlspecialchars($p['chart_shirt_length'], ENT_QUOTES); ?></span></div><?php endif; ?>
                  <?php if (!empty($p['chart_trouser_length'])): ?><div><label>Trouser/Inseam</label><span><?php echo htmlspecialchars($p['chart_trouser_length'], ENT_QUOTES); ?></span></div><?php endif; ?>
                </div>
              </div>
              <?php endif; ?>
            </div>
            <?php endif; ?>
            <div class="pd-actions">
              <a class="tp-btn-border-sm pd-addcart" href="javascript:void(0)"><span><i class="fa-regular fa-cart-shopping"></i> Add to Cart</span></a>
              <a class="tp-btn-border-sm pd-back" href="javascript:void(0)"><span><i class="fa-regular fa-arrow-left"></i> Back</span></a>
            </div>
           </div>
         </div>
       </div>
     </section>
   </main>

  <footer>
     <div id="site-contact" class="tp-footer-area z-index black-bg fix p-relative pt-115 pb-70">
       <div class="tp-footer-big-text d-none d-md-block">
          <span>ReWear</span>
       </div>
       <div class="container">
          <div class="row">
              <div class="col-xl-6 col-lg-6 mb-50 wow tpfadeLeft" data-wow-duration=".9s" data-wow-delay=".5s">
                  <div class="tp-footer-widget">
                     <div class="tp-form-box">
                        <div class="tp-footer-title-box pb-50">
                           <span class="tp-section-subtitle-2 mb-10">support email</span>
                           <h4 class="tp-form-title"><a href="mailto:info@listbnb.com">info@listbnb.com</a></h4>
                        </div>
                        <form action="contact_submit.php" method="post">
                           <div class="row">
                              <div class="col-xl-6 col-lg-6 col-md-6 col-12">
                                 <div class="tp-form-input-box">
                                    <label>full name</label>
                                    <input type="text" name="full_name" placeholder="Your name" required>
                                 </div>
                              </div>
                              <div class="col-xl-6 col-lg-6 col-md-6 col-12">
                                 <div class="tp-form-input-box">
                                    <label>email address</label>
                                    <input type="email" name="email" placeholder="Your email" required>
                                 </div>
                              </div>
                              <div class="col-12">
                                 <div class="tp-form-textarea-box">
                                    <label>message</label>
                                    <textarea name="message" placeholder="Your message" required></textarea>
                                 </div>
                              </div>
                           </div>
                           <div class="tp-form-button">
                              <button class="tp-btn-black theme-bg" type="submit">
                                 <span>Submit <i class="fa-sharp fa-regular fa-arrow-right-long"></i></span>
                              </button>
                           </div>
                        </form>
                     </div>
                  </div>
               </div>
               <div class="col-xl-6 col-lg-6 mb-50 wow tpfadeRight" data-wow-duration=".9s" data-wow-delay=".7s">
                  <div class="tp-footer-widget">
                     <div class="tp-footer-right">
                        <h4 class="tp-form-title pb-30">Essential</h4>
                        <div class="tp-footer-list pb-65">
                           <ul>
                              <li><a href="#">Company & Contact Info</a></li>
                              <li><a href="sitemap.html">Sitemap</a></li>
                              <li><a href="privacy.html">Privacy Policy</a></li>
                              <li><a href="faq.html">FAQ Page</a></li>
                              <li><a href="terms.html">Terms & Conditions</a></li>
                           </ul>
                        </div>
                        <div class="tp-footer-content tp-footer-content-border">
                           <p><i>ReWear</i> a Largest Classified Listing Marketplace offers perfect WordPress Ads classified Themes to build your own classified websites.</p>
                           <a href="contact.html"><i class="fal fa-arrow-right-long"></i> Get It Now</a>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
      <div class="tp-copyright-area black-bg">
         <div class="container">
            <div class="tp-copyright-ptb">
               <div class="row align-items-center">
                  <div class="col-xl-7 col-lg-6 col-md-6 col-sm-7 wow tpfadeUp" data-wow-duration=".9s" data-wow-delay=".3s">
                     <div class="tp-copyright-left d-flex align-items-center justify-content-center justify-content-md-start">
                        <div class="tp-copyright-logo d-none d-xl-block"><span>ReWear</span></div>
                        <div class="tp-copyright-text text-center text-md-start">
                           <p>Copyright & Design by <a href="#">@ThemePure</a> - 2024</p>
                        </div>
                     </div>
                  </div>
                  <div class="col-xl-5 col-lg-6 col-md-6 col-sm-5 wow tpfadeUp" data-wow-duration=".9s" data-wow-delay=".3s">
                     <div class="tp-copyright-right justify-content-center d-flex justify-content-sm-end align-items-center">
                        <div class="tp-copyright-social">
                           <a href="#"><i class="fa-brands fa-facebook-f"></i></a>
                           <a href="#"><i class="fa-brands fa-twitter"></i></a>
                           <a href="#"><i class="fa-brands fa-behance"></i></a>
                           <a href="#"><i class="fa-brands fa-youtube"></i></a>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </footer>

   <script src="assets/js/vendor/jquery.js"></script>
   <script src="assets/js/bootstrap-bundle.js"></script>
   <script src="assets/js/swiper-bundle.js"></script>
   <script src="assets/js/slick.js"></script>
   <script src="assets/js/magnific-popup.js"></script>
   <script src="assets/js/nice-select.js"></script>
   <script src="assets/js/purecounter.js"></script>
   <script src="assets/js/countdown.js"></script>
   <script src="assets/js/wow.js"></script>
   <script src="assets/js/isotope-pkgd.js"></script>
   <script src="assets/js/imagesloaded-pkgd.js"></script>
   <script src="assets/js/ajax-form.js"></script>
   <script src="assets/js/main.js"></script>
   <script>
      (function(){
        var thumbs = document.querySelectorAll('.thumbs img');
        var main = document.getElementById('mainImage');
        thumbs.forEach(function(t){
          t.addEventListener('click', function(){
            var src = t.getAttribute('src');
            if (src) { main.setAttribute('src', src); }
          });
        });
        var addBtn = document.querySelector('.pd-addcart');
        if (addBtn) {
          addBtn.addEventListener('click', function(){
            var id = <?php echo (int)$p['id']; ?>;
            fetch('api/cart.php?action=add', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'id='+encodeURIComponent(id)})
              .then(function(r){ return r.json(); })
              .then(function(){ window.location.href = 'cart.php'; })
              .catch(function(){ window.location.href = 'cart.php'; });
          });
        }
        var backBtn = document.querySelector('.pd-back');
        if (backBtn) {
          backBtn.addEventListener('click', function(e){
            e.preventDefault();
            if (document.referrer && document.referrer !== '') { history.back(); }
            else { window.location.href = 'index-2.php'; }
          });
        }
      })();
   </script>
</body>
</html>
