<?php
/**
 * Product Management Page
 * CMTC Shopping
 */
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';

// Auth & Permission Check
require_permission($db, 'manage_products');

$error = "";
$success = "";

// Read flash messages from session
if (!empty($_SESSION['flash_success'])) {
    $success = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}
if (!empty($_SESSION['flash_error'])) {
    $error = $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

// 1. Export CSV Handler
if (isset($_GET['action']) && $_GET['action'] === 'export') {
    $stmt = $db->query("SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.id DESC");
    $prods = $stmt->fetchAll();
    
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="products_export_' . date('Ymd') . '.csv"');
    
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    fputcsv($output, ['ID', 'SKU', 'Barcode', 'Name', 'Category', 'Price', 'Promo Price', 'Status', 'Min Stock']);
    foreach ($prods as $p) {
        fputcsv($output, [
            $p['id'],
            $p['sku'],
            $p['barcode'],
            $p['name'],
            $p['category_name'],
            $p['price'],
            $p['promo_price'],
            $p['status'],
            $p['min_stock']
        ]);
    }
    fclose($output);
    log_activity($db, 'export', 'ส่งออกข้อมูลสินค้าเป็น CSV');
    exit();
}

// 2. Import CSV Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_csv'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['csv_file']['tmp_name'];
        $handle = fopen($file, "r");
        
        $bom = fread($handle, 3);
        if ($bom !== "\xEF\xBB\xBF") {
            rewind($handle);
        }
        fgetcsv($handle);
        
        $imported = 0;
        $db->beginTransaction();
        try {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if (count($data) < 8) continue;
                $sku = trim($data[1]);
                $barcode = trim($data[2]);
                $name = trim($data[3]);
                $price = floatval($data[5]);
                $promo_price = !empty($data[6]) ? floatval($data[6]) : null;
                $status = trim($data[7]) === 'active' ? 'active' : 'inactive';
                $min_stock = intval($data[8] ?? 5);

                $stmt = $db->prepare("
                    INSERT INTO products (sku, barcode, name, price, promo_price, status, min_stock) 
                    VALUES (?, ?, ?, ?, ?, ?, ?) 
                    ON DUPLICATE KEY UPDATE name=?, price=?, promo_price=?, status=?, min_stock=?
                ");
                $stmt->execute([$sku, $barcode, $name, $price, $promo_price, $status, $min_stock, $name, $price, $promo_price, $status, $min_stock]);
                $imported++;
            }
            $db->commit();
            log_activity($db, 'add', "นำเข้าสินค้าผ่าน CSV จำนวน $imported รายการ");
            $success = "นำเข้าข้อมูลสินค้าสำเร็จเรียบร้อยแล้วทั้งหมด $imported รายการ";
        } catch (Exception $e) {
            $db->rollBack();
            $error = "เกิดข้อผิดพลาด: " . $e->getMessage();
        }
        fclose($handle);
    } else {
        $error = "กรุณาเลือกไฟล์ CSV ที่ถูกต้อง";
    }
}

// 2.1 Edit Product Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_product'])) {
    $edit_id = intval($_POST['edit_id']);
    $sku = trim($_POST['sku'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $category_id = intval($_POST['category_id'] ?? 0);
    $price = floatval($_POST['price'] ?? 0);
    $promo_price = !empty($_POST['promo_price']) ? floatval($_POST['promo_price']) : null;
    $min_stock = intval($_POST['min_stock'] ?? 5);
    $status = trim($_POST['status'] ?? 'active');
    $purchase_type = trim($_POST['edit_purchase_type'] ?? 'normal');

    if (empty($name) || $price <= 0) {
        $error = "กรุณากรอกข้อมูลที่จำเป็นให้ครบถ้วน";
    } else {
        try {
            if (empty($sku)) {
                $stmt = $db->prepare("UPDATE products SET name = ?, category_id = ?, price = ?, promo_price = ?, min_stock = ?, status = ?, purchase_type = ? WHERE id = ?");
                $stmt->execute([$name, $category_id ?: null, $price, $promo_price, $min_stock, $status, $purchase_type, $edit_id]);
            } else {
                $stmt = $db->prepare("UPDATE products SET sku = ?, name = ?, category_id = ?, price = ?, promo_price = ?, min_stock = ?, status = ?, purchase_type = ? WHERE id = ?");
                $stmt->execute([$sku, $name, $category_id ?: null, $price, $promo_price, $min_stock, $status, $purchase_type, $edit_id]);
            }

            // Handle multiple product image uploads during edit
            if (isset($_FILES['images']) && is_array($_FILES['images']['name'])) {
                $files = $_FILES['images'];
                $stmt_img = $db->prepare("INSERT INTO product_images (product_id, image_path, is_main) VALUES (?, ?, ?)");
                
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK) {
                        $single_file = [
                            'name' => $files['name'][$i],
                            'type' => $files['type'][$i] ?? '',
                            'tmp_name' => $files['tmp_name'][$i],
                            'error' => $files['error'][$i],
                            'size' => $files['size'][$i]
                        ];
                        
                        $upload_res = upload_image($single_file, 'products', 'prod');
                        if ($upload_res['success']) {
                            $check_main = $db->prepare("SELECT COUNT(*) FROM product_images WHERE product_id = ? AND is_main = 1");
                            $check_main->execute([$edit_id]);
                            $has_main = $check_main->fetchColumn() > 0;
                            $is_main = (!$has_main && $i === 0) ? 1 : 0;
                            
                            $img_save_path = 'uploads/products/' . $upload_res['filename'];
                            $stmt_img->execute([$edit_id, $img_save_path, $is_main]);
                        }
                    }
                }
            }

            log_activity($db, 'edit', "แก้ไขสินค้า ID $edit_id: $name");
            $success = "แก้ไขข้อมูลสินค้าเรียบร้อยแล้ว";
            header("Location: products.php?success=1");
            exit();
        } catch (Exception $e) {
            $error = "เกิดข้อผิดพลาด: " . $e->getMessage();
        }
    }
}

