<?php declare(strict_types=1);
session_start();
$isAdmin = isset($_SESSION['role']) && $_SESSION['role'] === 'Admin' && isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0;
if (!$isAdmin) {
  header('Location: login.html');
  exit;
}

$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='admin-products.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='admin-products.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='admin-products.php';</script></body></html>";
  exit;
}
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>Admin • Edit Product</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>
    :root{--ad-bg:#0f0f10;--ad-card:#ffffff;--ad-border:#e6e8eb;--ad-muted:#6b7280;--ad-title:#121317;--ad-accent:#4f46e5}
    .tp-profile-area{padding-top:0!important;padding-bottom:48px!important}
    .tp-header-area.tp-header-inner-style{margin-bottom:0;border-bottom:1px solid #1b1b1b}
    .admin-layout{display:grid;grid-template-columns:260px 1fr;gap:24px;margin-top:24px}
    .section{background:#fff;border:1px solid var(--ad-border);border-radius:16px;padding:20px;box-shadow:0 4px 16px rgba(0,0,0,.06)}
    .card{background:#fff;border:1px solid var(--ad-border);border-radius:16px;box-shadow:0 8px 28px rgba(0,0,0,.06)}
    .card-header{display:flex;align-items:center;justify-content:space-between;padding:18px 20px;border-bottom:1px solid var(--ad-border)}
    .card-title{font-size:22px;font-weight:800;color:var(--ad-title);margin:0}
    .breadcrumb{display:flex;gap:8px;color:var(--ad-muted);font-size:13px;margin-top:6px}
    .btn-primary{padding:10px 16px;border-radius:12px;background:#4f46e5;color:#fff;border:none;box-shadow:0 2px 10px rgba(79,70,229,.25);display:inline-flex;align-items:center;gap:8px}
    .btn-secondary{padding:10px 16px;border-radius:12px;background:#f8fafc;color:#0f172a;border:1px solid #e5e7eb;display:inline-flex;align-items:center;gap:8px}
    .grid-2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
    .tp-login-input-box label{font-weight:600;color:#111}
    .tp-login-input input, .tp-login-textarea textarea, .postbox__select select{width:100%;height:44px;padding:10px 12px;background:#fff;border:1px solid var(--ad-border);border-radius:10px;color:#111;box-shadow:none}
    .tp-login-textarea textarea{min-height:120px}
    .preview-card{background:#fff;border:1px solid var(--ad-border);border-radius:16px;box-shadow:0 8px 28px rgba(0,0,0,.06)}
    .preview-head{padding:14px 16px;border-bottom:1px solid var(--ad-border);display:flex;align-items:center;justify-content:space-between}
    .preview-title{font-weight:700;font-size:16px;color:#111}
    .preview-body{padding:16px}
    .preview-thumb{width:100%;height:180px;object-fit:cover;border-radius:12px;border:1px solid #eee}
    .preview-meta{display:flex;align-items:center;justify-content:space-between;margin-top:12px}
    .preview-price{font-weight:700;font-size:18px}
    .preview-badge{display:inline-block;padding:6px 10px;border-radius:999px;border:1px solid var(--ad-border);font-size:12px}
    .upload-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:10px}
    .upload-card{border:1px solid var(--ad-border);border-radius:12px;background:#fff}
    .upload-drop{position:relative;min-height:100px;border-radius:12px;border:1px dashed #cbd5e1;background:#f8fafc;display:flex;align-items:center;justify-content:center;overflow:hidden}
    .upload-drop img{width:100%;height:100%;object-fit:cover}
    .upload-actions{display:flex;gap:8px;padding:8px;justify-content:center}
    .upload-input{display:none}
    .form-actions{display:flex;gap:12px;justify-content:center;margin-top:8px}
    .admin-sidebar .menu-title{font-size:13px;color:var(--ad-muted);text-transform:uppercase;margin:24px 0 12px;letter-spacing:.05em;font-weight:600;padding-left:8px}
    .admin-sidebar ul{list-style:none;padding:0;margin:0}
    .admin-sidebar li a{display:flex;align-items:center;gap:12px;padding:10px 12px;border-radius:8px;color:#111;text-decoration:none;transition:all .2s ease;font-weight:500}
    .admin-sidebar li a:hover,.admin-sidebar li a.active{background:#eef2ff;color:#4f46e5}
  </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="admin-dashboard.php"><span style="color:#fff;font-weight:800">Admin</span></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></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-sign-box d-none d-sm-block">
                <a href="logout.php"><i class="fa-solid fa-right-from-bracket"></i>Logout</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>

  <main>
    <div class="tp-profile-area z-index pb-120 pt-60">
      <div class="container">
        <div class="admin-layout">
          <div class="section sidebar-card">
            <aside class="admin-sidebar">
              <div class="menu-title">Menu</div>
              <ul>
                <li><a href="admin-dashboard.php"><i class="fa-regular fa-grid-2"></i> Dashboard</a></li>
              </ul>
              <div class="menu-title">Product & Order</div>
              <ul>
                <li><a href="admin-products.php" class="active"><i class="fa-regular fa-box"></i> Manage Products</a></li>
                <li><a href="admin-order-requests.php"><i class="fa-regular fa-cart-shopping"></i> Manage Order Requests</a></li>
              </ul>
              <div class="menu-title">Site Content</div>
              <ul>
                <li><a href="admin-home-images.php"><i class="fa-regular fa-image"></i> Home Image</a></li>
              </ul>
              <div class="menu-title">Accounts & Roles</div>
              <ul>
                <li><a href="admin-users.php"><i class="fa-regular fa-users"></i> Customers</a></li>
                <li><a href="#"><i class="fa-regular fa-user-tie"></i> Sellers</a></li>
                <li><a href="#"><i class="fa-regular fa-chart-pie-simple"></i> Reports</a></li>
              </ul>
            </aside>
          </div>
          <section class="admin-main">
            <div class="card mb-20">
              <div class="card-header">
                <div>
                  <h4 class="card-title"><i class="fa-regular fa-pen" style="margin-right:8px"></i>Edit Product</h4>
                  <div class="breadcrumb"><span>Products</span><span class="sep">/</span><span>Edit Product</span></div>
                </div>
                <div class="actions">
                  <a href="admin-products.php" class="btn-secondary"><i class="fa-regular fa-box"></i><span>Back to Products</span></a>
                </div>
              </div>
            </div>
            <div class="section">
              <form action="product_edit.php" method="post" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?php echo (int)$p['id']; ?>"/>
                <div class="grid-2">
                  <div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Product Title <i> *</i></label>
                      <div class="tp-login-input p-relative">
                        <input type="text" name="product_title" value="<?php echo htmlspecialchars($p['product_title'], ENT_QUOTES); ?>" required>
                      </div>
                    </div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Product Size <i> *</i></label>
                      <div class="postbox__select">
                        <select name="product_size" required>
                          <?php foreach(['XS','Small','Medium','Large','XL'] as $s): ?>
                          <option value="<?php echo $s; ?>" <?php echo $p['product_size']===$s?'selected':''; ?>><?php echo $s; ?></option>
                          <?php endforeach; ?>
                        </select>
                      </div>
                    </div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Price <i> *</i></label>
                      <div class="tp-login-input p-relative">
                        <input type="number" name="price" value="<?php echo htmlspecialchars($p['price'], ENT_QUOTES); ?>" step="0.01" required>
                      </div>
                    </div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Condition <i> *</i></label>
                      <div class="postbox__select">
                        <select name="condition" required>
                          <option value="New" <?php echo $p['condition']==='New'?'selected':''; ?>>New</option>
                          <option value="Used" <?php echo $p['condition']==='Used'?'selected':''; ?>>Used</option>
                        </select>
                      </div>
                    </div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Category <i> *</i></label>
                      <div class="postbox__select">
                        <select name="category" required>
                          <?php $cats=['summer'=>'Summer Clothing','winter'=>'Winter Clothing','dress_type'=>'By Dress Type','party_formal'=>'Party & Formal Wear','active'=>'Active Wear / Gym Wear','nightwear'=>'Nightwear / Sleepwear','modest'=>'Modest Wear','casual'=>'Casual Wear','spring'=>'Spring Clothing','autumn'=>'Autumn / Fall Clothing'];
                          foreach($cats as $code=>$name): $sel = ($p['category']===$name)?'selected':''; ?>
                          <option value="<?php echo $code; ?>" <?php echo $sel; ?>><?php echo $name; ?></option>
                          <?php endforeach; ?>
                        </select>
                      </div>
                    </div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Product Type <i> *</i></label>
                      <div class="tp-login-input p-relative">
                        <input type="text" name="product_type" value="<?php echo htmlspecialchars($p['product_type'], ENT_QUOTES); ?>" required>
                      </div>
                    </div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Brand</label>
                      <div class="tp-login-input p-relative">
                        <input type="text" name="brand" value="<?php echo htmlspecialchars($p['brand'] ?? '', ENT_QUOTES); ?>">
                      </div>
                    </div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Color</label>
                      <div class="tp-login-input p-relative">
                        <input type="text" name="color" value="<?php echo htmlspecialchars($p['color'] ?? '', ENT_QUOTES); ?>" placeholder="e.g. Red">
                      </div>
                    </div>
                  </div>
                  <div>
                    <div class="preview-card mb-20">
                      <div class="preview-head"><div class="preview-title">Preview</div></div>
                      <div class="preview-body">
                        <img id="pvThumb" class="preview-thumb" src="<?php echo !empty($p['image1']) ? htmlspecialchars($p['image1'], ENT_QUOTES) : 'assets/img/listing/listing-1-1.png'; ?>" alt="thumb">
                        <div class="preview-meta">
                          <div id="pvTitle"><?php echo htmlspecialchars($p['product_title'], ENT_QUOTES); ?></div>
                          <div id="pvPrice" class="preview-price">$<?php echo number_format((float)$p['price'],2); ?></div>
                        </div>
                        <div style="margin-top:8px"><span id="pvCond" class="preview-badge"><?php echo htmlspecialchars($p['condition'], ENT_QUOTES); ?></span></div>
                      </div>
                    </div>
                    <div class="tp-login-input-box text-start mb-20">
                      <label>Product Description <i> *</i></label>
                      <div class="tp-login-textarea p-relative">
                        <textarea name="description" required><?php echo htmlspecialchars($p['description'], ENT_QUOTES); ?></textarea>
                      </div>
                    </div>
                    <div class="upload-grid">
                      <?php for($i=1;$i<=5;$i++): $k='image'.$i; ?>
                      <div class="upload-card">
                        <div class="upload-drop" data-index="<?php echo $i; ?>">
                          <?php if(!empty($p[$k])): ?><img src="<?php echo htmlspecialchars($p[$k], ENT_QUOTES); ?>" alt="img"/><?php endif; ?>
                        </div>
                        <div class="upload-actions">
                          <label class="btn-secondary" style="cursor:pointer">
                            <input class="upload-input" type="file" name="image<?php echo $i; ?>" accept="image/png,image/jpeg">
                            <span>Browse</span>
                          </label>
                        </div>
                      </div>
                      <?php endfor; ?>
                    </div>
                  </div>
                </div>
                <div class="form-actions pt-10">
                  <a href="admin-products.php" class="btn-secondary"><i class="fa-regular fa-arrow-left"></i><span>Cancel</span></a>
                  <button type="submit" class="btn-primary"><i class="fa-regular fa-floppy-disk"></i><span>Update Product</span></button>
                </div>
              </form>
            </div>
          </section>
        </div>
      </div>
    </div>
  </main>

  <footer>
    <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">
              <div class="tp-copyright-left d-flex align-items-center justify-content-center justify-content-md-start">
                <div class="tp-copyright-text text-center text-md-start">
                  <p>ReWear Admin</p>
                </div>
              </div>
            </div>
            <div class="col-xl-5 col-lg-6 col-md-6 col-sm-5">
              <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>
                </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/slick.js"></script>
  <script src="assets/js/main.js"></script>
  <script>
    (function(){
      var t = document.querySelector('input[name="product_title"]');
      var p = document.querySelector('input[name="price"]');
      var c = document.querySelector('select[name="condition"]');
      var pvT = document.getElementById('pvTitle');
      var pvP = document.getElementById('pvPrice');
      var pvC = document.getElementById('pvCond');
      var pvImg = document.getElementById('pvThumb');
      function updTitle(){ pvT.textContent = t && t.value ? t.value : pvT.textContent; }
      function updPrice(){ var v = p && p.value ? parseFloat(p.value) : null; pvP.textContent = v && !isNaN(v) ? ('$'+v.toFixed(2)) : pvP.textContent; }
      function updCond(){ pvC.textContent = c && c.value ? c.value : pvC.textContent; }
      if(t) t.addEventListener('input', updTitle);
      if(p) p.addEventListener('input', updPrice);
      if(c) c.addEventListener('change', updCond);
      var inputs = document.querySelectorAll('.upload-input');
      inputs.forEach(function(input){
        input.addEventListener('change', function(e){
          var file = e.target.files && e.target.files[0];
          var card = e.target.closest('.upload-card');
          var drop = card ? card.querySelector('.upload-drop') : null;
          if(file && drop){
            var url = URL.createObjectURL(file);
            drop.innerHTML = '<img src="'+url+'" alt="img">';
            var idx = drop.getAttribute('data-index');
            if(idx === '1' && pvImg){ pvImg.src = url; }
          }
        });
      });
      var drops = document.querySelectorAll('.upload-drop');
      drops.forEach(function(drop){
        drop.addEventListener('dragover', function(e){ e.preventDefault(); drop.style.borderColor = '#4f46e5'; });
        drop.addEventListener('dragleave', function(){ drop.style.borderColor = '#cbd5e1'; });
        drop.addEventListener('drop', function(e){
          e.preventDefault(); drop.style.borderColor = '#cbd5e1';
          var idx = drop.getAttribute('data-index');
          var input = drop.parentElement.querySelector('.upload-input');
          var files = e.dataTransfer.files;
          if(input && files && files.length){
            input.files = files;
            var file = files[0];
            var url = URL.createObjectURL(file);
            drop.innerHTML = '<img src="'+url+'" alt="img">';
            if(idx === '1' && pvImg){ pvImg.src = url; }
          }
        });
      });
    })();
  </script>
</body>
</html>
