<?php
declare(strict_types=1);
session_start();
$isAdmin = isset($_SESSION['role']) && $_SESSION['role'] === 'Admin';
$successRedirect = $isAdmin ? 'admin-products.php' : 'my-products.php';

$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='".$successRedirect."';</script></body></html>";
    exit;
}

function mapCategoryCodeToName($code){
    $map = [
        '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',
    ];
    return $map[$code] ?? $code;
}

$id = (int)($_GET['id'] ?? $_POST['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='".$successRedirect."';</script></body></html>";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_title = trim($_POST['product_title'] ?? '');
    $product_size = trim($_POST['product_size'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $condition = trim($_POST['condition'] ?? '');
    $categoryCode = trim($_POST['category'] ?? '');
    $product_type = trim($_POST['product_type'] ?? '');
    $brand = trim($_POST['brand'] ?? '');
    $color = trim($_POST['color'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $category = mapCategoryCodeToName($categoryCode);

    $uploadDir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads';
    if (!is_dir($uploadDir)) @mkdir($uploadDir, 0775, true);

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

    $paths = [];
    for ($i=1;$i<=5;$i++) {
        $key='image'.$i;
        $paths[$i] = $existing[$key] ?? null;
        if (!isset($_FILES[$key])) continue;
        $name = $_FILES[$key]['name'] ?? '';
        $tmp = $_FILES[$key]['tmp_name'] ?? '';
        $err = $_FILES[$key]['error'] ?? UPLOAD_ERR_NO_FILE;
        if ($err === UPLOAD_ERR_NO_FILE || $name === '' || $tmp === '') continue;
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        if (!in_array($ext, ['png','jpg','jpeg'], true)) continue;
        $safe = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', pathinfo($name, PATHINFO_FILENAME));
        $final = $safe.'_'.uniqid('',true).'.'.$ext;
        $dest = $uploadDir . DIRECTORY_SEPARATOR . $final;
        if (@move_uploaded_file($tmp, $dest)) {
            $paths[$i] = 'uploads/'.$final;
        }
    }

    try {
        $upd = $pdo->prepare('UPDATE products SET product_title=:title, product_size=:size, price=:price, `condition`=:cond, category=:cat, product_type=:ptype, brand=:brand, color=:color, description=:descr, image1=:img1, image2=:img2, image3=:img3, image4=:img4, image5=:img5 WHERE id=:id');
        $upd->execute([
            ':title'=>$product_title,
            ':size'=>$product_size,
            ':price'=>number_format((float)$price,2,'.',''),
            ':cond'=>$condition,
            ':cat'=>$category,
            ':ptype'=>$product_type,
            ':brand'=>($brand !== '' ? $brand : null),
            ':color'=>($color !== '' ? $color : null),
            ':descr'=>$description,
            ':img1'=>$paths[1] ?? null,
            ':img2'=>$paths[2] ?? null,
            ':img3'=>$paths[3] ?? null,
            ':img4'=>$paths[4] ?? null,
            ':img5'=>$paths[5] ?? null,
            ':id'=>$id,
        ]);
    } catch (Throwable $e) {
        http_response_code(500);
        echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Failed to update product.');window.location.href='".$successRedirect."';</script></body></html>";
        exit;
    }

    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Product updated');window.location.href='".$successRedirect."';</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='".$successRedirect."';</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>Edit Product - 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>
      .edit-form-card{background:#fff;border:1px solid #e5e7eb;border-radius:16px;box-shadow:0 8px 28px rgba(0,0,0,.06);padding:24px}
      .form-title{font-size:22px;font-weight:700;margin-bottom:16px}
      .tp-login-input-box label{font-weight:600;color:#111}
      .tp-login-input input,.postbox__select select,.tp-login-textarea textarea{width:100%;border:1px solid #e5e7eb;border-radius:12px;padding:10px 12px}
      .tp-login-textarea textarea{min-height:120px}
      .preview-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:10px}
      .preview-grid img{width:100%;height:90px;object-fit:cover;border-radius:8px;border:1px solid #eee}
      .file-input{display:block;margin-top:6px}
      .form-actions{display:flex;gap:12px;justify-content:center;margin-top:8px}
      .btn-primary{padding:10px 16px;border-radius:12px;background:#2b5cff;color:#fff;border:none;box-shadow:0 4px 12px rgba(43,92,255,.25);transition:all .15s ease;display:inline-flex;align-items:center;gap:8px}
      .btn-primary:hover{background:#244de3}
      .btn-secondary{padding:10px 16px;border-radius:12px;background:#f8fafc;color:#0f172a;border:1px solid #e5e7eb;display:inline-flex;align-items:center;gap:8px}
      .btn-secondary:hover{background:#eef2f7}
    </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><a href="index-2.html">Home</a></li>
                           <li><a href="logout.php">Logout</a></li>
                        </ul>
                     </nav>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </header>

   <main>
      <div class="tp-profile-area z-index pb-120 pt-60">
         <div class="container">
            <div class="row">
               <div class="col-xl-12">
                  <div class="ads-Listing__form edit-form-card">
                     <div class="form-title">Update Product</div>
                     <form action="product_edit.php" method="post" enctype="multipart/form-data">
                        <input type="hidden" name="id" value="<?php echo (int)$p['id']; ?>"/>
                        <div class="row gx-20">
                           <div class="col-lg-6 col-md-6 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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>
                           <div class="col-lg-6 col-md-6 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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>
                           <div class="col-lg-6 col-md-6 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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>
                           <div class="col-lg-6 col-md-6 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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>
                           <div class="col-lg-6 col-md-6 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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>
                           <div class="col-lg-6 col-md-6 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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>
                           <div class="col-lg-6 col-md-6 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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>
                           <div class="col-lg-6 col-md-6 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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 class="col-lg-12 mb-20">
                              <div class="tp-login-input-box text-start">
                                 <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>
                           <div class="col-12 mb-20">
                              <div class="preview-grid">
                                 <?php for($i=1;$i<=5;$i++): $k='image'.$i; ?>
                                 <div>
                                    <?php if(!empty($p[$k])): ?><img src="<?php echo htmlspecialchars($p[$k], ENT_QUOTES); ?>" alt="img"/><?php endif; ?>
                                    <input class="file-input" type="file" name="image<?php echo $i; ?>" accept="image/png,image/jpeg">
                                  </div>
                                 <?php endfor; ?>
                              </div>
                           </div>
                        </div>
                        <div class="form-actions pt-10">
                           <a class="btn-secondary" href="my-products.php"><i class="fa-solid fa-arrow-left"></i><span>Back</span></a>
                           <button class="btn-primary" type="submit"><i class="fa-solid fa-floppy-disk"></i><span>Update Product</span></button>
                        </div>
                     </form>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </main>

   <script src="assets/js/vendor/jquery.js"></script>
   <script src="assets/js/bootstrap-bundle.js"></script>
   <script src="assets/js/main.js"></script>
</body>
</html>