// 3. Add Product Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_product'])) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? '')) {
        $error = "โทเค็นความปลอดภัยไม่ถูกต้อง";
    } else {
        $sku = trim($_POST['sku'] ?? '');
        $name = trim($_POST['name'] ?? '');
        $category_id = intval($_POST['category_id'] ?? 0);
        $price = floatval($_POST['price'] ?? 0);
        $promo_price = !empty($_POST['promo_price']) ? floatval($_POST['promo_price']) : null;
        $min_stock = intval($_POST['min_stock'] ?? 5);
        $description = trim($_POST['description'] ?? '');
        $purchase_type = trim($_POST['purchase_type'] ?? 'normal');
        
        $colors = $_POST['colors'] ?? [];
        $color_qtys = $_POST['color_qtys'] ?? [];

        if (empty($sku)) {
            $sku = 'SKU-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid(rand(), true)), 0, 5));
        }

        // Fetch category name to determine size input style
        $cat_name = '';
        if ($category_id > 0) {
            $stmt_cat = $db->prepare("SELECT name FROM categories WHERE id = ?");
            $stmt_cat->execute([$category_id]);
            $cat_name = $stmt_cat->fetchColumn() ?: '';
        }

        $sizes = [];
        $size_qtys = [];
        $size_images = [];
        if (mb_strpos($cat_name, 'เสื้อ') !== false) {
            $raw_sizes = $_POST['sizes'] ?? [];
            foreach ($raw_sizes as $s) {
                if (empty($s)) continue;
                $trimmed = trim($s);
                $sizes[] = $trimmed;
                $size_qtys[$trimmed] = intval($_POST['size_qty'][$s] ?? 0);
                $size_images[$trimmed] = null;
            }
        } else {
            $custom_sizes = $_POST['custom_sizes'] ?? [];
            $custom_size_qtys = $_POST['custom_size_qtys'] ?? [];
            $custom_files = $_FILES['custom_size_images'] ?? null;
            foreach ($custom_sizes as $idx => $s) {
                if (empty($s)) continue;
                $trimmed = trim($s);
                $sizes[] = $trimmed;
                $size_qtys[$trimmed] = intval($custom_size_qtys[$idx] ?? 0);
                
                $size_image_name = null;
                if ($custom_files && isset($custom_files['error'][$idx]) && $custom_files['error'][$idx] === UPLOAD_ERR_OK) {
                    $single_custom_file = [
                        'name' => $custom_files['name'][$idx],
                        'type' => $custom_files['type'][$idx] ?? '',
                        'tmp_name' => $custom_files['tmp_name'][$idx],
                        'error' => $custom_files['error'][$idx],
                        'size' => $custom_files['size'][$idx]
                    ];
                    $upload_res = upload_image($single_custom_file, 'products', 'sz');
                    if ($upload_res['success']) {
                        $size_image_name = $upload_res['filename'];
                    }
                }
                $size_images[$trimmed] = $size_image_name;
            }
        }

        try {
            $db->beginTransaction();
            
            // Insert product
            $stmt = $db->prepare("
                INSERT INTO products (user_id, category_id, sku, barcode, name, description, price, promo_price, min_stock, status, purchase_type) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?)
            ");
            $stmt->execute([
                $_SESSION['user_id'] ?? null,
                $category_id ?: null,
                $sku,
                $sku,
                $name,
                $description,
                $price,
                $promo_price,
                $min_stock,
                $purchase_type
            ]);
            $product_id = $db->lastInsertId();

            // Insert Colors
            $stmt_color = $db->prepare("INSERT INTO product_colors (product_id, color_name) VALUES (?, ?)");
            $inserted_colors = [];
            $color_stock_map = [];
            foreach ($colors as $c_idx => $c) {
                if (empty($c)) continue;
                $c_trimmed = trim($c);
                $stmt_color->execute([$product_id, $c_trimmed]);
                $inserted_id = $db->lastInsertId();
                $inserted_colors[$c_trimmed] = $inserted_id;
                $color_stock_map[$inserted_id] = intval($color_qtys[$c_idx] ?? 0);
            }

            // Insert Sizes
            $stmt_size = $db->prepare("INSERT INTO product_sizes (product_id, size_name, image_path) VALUES (?, ?, ?)");
            $inserted_sizes = [];
            foreach ($sizes as $s) {
                if (empty($s)) continue;
                $stmt_size->execute([$product_id, trim($s), $size_images[trim($s)] ?? null]);
                $inserted_sizes[trim($s)] = $db->lastInsertId();
            }

            // Insert Stock combinations
            $stmt_stock = $db->prepare("INSERT INTO product_stock (product_id, color_id, size_id, quantity) VALUES (?, ?, ?, ?)");
            $total_color_stock = array_sum($color_stock_map);
            $total_size_stock = array_sum($size_qtys);

            if (empty($inserted_colors) && empty($inserted_sizes)) {
                $stmt_stock->execute([$product_id, null, null, 10]);
            } elseif (empty($inserted_colors)) {
                foreach ($inserted_sizes as $s_name => $s_id) {
                    $qty_for_size = intval($size_qtys[$s_name] ?? 0);
                    $stmt_stock->execute([$product_id, null, $s_id, $qty_for_size]);
                }
            } elseif (empty($inserted_sizes)) {
                foreach ($inserted_colors as $c_name => $c_id) {
                    $qty_for_color = $color_stock_map[$c_id] ?? 0;
                    $stmt_stock->execute([$product_id, $c_id, null, $qty_for_color]);
                }
            } else {
                // Both colors and sizes exist: distribute accurately and consistently
                $num_colors = count($inserted_colors);
                $num_sizes = count($inserted_sizes);

                if ($total_color_stock > 0 && $total_size_stock == 0) {
                    // Distribute each color's stock across sizes
                    foreach ($inserted_colors as $c_name => $c_id) {
                        $c_qty = $color_stock_map[$c_id] ?? 0;
                        $base_qty = intval(floor($c_qty / $num_sizes));
                        $rem = $c_qty % $num_sizes;
                        $s_i = 0;
                        foreach ($inserted_sizes as $s_name => $s_id) {
                            $alloc = $base_qty + ($s_i < $rem ? 1 : 0);
                            $stmt_stock->execute([$product_id, $c_id, $s_id, $alloc]);
                            $s_i++;
                        }
                    }
                } elseif ($total_size_stock > 0 && $total_color_stock == 0) {
                    // Distribute each size's stock across colors
                    foreach ($inserted_sizes as $s_name => $s_id) {
                        $s_qty = intval($size_qtys[$s_name] ?? 0);
                        $base_qty = intval(floor($s_qty / $num_colors));
                        $rem = $s_qty % $num_colors;
                        $c_i = 0;
                        foreach ($inserted_colors as $c_name => $c_id) {
                            $alloc = $base_qty + ($c_i < $rem ? 1 : 0);
                            $stmt_stock->execute([$product_id, $c_id, $s_id, $alloc]);
                            $c_i++;
                        }
                    }
                } elseif ($total_color_stock > 0 && $total_size_stock > 0) {
                    // Both specified: distribute proportionally based on color ratio
                    foreach ($inserted_colors as $c_name => $c_id) {
                        $c_qty = $color_stock_map[$c_id] ?? 0;
                        $ratio = $c_qty / $total_color_stock;
                        foreach ($inserted_sizes as $s_name => $s_id) {
                            $s_qty = intval($size_qtys[$s_name] ?? 0);
                            $alloc = intval(round($s_qty * $ratio));
                            $stmt_stock->execute([$product_id, $c_id, $s_id, $alloc]);
                        }
                    }
                } else {
                    foreach ($inserted_colors as $c_name => $c_id) {
                        foreach ($inserted_sizes as $s_name => $s_id) {
                            $stmt_stock->execute([$product_id, $c_id, $s_id, 0]);
                        }
                    }
                }
            }

            // Handle multiple product image uploads
            if (isset($_FILES['images']) && is_array($_FILES['images']['name'])) {
                $files = $_FILES['images'];
                $stmt_img = $db->prepare("INSERT INTO product_images (product_id, image_path, is_main) VALUES (?, ?, ?)");
                
                $uploaded_count = 0;
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK) {
                        $single_file = [
                            'name' => $files['name'][$i],
                            'type' => $files['type'][$i] ?? '',
                            'tmp_name' => $files['tmp_name'][$i],
                            'error' => $files['error'][$i],
                            'size' => $files['size'][$i]
                        ];
                        
                        $upload_res = upload_image($single_file, 'products', 'prod');
                        if ($upload_res['success']) {
                            $is_main = ($uploaded_count === 0) ? 1 : 0;
                            $img_save_path = 'uploads/products/' . $upload_res['filename'];
                            $stmt_img->execute([$product_id, $img_save_path, $is_main]);
                            $uploaded_count++;
                        }
                    }
                }
            }

            $db->commit();
            log_activity($db, 'add', "เพิ่มสินค้าใหม่ SKU: $sku");
            $success = "เพิ่มสินค้าเรียบร้อยแล้ว";
        } catch (Exception $e) {
            $db->rollBack();
            $error = "เกิดข้อผิดพลาด: " . $e->getMessage();
        }
    }
}

