<?php
/**
 * vendor_panel/products.php — จัดการสินค้าของร้าน
 * Vendor เห็นเฉพาะสินค้าของตัวเอง
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/image_helper.php';

requireVendor();

$db       = getDBConnection();
$vendorId = getCurrentVendorId();

// Fallback vendor_id from session user if getCurrentVendorId() returned null
if (!$vendorId && isset($_SESSION['user']['id'])) {
    try {
        $vstmt = $db->prepare("SELECT id FROM vendors WHERE user_id = ? LIMIT 1");
        $vstmt->execute([$_SESSION['user']['id']]);
        $vendorId = (int)$vstmt->fetchColumn();
    } catch (PDOException $e) {}
}

if (!$vendorId) {
    $_SESSION['flash_error'] = 'ไม่พบข้อมูลร้านค้าของคุณ กรุณาสมัครเปิดร้านค้าก่อน';
    header('Location: ' . SITE_URL . '/register_store.php');
    exit;
}

$error = '';

// ── DELETE ──────────────────────────────────────────────────
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $pid = (int)$_GET['id'];
    requireProductOwnership($pid);
    try {
        $db->prepare("DELETE FROM products WHERE id=? AND vendor_id=?")->execute([$pid, $vendorId]);
        $_SESSION['flash_success'] = 'ลบสินค้าเรียบร้อยแล้ว';
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = 'เกิดข้อผิดพลาดในการลบสินค้า: ' . $e->getMessage();
    }
    header('Location: products.php'); exit;
}

// ── SAVE (Add / Edit) ─────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCSRFToken($_POST['csrf_token'] ?? '');

    $productId         = (int)($_POST['product_id'] ?? 0);
    $name              = sanitize($_POST['name']              ?? '');
    $category_id_raw   = $_POST['category_id'] ?? 1;
    $vendor_category_id= (int)($_POST['vendor_category_id']  ?? 0) ?: null;

    if ($category_id_raw === 'other' && !empty($_POST['custom_category_name'])) {
        $custom_cat = sanitize($_POST['custom_category_name']);
        $custom_slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $custom_cat)) . '-' . substr(md5(uniqid()), 0, 4);
        try {
            $db->prepare("INSERT INTO categories (name, slug, icon, is_active) VALUES (?, ?, '📦', 1)")
               ->execute([$custom_cat, $custom_slug]);
            $category_id = (int)$db->lastInsertId();
        } catch (PDOException $e) {
            $category_id = 1;
        }
    } else {
        $category_id = (int)$category_id_raw;
    }
    $price             = (float)($_POST['price']             ?? 0);
    $normal_price      = (float)($_POST['normal_price']      ?? 0) ?: null;
    $stock             = (int)($_POST['stock']               ?? 0);
    
    $stdSizes          = isset($_POST['standard_sizes']) && is_array($_POST['standard_sizes']) ? $_POST['standard_sizes'] : [];
    $customSizesStr    = $_POST['custom_sizes'] ?? '';
    $customSizesArr    = array_filter(array_map('trim', explode(',', $customSizesStr)), function($v) { return $v !== ''; });
    $allSizesArr       = array_unique(array_merge($stdSizes, $customSizesArr));
    $sizes             = sanitize(implode(', ', $allSizesArr));
    
    $colors            = sanitize($_POST['colors']            ?? '');
    $description       = sanitize($_POST['description']       ?? '');
    $status            = in_array($_POST['status'] ?? '', ['active','inactive']) ? $_POST['status'] : 'active';
    $slug              = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $name)) . '-' . substr(md5(uniqid()), 0, 6);

    $uploadedImages = [];
    if (isset($_FILES['product_images'])) {
        $subDir = 'vendors/' . $vendorId . '/products';
        $files = $_FILES['product_images'];
        if (is_array($files['name'])) {
            for ($i = 0; $i < count($files['name']); $i++) {
                if ($files['error'][$i] === UPLOAD_ERR_OK) {
                    $singleFile = [
                        'name'     => $files['name'][$i],
                        'type'     => $files['type'][$i],
                        'tmp_name' => $files['tmp_name'][$i],
                        'error'    => $files['error'][$i],
                        'size'     => $files['size'][$i],
                    ];
                    $result = processAndUploadImage($singleFile, $subDir);
                    if ($result['success']) {
                        $uploadedImages[] = [
                            'main_path' => UPLOAD_URL . $result['main_path'],
                            'thumb_path' => UPLOAD_URL . $result['thumb_path']
                        ];
                    }
                }
            }
        }
    }

    if (empty($name) || $price <= 0) {
        $error = 'กรุณากรอกชื่อสินค้าและราคาให้ถูกต้อง';
    } elseif (empty($error)) {
        // ตรวจสอบและสร้างคอลัมน์ใหม่ถ้ายังไม่มี (ครอบ try-catch ป้องกัน fatal error)
        try {
            $stockColCheck = $db->query("SHOW COLUMNS FROM products LIKE 'stock'")->fetch();
            if (!$stockColCheck) {
                $db->exec("ALTER TABLE products ADD COLUMN stock INT NOT NULL DEFAULT 0 AFTER price");
            }
        } catch (PDOException $e) {}

        try {
            $sizesColCheck = $db->query("SHOW COLUMNS FROM products LIKE 'sizes'")->fetch();
            if (!$sizesColCheck) {
                $db->exec("ALTER TABLE products ADD COLUMN sizes VARCHAR(255) NULL AFTER stock");
            }
        } catch (PDOException $e) {}

        try {
            $colorsColCheck = $db->query("SHOW COLUMNS FROM products LIKE 'colors'")->fetch();
            if (!$colorsColCheck) {
                $db->exec("ALTER TABLE products ADD COLUMN colors VARCHAR(255) NULL AFTER sizes");
            }
        } catch (PDOException $e) {}

        try {
            if ($productId > 0) {
                // ตรวจสิทธิ์
                requireProductOwnership($productId);
                $mainImage = !empty($uploadedImages) ? $uploadedImages[0]['main_path'] : null;
                
                if ($mainImage) {
                    $db->prepare("UPDATE products SET category_id=?,vendor_category_id=?,name=?,description=?,price=?,normal_price=?,stock=?,sizes=?,colors=?,main_image=?,status=? WHERE id=? AND vendor_id=?")
                       ->execute([$category_id,$vendor_category_id,$name,$description,$price,$normal_price,$stock,$sizes,$colors,$mainImage,$status,$productId,$vendorId]);
                    // Insert remaining images into gallery (if any)
                    for ($j = 1; $j < count($uploadedImages); $j++) {
                        try {
                            $db->prepare("INSERT INTO product_images (product_id, image_path, thumb_path) VALUES (?, ?, ?)")
                               ->execute([$productId, $uploadedImages[$j]['main_path'], $uploadedImages[$j]['thumb_path']]);
                        } catch (PDOException $e) {}
                    }
                } else {
                    $db->prepare("UPDATE products SET category_id=?,vendor_category_id=?,name=?,description=?,price=?,normal_price=?,stock=?,sizes=?,colors=?,status=? WHERE id=? AND vendor_id=?")
                       ->execute([$category_id,$vendor_category_id,$name,$description,$price,$normal_price,$stock,$sizes,$colors,$status,$productId,$vendorId]);
                }
                $_SESSION['flash_success'] = 'แก้ไขสินค้าเรียบร้อยแล้ว';
            } else {
                $mainImage = !empty($uploadedImages) ? $uploadedImages[0]['main_path'] : 'https://images.unsplash.com/photo-1521572267360-ee0c2909d518?w=800';
                $db->prepare("INSERT INTO products (vendor_id,category_id,vendor_category_id,name,slug,description,price,normal_price,stock,sizes,colors,main_image,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)")
                   ->execute([$vendorId,$category_id,$vendor_category_id,$name,$slug,$description,$price,$normal_price,$stock,$sizes,$colors,$mainImage,$status]);
                
                $newProductId = $db->lastInsertId();
                
                // Insert remaining images into gallery
                for ($j = 1; $j < count($uploadedImages); $j++) {
                    try {
                        $db->prepare("INSERT INTO product_images (product_id, image_path, thumb_path) VALUES (?, ?, ?)")
                           ->execute([$newProductId, $uploadedImages[$j]['main_path'], $uploadedImages[$j]['thumb_path']]);
                    } catch (PDOException $e) {}
                }
                $_SESSION['flash_success'] = 'เพิ่มสินค้าใหม่สำเร็จ!';
            }
            header('Location: products.php'); exit;
        } catch (PDOException $e) {
            $error = 'เกิดข้อผิดพลาดในการบันทึกข้อมูลสินค้า: ' . $e->getMessage();
        }
    }
}

// ── DATA ──────────────────────────────────────────────────
$mainCategories = [];
try {
    $mainCategoriesStmt = $db->query("SELECT * FROM categories WHERE is_active=1 ORDER BY sort_order ASC, name ASC");
    if ($mainCategoriesStmt) {
        $mainCategories = $mainCategoriesStmt->fetchAll() ?: [];
    }
} catch (PDOException $e) {}

$vendorCategories = [];
try {
    $vendorCategoriesStmt = $db->prepare("SELECT * FROM vendor_categories WHERE vendor_id=? AND is_active=1 ORDER BY sort_order ASC, name ASC");
    $vendorCategoriesStmt->execute([$vendorId]);
    $vendorCategories = $vendorCategoriesStmt->fetchAll() ?: [];
} catch (PDOException $e) {}

$filterStatus = $_GET['status'] ?? '';
$whereSql = "WHERE p.vendor_id = ?";
$queryParams = [$vendorId];
if (!empty($filterStatus) && in_array($filterStatus, ['active', 'inactive', 'pending'])) {
    $whereSql .= " AND p.status = ?";
    $queryParams[] = $filterStatus;
}

$products = [];
try {
    $productsStmt = $db->prepare("
        SELECT p.*, c.name AS cat_name, vc.name AS vcat_name
        FROM products p
        LEFT JOIN categories c ON p.category_id = c.id
        LEFT JOIN vendor_categories vc ON p.vendor_category_id = vc.id
        $whereSql
        ORDER BY p.created_at DESC
    ");
    $productsStmt->execute($queryParams);
    $products = $productsStmt->fetchAll() ?: [];
} catch (PDOException $e) {
    $error = 'เกิดข้อผิดพลาดในการดึงข้อมูลสินค้า: ' . $e->getMessage();
}

// ── โหลด vendor_header (ส่ง HTML) หลังประมวลผลเสร็จ ──
require_once __DIR__ . '/vendor_header.php';
?>

<!-- Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h4 class="fw-bold mb-0">📦 สินค้าของฉัน</h4>
    <small class="text-muted">สินค้าทั้งหมด <?php echo is_array($products) ? count($products) : 0; ?> รายการ</small>
  </div>
  <button class="btn btn-vendor-primary px-4" data-bs-toggle="modal" data-bs-target="#productModal" onclick="resetForm()">
    + เพิ่มสินค้าใหม่
  </button>
</div>

<!-- Filter -->
<div class="v-card mb-3 p-3">
  <div class="d-flex gap-2 flex-wrap align-items-center">
    <span class="fw-semibold text-muted" style="font-size:.85rem">กรอง:</span>
    <?php foreach (['' => 'ทั้งหมด', 'active' => '✅ เปิดขาย', 'inactive' => '⛔ ปิด'] as $val => $label): ?>
      <a href="?status=<?php echo $val; ?>"
         class="btn btn-sm <?php echo $filterStatus === $val ? 'btn-primary' : 'btn-outline-secondary'; ?> rounded-pill">
        <?php echo $label; ?>
      </a>
    <?php endforeach; ?>
  </div>
</div>

<?php if ($error): ?>
  <div class="alert alert-danger rounded-3"><?php echo $error; ?></div>
<?php endif; ?>

<!-- Product Table -->
<div class="v-card">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th style="width:60px">รูป</th>
          <th>ชื่อสินค้า</th>
          <th>หมวดหมู่</th>
          <th class="text-end">ราคา</th>
          <th class="text-center">สต็อก</th>
          <th class="text-center">สถานะ</th>
          <th class="text-center">จัดการ</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($products)): ?>
          <tr>
            <td colspan="7" class="text-center py-5">
              <div style="font-size:2.5rem">📦</div>
              <div class="text-muted mt-2">ยังไม่มีสินค้า</div>
              <button class="btn btn-vendor-primary mt-3 px-4" data-bs-toggle="modal" data-bs-target="#productModal" onclick="resetForm()">
                + เพิ่มสินค้าแรก
              </button>
            </td>
          </tr>
        <?php endif; ?>
        <?php foreach ($products as $p): ?>
          <?php
            $sc = ($p['status'] ?? '') === 'active' ? 'badge-status-active' : 'badge-status-inactive';
            $sl = ($p['status'] ?? '') === 'active' ? '✅ เปิดขาย' : '⛔ ปิด';
            $rawImg = !empty($p['main_image']) ? $p['main_image'] : (!empty($p['image']) ? $p['image'] : '');
            $imgUrl = function_exists('formatImageUrl') ? formatImageUrl($rawImg) : $rawImg;
            if (empty($imgUrl)) {
                $imgUrl = defined('SITE_URL') ? SITE_URL . '/assets/images/no-image.png' : 'assets/images/no-image.png';
            }
          ?>
          <tr>
            <td>
              <img src="<?php echo htmlspecialchars($imgUrl); ?>"
                   onerror="this.onerror=null; this.src='<?php echo SITE_URL; ?>/assets/images/no-image.png';"
                   class="rounded-2 border shadow-sm" style="width:48px;height:48px;object-fit:cover" alt="<?php echo htmlspecialchars($p['name'] ?? ''); ?>">
            </td>
            <td>
              <div class="fw-semibold"><?php echo htmlspecialchars($p['name'] ?? ''); ?></div>
              <div class="text-muted" style="font-size:.75rem">฿<?php echo number_format((float)($p['price'] ?? 0), 2); ?></div>
            </td>
            <td>
              <span class="badge bg-light text-dark border"><?php echo htmlspecialchars($p['cat_name'] ?? 'ไม่มีหมวดหมู่'); ?></span>
              <?php if (!empty($p['vcat_name'])): ?>
                <span class="badge bg-light text-primary border ms-1" style="font-size:.7rem"><?php echo htmlspecialchars($p['vcat_name']); ?></span>
              <?php endif; ?>
            </td>
            <td class="text-end fw-bold">฿<?php echo number_format((float)($p['price'] ?? 0), 2); ?></td>
            <td class="text-center">
              <?php
                $variantStock = 0;
                try {
                    $stockStmt = $db->prepare("SELECT COALESCE(SUM(stock),0) FROM product_variants WHERE product_id=?");
                    $stockStmt->execute([$p['id']]);
                    $variantStock = (int)$stockStmt->fetchColumn();
                } catch (PDOException $e) {}
                $stockQty = $variantStock > 0 ? $variantStock : (int)($p['stock'] ?? 0);
                $stockClass = $stockQty <= 0 ? 'text-danger' : ($stockQty <= 5 ? 'text-warning' : 'text-success');
              ?>
              <span class="fw-bold <?php echo $stockClass; ?>"><?php echo $stockQty; ?></span>
            </td>
            <td class="text-center">
              <span class="badge <?php echo $sc; ?> px-2 py-1 rounded-pill"><?php echo $sl; ?></span>
            </td>
            <td class="text-center">
              <button class="btn btn-sm btn-outline-primary rounded-pill me-1"
                onclick='openEditModal(<?php echo json_encode($p); ?>)'>✏️ แก้ไข</button>
              <a href="?action=delete&id=<?php echo $p['id']; ?>"
                 class="btn btn-sm btn-outline-danger rounded-pill"
                 onclick="return confirm('ลบสินค้า \"<?php echo htmlspecialchars($p['name'] ?? '', ENT_QUOTES); ?>\" ?')">🗑️</a>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- ── PRODUCT MODAL ─────────────────────────────────────── -->
<div class="modal fade" id="productModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content rounded-4">
      <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
        <input type="hidden" name="product_id" id="prod_id">

        <div class="modal-header border-0 pb-0">
          <h5 class="modal-title fw-bold" id="modalTitle">+ เพิ่มสินค้าใหม่</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body pt-2">
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label fw-semibold">ชื่อสินค้า <span class="text-danger">*</span></label>
              <input type="text" name="name" id="prod_name" class="form-control" required placeholder="ชื่อสินค้า...">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">หมวดหมู่หลัก <span class="text-danger">*</span></label>
              <select name="category_id" id="prod_cat" class="form-select" required onchange="toggleCustomCategory()">
                <?php foreach ($mainCategories as $mc): ?>
                  <option value="<?php echo $mc['id']; ?>"><?php echo htmlspecialchars($mc['icon'].' '.$mc['name']); ?></option>
                <?php endforeach; ?>
                <option value="other">+ อื่นๆ (ระบุเอง)</option>
              </select>
              <input type="text" name="custom_category_name" id="custom_category_input" class="form-control mt-2" placeholder="พิมพ์ชื่อหมวดหมู่ใหม่ที่ต้องการ..." style="display: none;">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">หมวดหมู่ร้าน (ย่อย)</label>
              <select name="vendor_category_id" id="prod_vcat" class="form-select">
                <option value="">-- ไม่ระบุ --</option>
                <?php foreach ($vendorCategories as $vc): ?>
                  <option value="<?php echo $vc['id']; ?>"><?php echo htmlspecialchars($vc['name']); ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label fw-semibold">ราคาขาย (บาท) <span class="text-danger">*</span></label>
              <input type="number" step="0.01" min="0" name="price" id="prod_price" class="form-control" required placeholder="0.00">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-semibold">ราคาปกติ (ขีดฆ่า)</label>
              <input type="number" step="0.01" min="0" name="normal_price" id="prod_nprice" class="form-control" placeholder="ไม่บังคับ">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-semibold">จำนวนสต็อก <span class="text-danger">*</span></label>
              <input type="number" min="0" name="stock" id="prod_stock" class="form-control" required placeholder="0">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">ไซส์ (Sizes)</label>
              <div class="d-flex flex-wrap gap-2 mb-2">
                <?php foreach(['S','M','L','XL','XXL','oversize'] as $sz): ?>
                  <div class="form-check">
                    <input class="form-check-input size-checkbox" type="checkbox" name="standard_sizes[]" value="<?php echo $sz; ?>" id="size_<?php echo $sz; ?>">
                    <label class="form-check-label" for="size_<?php echo $sz; ?>"><?php echo $sz; ?></label>
                  </div>
                <?php endforeach; ?>
              </div>
              <input type="text" name="custom_sizes" id="custom_sizes" class="form-control" placeholder="ไซส์อื่นๆ เช่น Free Size, 38, 40 (คั่นด้วย ,)">
              <div class="form-text text-muted small">ระบุไซส์เพิ่มเติมโดยคั่นด้วยเครื่องหมาย ,</div>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">สี (Colors)</label>
              <input type="text" name="colors" id="prod_colors" class="form-control" placeholder="เช่น ดำ, ขาว, แดง (คั่นด้วย ,)">
              <div class="form-text text-muted small">ระบุหลายสีโดยคั่นด้วยเครื่องหมาย ,</div>
            </div>
            <div class="col-12">
              <label class="form-label fw-semibold">รูปภาพสินค้า</label>
              <input type="file" name="product_images[]" id="prod_img" class="form-control" accept="image/*" multiple
                     onchange="previewImg(this)">
              <div id="image_preview_container" class="d-flex flex-wrap gap-2 mt-2"></div>
            </div>
            <div class="col-12">
              <label class="form-label fw-semibold">รายละเอียดสินค้า</label>
              <textarea name="description" id="prod_desc" class="form-control" rows="3" placeholder="บรรยายสินค้า..."></textarea>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">สถานะ</label>
              <select name="status" id="prod_status" class="form-select">
                <option value="active">✅ เปิดขาย</option>
                <option value="inactive">⛔ ปิดชั่วคราว</option>
              </select>
            </div>
          </div>
        </div>
        <div class="modal-footer border-0">
          <button type="button" class="btn btn-light rounded-pill" data-bs-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-vendor-primary rounded-pill px-4">💾 บันทึก</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function toggleCustomCategory() {
  const catSelect = document.getElementById('prod_cat');
  const customInput = document.getElementById('custom_category_input');
  if (catSelect.value === 'other') {
    customInput.style.display = 'block';
    customInput.setAttribute('required', 'required');
  } else {
    customInput.style.display = 'none';
    customInput.removeAttribute('required');
    customInput.value = '';
  }
}

let selectedFiles = [];

function previewImg(input) {
  if (input.files) {
    for (let i = 0; i < input.files.length; i++) {
        selectedFiles.push(input.files[i]);
    }
  }
  renderPreviews();
}

function renderPreviews() {
  const container = document.getElementById('image_preview_container');
  container.innerHTML = '';
  
  const dt = new DataTransfer();
  selectedFiles.forEach(file => dt.items.add(file));
  document.getElementById('prod_img').files = dt.files;

  selectedFiles.forEach((file, index) => {
    const reader = new FileReader();
    reader.onload = e => {
      const div = document.createElement('div');
      div.className = 'position-relative d-inline-block';
      div.innerHTML = `
        <img src="${e.target.result}" class="rounded-3 shadow-sm border" style="width:100px;height:100px;object-fit:cover;">
        <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 rounded-circle m-1 p-0 d-flex align-items-center justify-content-center" style="width:20px;height:20px;line-height:1;" onclick="removeImage(${index})">&times;</button>
      `;
      container.appendChild(div);
    };
    reader.readAsDataURL(file);
  });
}

function removeImage(index) {
  selectedFiles.splice(index, 1);
  renderPreviews();
}

function resetForm() {
  document.getElementById('modalTitle').textContent = '+ เพิ่มสินค้าใหม่';
  ['prod_id','prod_name','prod_price','prod_nprice','prod_stock','prod_colors','prod_desc','custom_category_input'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.value = '';
  });
  document.querySelectorAll('.size-checkbox').forEach(cb => cb.checked = false);
  document.getElementById('custom_sizes').value = '';
  document.getElementById('prod_status').value = 'active';
  
  selectedFiles = [];
  document.getElementById('prod_img').value = '';
  document.getElementById('image_preview_container').innerHTML = '';
  
  toggleCustomCategory();
}

function openEditModal(p) {
  document.getElementById('modalTitle').textContent = '✏️ แก้ไขสินค้า';
  document.getElementById('prod_id').value      = p.id;
  document.getElementById('prod_name').value    = p.name;
  document.getElementById('prod_cat').value     = p.category_id;
  document.getElementById('prod_vcat').value    = p.vendor_category_id || '';
  document.getElementById('prod_price').value   = p.price;
  document.getElementById('prod_nprice').value  = p.normal_price || '';
  document.getElementById('prod_stock').value   = p.stock || 0;
  
  document.querySelectorAll('.size-checkbox').forEach(cb => cb.checked = false);
  let customSizes = [];
  if(p.sizes) {
      const stdList = ['S','M','L','XL','XXL','oversize'];
      const sizeArr = p.sizes.split(',').map(s => s.trim()).filter(s => s !== '');
      sizeArr.forEach(s => {
          if (stdList.includes(s)) {
              const cb = document.getElementById('size_' + s);
              if(cb) cb.checked = true;
          } else {
              customSizes.push(s);
          }
      });
  }
  document.getElementById('custom_sizes').value = customSizes.join(', ');

  document.getElementById('prod_colors').value  = p.colors || '';
  document.getElementById('prod_desc').value    = p.description || '';
  document.getElementById('prod_status').value  = p.status;
  toggleCustomCategory();
  
  selectedFiles = [];
  document.getElementById('prod_img').value = '';
  const container = document.getElementById('image_preview_container');
  if (p.main_image) {
    container.innerHTML = `
      <div class="position-relative d-inline-block">
        <img src="${p.main_image}" class="rounded-3 shadow-sm border" style="width:100px;height:100px;object-fit:cover;">
      </div>
    `;
  } else {
    container.innerHTML = '';
  }
  
  new bootstrap.Modal(document.getElementById('productModal')).show();
}
</script>

<?php require_once __DIR__ . '/vendor_footer.php'; ?>