// 4. Delete Product Handler (POST to avoid browser caching)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_product_id'])) {
    $del_id = intval($_POST['delete_product_id']);
    if ($del_id > 0) {
        try {
            $db->beginTransaction();
            foreach (['product_colors', 'product_sizes', 'product_images', 'product_stock'] as $tbl) {
                $db->prepare("DELETE FROM $tbl WHERE product_id = ?")->execute([$del_id]);
            }
            $db->prepare("DELETE FROM order_items WHERE product_id = ?")->execute([$del_id]);
            $db->prepare("DELETE FROM products WHERE id = ?")->execute([$del_id]);
            log_activity($db, 'delete', "ลบสินค้า ID: $del_id");
            $db->commit();
            $_SESSION['flash_success'] = "ลบสินค้า ID $del_id สำเร็จเรียบร้อย";
        } catch (Exception $e) {
            $db->rollBack();
            $_SESSION['flash_error'] = "เกิดข้อผิดพลาด: " . $e->getMessage();
        }
    }
    // Use both header + meta redirect for maximum compatibility
    if (!headers_sent()) {
        header("Location: products.php");
    } else {
        echo "<script>window.location.href='products.php';</script>";
        echo "<meta http-equiv='refresh' content='0;url=products.php'>";
    }
    exit();
}
// Also handle old GET-based delete for backward compat
if (isset($_GET['delete_product_id'])) {
    header("Location: products.php");
    exit();
}

// Fetch categories and products for lists
$categories = $db->query("SELECT * FROM categories ORDER BY name ASC")->fetchAll();
$products = $db->query("
    SELECT p.*, c.name as category_name, 
           (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY is_main DESC, id ASC LIMIT 1) as main_image 
    FROM products p 
    LEFT JOIN categories c ON p.category_id = c.id 
    ORDER BY p.id DESC
")->fetchAll();
?>

<div class="d-flex">
    <?php require_once __DIR__ . '/../includes/sidebar.php'; ?>

    <main class="flex-grow-1 p-4" style="background-color: var(--bs-body-bg);">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="fw-bold mb-0"><i class="bi bi-box-seam-fill text-primary me-2"></i>จัดการสินค้า</h3>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item"><a href="dashboard.php">แดชบอร์ด</a></li>
                        <li class="breadcrumb-item active" aria-current="page">จัดการสินค้า</li>
                    </ol>
                </nav>
            </div>
            <div class="d-flex gap-2">
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProductModal">
                    <i class="bi bi-plus-circle me-1"></i> เพิ่มสินค้าใหม่
                </button>
                <button class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#importModal">
                    <i class="bi bi-file-earmark-spreadsheet me-1"></i> นำเข้า Excel/CSV
                </button>
                <a href="products.php?action=export" class="btn btn-outline-primary">
                    <i class="bi bi-download me-1"></i> ส่งออกข้อมูลสินค้า
                </a>
            </div>
        </div>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger mb-4"><?php echo $error; ?></div>
        <?php endif; ?>
        <?php if (!empty($success) || isset($_GET['success'])): ?>
            <div class="alert alert-success mb-4"><?php echo !empty($success) ? $success : 'ดำเนินการสำเร็จ'; ?></div>
        <?php endif; ?>

        <!-- Products Table Card -->
        <div class="card border-0 shadow-sm glass-card p-4">
            <div class="table-responsive">
                <table class="table table-hover align-middle datatable">
                    <thead>
                        <tr>
                            <th>รูปสินค้า</th>
                            <th>SKU</th>
                            <th>ชื่อสินค้า</th>
                            <th>หมวดหมู่</th>
                            <th>ราคาปกติ</th>
                            <th>ราคาโปรโมชั่น</th>
                            <th>สถานะ</th>
                            <th class="text-center">จัดการ</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $p): ?>
                            <tr>
                                <td>
                                    <?php 
                                    $img_src = !empty($p['main_image']) ? product_image_url($p['main_image']) : base_url('assets/images/no-image.png');
                                    ?>
                                    <img src="<?php echo $img_src; ?>" class="rounded shadow-xs border" width="50" height="50" style="object-fit: cover;" onerror="this.onerror=null; this.src='<?php echo base_url('assets/images/no-image.png'); ?>';">
                                </td>
                                <td><code class="fw-bold"><?php echo sanitize($p['sku']); ?></code></td>
                                <td class="fw-semibold"><?php echo sanitize($p['name']); ?></td>
                                <td><?php echo sanitize($p['category_name'] ?? 'ไม่มีหมวดหมู่'); ?></td>
                                <td><?php echo format_price($p['price']); ?></td>
                                <td class="text-danger fw-bold"><?php echo $p['promo_price'] ? format_price($p['promo_price']) : '-'; ?></td>
                                <td>
                                    <span class="badge bg-<?php echo $p['status'] === 'active' ? 'success' : 'secondary'; ?>">
                                        <?php echo $p['status'] === 'active' ? 'เปิดขาย' : 'ปิดการขาย'; ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <button class="btn btn-sm btn-outline-primary me-1 btn-edit-product"
                                            data-id="<?php echo $p['id']; ?>"
                                            data-sku="<?php echo sanitize($p['sku']); ?>"
                                            data-name="<?php echo sanitize($p['name']); ?>"
                                            data-category="<?php echo $p['category_id']; ?>"
                                            data-price="<?php echo $p['price']; ?>"
                                            data-promo="<?php echo $p['promo_price']; ?>"
                                            data-min="<?php echo $p['min_stock']; ?>"
                                            data-status="<?php echo $p['status']; ?>"
                                            data-purchase-type="<?php echo sanitize($p['purchase_type']); ?>"
                                            data-bs-toggle="modal" 
                                            data-bs-target="#editProductModal">
                                        <i class="bi bi-pencil-square"></i> แก้ไข
                                    </button>
                                    <a href="products.php?delete_product_id=<?php echo $p['id']; ?>" 
                                       class="btn btn-sm btn-outline-danger" 
                                       onclick="return confirm('แน่ใจใช่หรือไม่ว่าต้องการลบสินค้าชิ้นนี้?');"
                                       style="display:none">
                                        ลบ (GET)
                                    </a>
                                    <form method="POST" action="products.php" style="display:inline" 
                                          onsubmit="return confirm('แน่ใจใช่หรือไม่ ว่าต้องการลบสินค้าชิ้นนี้?');">
                                        <input type="hidden" name="delete_product_id" value="<?php echo $p['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger">
                                            <i class="bi bi-trash"></i> ลบ
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

<!-- Add Product Modal -->
<div class="modal fade" id="addProductModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-plus-circle-fill text-primary"></i> เพิ่มสินค้าใหม่เข้าระบบ</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="name" class="form-label">ชื่อสินค้า *</label>
                            <input type="text" name="name" id="name" class="form-control" required placeholder="เช่น เสื้อช็อปแผนกเทคนิคคอมพิวเตอร์">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="category_id" class="form-label">หมวดหมู่สินค้า (ไม่บังคับ)</label>
                            <select name="category_id" id="category_id" class="form-select">
                                <option value="">-- เลือกหมวดหมู่ --</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>"><?php echo sanitize($cat['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label for="price" class="form-label">ราคาปกติ *</label>
                            <input type="number" step="0.01" name="price" id="price" class="form-control" required placeholder="0.00">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label for="promo_price" class="form-label">ราคาโปรโมชั่น (ไม่บังคับ)</label>
                            <input type="number" step="0.01" name="promo_price" id="promo_price" class="form-control" placeholder="0.00">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label d-block fw-bold">รูปแบบการขาย *</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="purchase_type" id="purchase_type_normal" value="normal" checked>
                            <label class="form-check-label fw-semibold text-success" for="purchase_type_normal">ซื้อสินค้าปกติ (Normal Purchase)</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="purchase_type" id="purchase_type_booking" value="booking">
                            <label class="form-check-label fw-semibold text-primary" for="purchase_type_booking">เปิดจองสินค้า (Pre-order / Booking)</label>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="description" class="form-label">รายละเอียดสินค้า</label>
                        <textarea name="description" id="description" class="form-control" rows="3" placeholder="ระบุรายละเอียดสินค้า สเปค ข้อมูลเสื้อผ้า หรือคำแนะนำเพิ่มเติม"></textarea>
                    </div>

                    <!-- Colors Section -->
                    <div class="mb-3">
                        <label class="form-label d-block fw-bold">สีของสินค้า (ระบุสีและจำนวนสต๊อก)</label>
                        <div class="d-flex flex-column gap-2 mb-2" id="color-inputs">
                            <div class="d-flex align-items-center gap-2 color-row">
                                <input type="text" name="colors[]" class="form-control form-control-sm w-50" placeholder="ระบุชื่อสี เช่น สีดำ">
                                <input type="number" name="color_qtys[]" class="form-control form-control-sm" style="width: 120px;" placeholder="จำนวน (ชิ้น)" min="0" value="0">
                            </div>
                            <div class="d-flex align-items-center gap-2 color-row">
                                <input type="text" name="colors[]" class="form-control form-control-sm w-50" placeholder="ระบุชื่อสี เช่น สีขาว">
                                <input type="number" name="color_qtys[]" class="form-control form-control-sm" style="width: 120px;" placeholder="จำนวน (ชิ้น)" min="0" value="0">
                            </div>
                            <div class="d-flex align-items-center gap-2 color-row">
                                <input type="text" name="colors[]" class="form-control form-control-sm w-50" placeholder="ระบุชื่อสี เช่น สีกรม">
                                <input type="number" name="color_qtys[]" class="form-control form-control-sm" style="width: 120px;" placeholder="จำนวน (ชิ้น)" min="0" value="0">
                            </div>
                            <div class="d-flex align-items-center gap-2 color-row">
                                <input type="text" name="colors[]" class="form-control form-control-sm w-50" placeholder="ระบุชื่อสี เช่น สีไข่">
                                <input type="number" name="color_qtys[]" class="form-control form-control-sm" style="width: 120px;" placeholder="จำนวน (ชิ้น)" min="0" value="0">
                            </div>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="addNewColorField()"><i class="bi bi-plus-circle"></i> เพิ่มช่องระบุสี</button>
                    </div>

                    <!-- Clothing Size Checkboxes -->
                    <div class="mb-3 clothing-size-section">
                        <label class="form-label">ไซส์/ขนาดสินค้า (และระบุสต๊อกเริ่มต้นของแต่ละไซส์)</label>
                        <div class="row g-2">
                            <?php 
                            $available_sizes = ['XS', 'S', 'M', 'L', 'XL', '2XL', '3XL', '4XL', '5XL', 'Free Size'];
                            foreach ($available_sizes as $sz):
                            ?>
                                <div class="col-6 col-sm-4 col-md-3">
                                    <div class="card p-2 border-light shadow-xs bg-body-tertiary">
                                        <div class="form-check mb-1">
                                            <input class="form-check-input size-checkbox" type="checkbox" name="sizes[]" value="<?php echo $sz; ?>" id="size_<?php echo $sz; ?>">
                                            <label class="form-check-label fw-bold text-primary" for="size_<?php echo $sz; ?>"><?php echo $sz; ?></label>
                                        </div>
                                        <div class="size-qty-wrapper" style="display: none;">
                                            <input type="number" name="size_qty[<?php echo $sz; ?>]" class="form-control form-control-sm" placeholder="จำนวนคลัง" min="0" value="0">
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Custom Size Section (for Souvenir / General Goods) -->
                    <div class="mb-3 custom-size-section" style="display: none;">
                        <label class="form-label d-block fw-bold">ขนาด / ตัวเลือกสินค้า (สำหรับของที่ระลึกและของทั่วไป)</label>
                        <div class="d-flex flex-column gap-2 mb-2" id="custom-size-inputs-add">
                            <div class="d-flex align-items-center gap-2 custom-size-row">
                                <input type="text" name="custom_sizes[]" class="form-control form-control-sm w-40" placeholder="เช่น แก้ว, พวงกุญแจ, 7 นิ้ว">
                                <input type="number" name="custom_size_qtys[]" class="form-control form-control-sm" style="width: 100px;" placeholder="จำนวนคลัง" min="0" value="0">
                                <div class="d-flex align-items-center gap-1">
                                    <i class="bi bi-image text-muted small"></i>
                                    <input type="file" name="custom_size_images[]" class="form-control form-control-sm" style="width: 160px;" accept="image/*">
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="addNewCustomSizeField('add')"><i class="bi bi-plus-circle"></i> เพิ่มขนาด/ตัวเลือกสินค้า</button>
                    </div>

                    <!-- Stock Sync & Summary Card -->
                    <div class="card border-0 bg-primary-subtle p-3 mb-3 rounded-3" id="stock-sync-card">
                        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <div>
                                <div class="fw-bold text-primary mb-0"><i class="bi bi-box-seam-fill me-1"></i> รวมสต็อกสินค้าทั้งหมด: <span id="total-stock-count" class="fs-5 fw-bold text-dark">0</span> ชิ้น</div>
                                <small class="text-muted d-block" id="stock-breakdown-text">จากสี: 0 ชิ้น | จากขนาด/ตัวเลือก: 0 ชิ้น</small>
                            </div>
                            <div class="d-flex gap-1">
                                <button type="button" class="btn btn-sm btn-primary" id="btn-sync-to-sizes" title="กระจายสต็อกรวมจากสีไปยังขนาด/ตัวเลือกเท่าๆ กัน">
                                    <i class="bi bi-arrow-down-up me-1"></i> ซิงค์สต็อกสีไปยังตัวเลือก
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="btn-sync-to-colors" title="กระจายสต็อกรวมจากขนาด/ตัวเลือกไปยังสีเท่าๆ กัน">
                                    <i class="bi bi-arrow-up-down me-1"></i> ซิงค์สต็อกตัวเลือกไปยังสี
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="min_stock" class="form-label">ระดับแจ้งเตือนคลังสินค้าขั้นต่ำ *</label>
                        <input type="number" name="min_stock" id="min_stock" class="form-control" value="5" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold"><i class="bi bi-images me-1 text-primary"></i>อัปโหลดรูปภาพสินค้า (สูงสุด 5 รูป)</label>
                        <div class="row g-2">
                            <div class="col-12 mb-2">
                                <label class="form-label small text-muted mb-1">รูปภาพที่ 1 (รูปภาพหลัก) *</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#add_img_prev_0">
                                <div id="add_img_prev_0" class="mt-1 d-none"><img src="" class="rounded border" style="width: 70px; height: 70px; object-fit: cover;"></div>
                            </div>
                            <div class="col-6 col-sm-3">
                                <label class="form-label small text-muted mb-1">รูปภาพที่ 2</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#add_img_prev_1">
                                <div id="add_img_prev_1" class="mt-1 d-none"><img src="" class="rounded border" style="width: 60px; height: 60px; object-fit: cover;"></div>
                            </div>
                            <div class="col-6 col-sm-3">
                                <label class="form-label small text-muted mb-1">รูปภาพที่ 3</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#add_img_prev_2">
                                <div id="add_img_prev_2" class="mt-1 d-none"><img src="" class="rounded border" style="width: 60px; height: 60px; object-fit: cover;"></div>
                            </div>
                            <div class="col-6 col-sm-3">
                                <label class="form-label small text-muted mb-1">รูปภาพที่ 4</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#add_img_prev_3">
                                <div id="add_img_prev_3" class="mt-1 d-none"><img src="" class="rounded border" style="width: 60px; height: 60px; object-fit: cover;"></div>
                            </div>
                            <div class="col-6 col-sm-3">
                                <label class="form-label small text-muted mb-1">รูปภาพที่ 5</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#add_img_prev_4">
                                <div id="add_img_prev_4" class="mt-1 d-none"><img src="" class="rounded border" style="width: 60px; height: 60px; object-fit: cover;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">ยกเลิก</button>
                    <button type="submit" name="add_product" class="btn btn-primary">เพิ่มสินค้าเข้าสต๊อก</button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Import Excel/CSV Modal -->
<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" enctype="multipart/form-data">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-file-earmark-spreadsheet-fill text-success"></i> นำเข้าข้อมูลสินค้า</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p class="text-muted small">กรุณาเลือกไฟล์รูปแบบ CSV โครงสร้างหลักประกอบด้วยหัวคอลัมน์: ID, SKU, Barcode, Name, Category, Price, Promo Price, Status, Min Stock</p>
                    <div class="mb-3">
                        <label for="csv_file" class="form-label">เลือกไฟล์ CSV *</label>
                        <input type="file" name="csv_file" id="csv_file" class="form-control" accept=".csv" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">ยกเลิก</button>
                    <button type="submit" name="import_csv" class="btn btn-success">นำเข้าข้อมูล</button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Edit Product Modal -->
<div class="modal fade" id="editProductModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="POST" enctype="multipart/form-data">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-pencil-square text-primary"></i> แก้ไขข้อมูลสินค้า</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="edit_id" id="edit_id">
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="edit_name" class="form-label">ชื่อสินค้า *</label>
                            <input type="text" name="name" id="edit_name" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="edit_category_id" class="form-label">หมวดหมู่สินค้า (ไม่บังคับ)</label>
                            <select name="category_id" id="edit_category_id" class="form-select">
                                <option value="">-- เลือกหมวดหมู่ --</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>"><?php echo sanitize($cat['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label for="edit_price" class="form-label">ราคาปกติ *</label>
                            <input type="number" step="0.01" name="price" id="edit_price" class="form-control" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label for="edit_promo_price" class="form-label">ราคาโปรโมชั่น (ไม่บังคับ)</label>
                            <input type="number" step="0.01" name="promo_price" id="edit_promo_price" class="form-control">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="edit_min_stock" class="form-label">ระดับแจ้งเตือนคลังสินค้าขั้นต่ำ *</label>
                            <input type="number" name="min_stock" id="edit_min_stock" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="edit_status" class="form-label">สถานะการขาย *</label>
                            <select name="status" id="edit_status" class="form-select" required>
                                <option value="active">เปิดขาย (Active)</option>
                                <option value="inactive">ปิดการขาย (Inactive)</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label d-block fw-bold">รูปแบบการขาย *</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="edit_purchase_type" id="edit_purchase_type_normal" value="normal">
                            <label class="form-check-label fw-semibold text-success" for="edit_purchase_type_normal">ซื้อสินค้าปกติ (Normal Purchase)</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="edit_purchase_type" id="edit_purchase_type_booking" value="booking">
                            <label class="form-check-label fw-semibold text-primary" for="edit_purchase_type_booking">เปิดจองสินค้า (Pre-order / Booking)</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold"><i class="bi bi-images me-1 text-primary"></i>อัปโหลดรูปภาพสินค้าเพิ่มเติม (สูงสุด 5 รูป)</label>
                        <div class="row g-2">
                            <div class="col-6 col-sm-4 col-md-2">
                                <label class="form-label small text-muted mb-1">รูปใหม่ 1</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#edit_img_prev_0">
                                <div id="edit_img_prev_0" class="mt-1 d-none"><img src="" class="rounded border" style="width: 55px; height: 55px; object-fit: cover;"></div>
                            </div>
                            <div class="col-6 col-sm-4 col-md-2">
                                <label class="form-label small text-muted mb-1">รูปใหม่ 2</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#edit_img_prev_1">
                                <div id="edit_img_prev_1" class="mt-1 d-none"><img src="" class="rounded border" style="width: 55px; height: 55px; object-fit: cover;"></div>
                            </div>
                            <div class="col-6 col-sm-4 col-md-2">
                                <label class="form-label small text-muted mb-1">รูปใหม่ 3</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#edit_img_prev_2">
                                <div id="edit_img_prev_2" class="mt-1 d-none"><img src="" class="rounded border" style="width: 55px; height: 55px; object-fit: cover;"></div>
                            </div>
                            <div class="col-6 col-sm-4 col-md-2">
                                <label class="form-label small text-muted mb-1">รูปใหม่ 4</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#edit_img_prev_3">
                                <div id="edit_img_prev_3" class="mt-1 d-none"><img src="" class="rounded border" style="width: 55px; height: 55px; object-fit: cover;"></div>
                            </div>
                            <div class="col-6 col-sm-4 col-md-2">
                                <label class="form-label small text-muted mb-1">รูปใหม่ 5</label>
                                <input type="file" name="images[]" class="form-control form-control-sm img-preview-input" accept="image/*" data-preview="#edit_img_prev_4">
                                <div id="edit_img_prev_4" class="mt-1 d-none"><img src="" class="rounded border" style="width: 55px; height: 55px; object-fit: cover;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">ยกเลิก</button>
                    <button type="submit" name="edit_product" class="btn btn-primary">บันทึกการแก้ไข</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function addNewColorField() {
    $('#color-inputs').append(`
        <div class="d-flex align-items-center gap-2 mt-2 color-row">
            <input type="text" name="colors[]" class="form-control form-control-sm w-50" placeholder="ระบุชื่อสีเพิ่มเติม">
            <input type="number" name="color_qtys[]" class="form-control form-control-sm" style="width: 120px;" placeholder="จำนวน (ชิ้น)" min="0" value="0">
        </div>
    `);
}

function addNewCustomSizeField(type) {
    var containerId = type === 'add' ? '#custom-size-inputs-add' : '#custom-size-inputs-edit';
    $(containerId).append(`
        <div class="d-flex align-items-center gap-2 mt-2 custom-size-row">
            <input type="text" name="custom_sizes[]" class="form-control form-control-sm w-40" placeholder="ชื่อขนาด/ตัวเลือกเพิ่มเติม">
            <input type="number" name="custom_size_qtys[]" class="form-control form-control-sm" style="width: 100px;" placeholder="จำนวนคลัง" min="0" value="0">
            <div class="d-flex align-items-center gap-1">
                <i class="bi bi-image text-muted small"></i>
                <input type="file" name="custom_size_images[]" class="form-control form-control-sm" style="width: 160px;" accept="image/*">
            </div>
        </div>
    `);
}

function handleCategoryChange(selectSelector, modalSelector) {
    var selectedText = $(selectSelector + ' option:selected').text();
    var clothingSection = $(modalSelector + ' .clothing-size-section');
    var customSection = $(modalSelector + ' .custom-size-section');

    if (selectedText.indexOf('เสื้อ') !== -1) {
        clothingSection.show();
        customSection.hide();
    } else {
        clothingSection.hide();
        customSection.show();
    }
    updateStockCalculation();
}

function updateStockCalculation() {
    var totalColor = 0;
    var filledColors = 0;
    $('#color-inputs .color-row').each(function() {
        var name = $(this).find('input[name="colors[]"]').val().trim();
        var q = parseInt($(this).find('input[name="color_qtys[]"]').val()) || 0;
        if (name !== '') {
            filledColors++;
            totalColor += q;
        }
    });

    var totalSize = 0;
    var filledSizes = 0;
    var isClothing = $('#addProductModal .clothing-size-section').is(':visible');

    if (isClothing) {
        $('.size-checkbox:checked').each(function() {
            var szVal = $(this).val();
            var q = parseInt($('input[name="size_qty[' + szVal + ']"]').val()) || 0;
            filledSizes++;
            totalSize += q;
        });
    } else {
        $('#custom-size-inputs-add .custom-size-row').each(function() {
            var name = $(this).find('input[name="custom_sizes[]"]').val().trim();
            var q = parseInt($(this).find('input[name="custom_size_qtys[]"]').val()) || 0;
            if (name !== '') {
                filledSizes++;
                totalSize += q;
            }
        });
    }

    var displayTotal = 0;
    if (filledColors > 0 && filledSizes > 0) {
        // If both exist, display the maximum or aligned total
        displayTotal = Math.max(totalColor, totalSize);
    } else if (filledColors > 0) {
        displayTotal = totalColor;
    } else if (filledSizes > 0) {
        displayTotal = totalSize;
    }

    $('#total-stock-count').text(displayTotal.toLocaleString());
    $('#stock-breakdown-text').html(`สต็อกรวมจากสี: <strong>${totalColor}</strong> ชิ้น | สต็อกรวมจากขนาด/ตัวเลือก: <strong>${totalSize}</strong> ชิ้น`);

    if (filledColors > 0 && filledSizes > 0 && totalColor !== totalSize) {
        $('#stock-breakdown-text').addClass('text-danger fw-bold').removeClass('text-muted');
    } else {
        $('#stock-breakdown-text').removeClass('text-danger fw-bold').addClass('text-muted');
    }
}

$(document).ready(function() {
    $('#category_id').on('change', function() {
        handleCategoryChange('#category_id', '#addProductModal');
    });
    $('#addProductModal').on('shown.bs.modal', function () {
        handleCategoryChange('#category_id', '#addProductModal');
        updateStockCalculation();
    });

    $('#edit_category_id').on('change', function() {
        handleCategoryChange('#edit_category_id', '#editProductModal');
    });

    // Color qty changes
    $(document).on('input change', 'input[name="colors[]"], input[name="color_qtys[]"]', function() {
        var totalColor = 0;
        $('#color-inputs .color-row').each(function() {
            var name = $(this).find('input[name="colors[]"]').val().trim();
            var q = parseInt($(this).find('input[name="color_qtys[]"]').val()) || 0;
            if (name !== '') totalColor += q;
        });

        // Auto-sync if only 1 custom size exists
        var customRows = $('#custom-size-inputs-add .custom-size-row');
        if (customRows.length === 1 && customRows.find('input[name="custom_sizes[]"]').val().trim() !== '') {
            customRows.find('input[name="custom_size_qtys[]"]').val(totalColor);
        }

        // Auto-sync if only 1 clothing size is checked
        var checkedSizes = $('.size-checkbox:checked');
        if (checkedSizes.length === 1) {
            $('input[name="size_qty[' + checkedSizes.val() + ']"]').val(totalColor);
        }

        updateStockCalculation();
    });

    // Custom size changes
    $(document).on('input change', 'input[name="custom_sizes[]"], input[name="custom_size_qtys[]"]', function() {
        var totalCustom = 0;
        $('#custom-size-inputs-add .custom-size-row').each(function() {
            var name = $(this).find('input[name="custom_sizes[]"]').val().trim();
            var q = parseInt($(this).find('input[name="custom_size_qtys[]"]').val()) || 0;
            if (name !== '') totalCustom += q;
        });

        // Auto-sync if only 1 color is entered
        var activeColors = $('#color-inputs .color-row').filter(function() {
            return $(this).find('input[name="colors[]"]').val().trim() !== '';
        });
        if (activeColors.length === 1) {
            activeColors.find('input[name="color_qtys[]"]').val(totalCustom);
        }

        updateStockCalculation();
    });

    // Clothing size changes
    $('.size-checkbox').on('change', function() {
        var wrapper = $(this).closest('.card').find('.size-qty-wrapper');
        if (this.checked) {
            wrapper.slideDown(200);
            if (parseInt(wrapper.find('input').val()) <= 0) {
                wrapper.find('input').val(10);
            }
        } else {
            wrapper.slideUp(200);
            wrapper.find('input').val(0);
        }
        updateStockCalculation();
    });

    $(document).on('input change', 'input[name^="size_qty"]', function() {
        updateStockCalculation();
    });

    // Sync button: Colors to Sizes/Options
    $('#btn-sync-to-sizes').on('click', function() {
        var totalColor = 0;
        $('#color-inputs .color-row').each(function() {
            var name = $(this).find('input[name="colors[]"]').val().trim();
            var q = parseInt($(this).find('input[name="color_qtys[]"]').val()) || 0;
            if (name !== '') totalColor += q;
        });

        var isClothing = $('#addProductModal .clothing-size-section').is(':visible');
        if (isClothing) {
            var checked = $('.size-checkbox:checked');
            if (checked.length > 0) {
                var perSize = Math.floor(totalColor / checked.length);
                var rem = totalColor % checked.length;
                checked.each(function(idx) {
                    var extra = idx < rem ? 1 : 0;
                    $('input[name="size_qty[' + $(this).val() + ']"]').val(perSize + extra);
                });
            }
        } else {
            var rows = $('#custom-size-inputs-add .custom-size-row').filter(function() {
                return $(this).find('input[name="custom_sizes[]"]').val().trim() !== '';
            });
            if (rows.length > 0) {
                var perRow = Math.floor(totalColor / rows.length);
                var rem = totalColor % rows.length;
                rows.each(function(idx) {
                    var extra = idx < rem ? 1 : 0;
                    $(this).find('input[name="custom_size_qtys[]"]').val(perRow + extra);
                });
            }
        }
        updateStockCalculation();
    });

    // Sync button: Sizes/Options to Colors
    $('#btn-sync-to-colors').on('click', function() {
        var totalSize = 0;
        var isClothing = $('#addProductModal .clothing-size-section').is(':visible');

        if (isClothing) {
            $('.size-checkbox:checked').each(function() {
                var q = parseInt($('input[name="size_qty[' + $(this).val() + ']"]').val()) || 0;
                totalSize += q;
            });
        } else {
            $('#custom-size-inputs-add .custom-size-row').each(function() {
                var name = $(this).find('input[name="custom_sizes[]"]').val().trim();
                var q = parseInt($(this).find('input[name="custom_size_qtys[]"]').val()) || 0;
                if (name !== '') totalSize += q;
            });
        }

        var activeColors = $('#color-inputs .color-row').filter(function() {
            return $(this).find('input[name="colors[]"]').val().trim() !== '';
        });
        if (activeColors.length > 0) {
            var perColor = Math.floor(totalSize / activeColors.length);
            var rem = totalSize % activeColors.length;
            activeColors.each(function(idx) {
                var extra = idx < rem ? 1 : 0;
                $(this).find('input[name="color_qtys[]"]').val(perColor + extra);
            });
        }
        updateStockCalculation();
    });

    $('.btn-edit-product').on('click', function() {
        $('#edit_id').val($(this).data('id'));
        $('#edit_sku').val($(this).data('sku'));
        $('#edit_name').val($(this).data('name'));
        $('#edit_category_id').val($(this).data('category'));
        $('#edit_price').val($(this).data('price'));
        $('#edit_promo_price').val($(this).data('promo'));
        $('#edit_min_stock').val($(this).data('min'));
        $('#edit_status').val($(this).data('status'));
        
        var pType = $(this).data('purchase-type') || 'normal';
        $('input[name="edit_purchase_type"][value="' + pType + '"]').prop('checked', true);

        setTimeout(function() {
            handleCategoryChange('#edit_category_id', '#editProductModal');
        }, 150);
    });

    // Image Preview Handler
    $('.img-preview-input').on('change', function(e) {
        var previewTarget = $(this).data('preview');
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = function(evt) {
                $(previewTarget).find('img').attr('src', evt.target.result);
                $(previewTarget).removeClass('d-none');
            };
            reader.readAsDataURL(this.files[0]);
        } else {
            $(previewTarget).addClass('d-none');
        }
    });

    $('#addProductModal, #editProductModal').on('hidden.bs.modal', function () {
        $(this).find('.img-preview-input').val('');
        $(this).find('[id$="_prev_0"], [id$="_prev_1"], [id$="_prev_2"], [id$="_prev_3"], [id$="_prev_4"]').addClass('d-none').find('img').attr('src', '');
    });
});
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
