<?php
include 'inc/header.php';


$id = (int)$_GET['id'];

$product = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT * FROM products WHERE id = $id
"));

if(!$product){
    die("Product not found");
}

$variants = mysqli_query($conn,"
    SELECT * FROM product_variants WHERE product_id = $id
");

$addons = mysqli_query($conn,"
    SELECT * FROM product_addons WHERE product_id = $id
");

$gallery = mysqli_query($conn,"
    SELECT * FROM product_images
    WHERE product_id = $id
");


$sortingSelected = [];
$sortRes = mysqli_query($conn,"
    SELECT sorting_option_id 
    FROM product_sorting_map 
    WHERE product_id = $id
");
while($s = mysqli_fetch_assoc($sortRes)){
    $sortingSelected[] = $s['sorting_option_id'];
}
?>
<style>
body {
    background: #f6f7f9;
}

.card {
    border-radius: 12px;
}

.variant-row,
.addon-row {
    background: #fafafa;
    border: 1px dashed #ddd;
    border-radius: 10px;
    padding: 12px;
    margin-bottom: 10px;
}

.remove-btn {
    cursor: pointer;
    color: #dc3545;
    font-weight: 600;
}
</style>
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-secondary">Edit Product</h6>
    </div>

    <div class="container my-4">

        <form id="productForm" enctype="multipart/form-data">

            <input type="hidden" name="id" value="<?= $product['id'] ?>">

            <!-- BASIC INFO -->
            <div class="card mb-3">
                <div class="card-body">
                    <h5>Basic Information</h5>

                   <div class="row">

    <div class="col-md-4">
        <label>Product Name</label>
        <input type="text"
               name="name"
               class="form-control"
               value="<?= htmlspecialchars($product['name']) ?>"
               required>
    </div>

  <div class="col-md-4">
    <label>Category</label>
    <select name="category_id" id="categorySelect" class="form-control" required>
        <option value="">Select Category</option>
    </select>
</div>

<div class="col-md-4">
    <label>Subcategory</label>
    <select name="subcategory_id" id="subcategorySelect" class="form-control">
        <option value="">Select Subcategory</option>
    </select>
</div>

  

</div>


                    <div class="mt-3">
                        <label>Description</label>
                        <textarea name="description"
                            class="form-control"><?= htmlspecialchars($product['description']) ?></textarea>
                    </div>

                    <div class="row mt-3">
                          <div class="col-md-4">
        <label>Base Price</label>
        <input type="number"
               step="0.01"
               name="base_price"
               class="form-control"
               value="<?= (float)$product['base_price'] ?>"
               placeholder="Used if no variants">
    </div>
                        <div class="col-md-4">
                            <label>Featured Image</label>
                            <br>
                            <?php if($product['featured_image']){ ?>
                            <img src="uploads/products/<?= $product['featured_image'] ?>" width="120" class="mb-2">
                            <?php } ?>
                            <input type="file" name="featured_image" class="form-control">
                        </div>

                        <div class="col-md-4">
                            <label>Add Gallery Images</label>

                            <!-- EXISTING IMAGES -->
                            <!-- EXISTING IMAGES -->
<div class="mb-2 d-flex flex-wrap" id="galleryExisting">

<?php while($g = mysqli_fetch_assoc($gallery)){ ?>
    <div class="gallery-item" data-id="<?= $g['id'] ?>" style="margin:5px; position:relative;">
        
        <img src="uploads/products/<?= $g['image'] ?>" width="90"
             style="border-radius:8px;border:1px solid #ddd;padding:4px;">

        <!-- ❌ REMOVE BUTTON -->
        <span class="img-remove-btn"
              style="position:absolute;top:-6px;right:-6px;
                     background:#dc3545;color:#fff;
                     width:22px;height:22px;
                     border-radius:50%;
                     font-size:14px;
                     display:flex;align-items:center;justify-content:center;
                     cursor:pointer;">×</span>

        <!-- hidden input to keep existing -->
        <input type="hidden" name="existing_images[]" value="<?= $g['id'] ?>">
    </div>
<?php } ?>

</div>



                            <input type="file" name="gallery_images[]" class="form-control" multiple>
                        </div>

                    </div>

                    <div class="form-check mt-3">
                        <input type="checkbox" name="requires_machinery" value="1"
                            <?= $product['requires_machinery']?'checked':'' ?>>
                        <label>Requires Machinery</label>
                    </div>

                    <div class="form-check">
                        <input type="checkbox" name="no_sorting" value="1" <?= $product['no_sorting']?'checked':'' ?>>
                        <label>No Sorting</label>
                    </div>

                </div>
            </div>

            <!-- SORTING -->
            <div class="card mb-3">
                <div class="card-body">
                    <h5>Sorting Options</h5>
                    <div id="sortingContainer" class="row"></div>
                </div>
            </div>

            <!-- VARIANTS -->
            <div class="card mb-3">
                <div class="card-body">
                    <h5>Product Variants</h5>
                    <div id="variantsContainer">
                        <?php while($v = mysqli_fetch_assoc($variants)){ ?>
                       <div class="variant-row row">

    <div class="col-md-3">
        <select name="variant_group_id[]" 
                class="form-control gv-dropdown"
                data-selected="<?= $v['variant_group_id'] ?>">
            <option value="">Select Group</option>
        </select>
    </div>

    <div class="col-md-2">
        <input type="text" name="variant_label[]" 
               class="form-control"
               value="<?= htmlspecialchars($v['label']) ?>">
    </div>

    <div class="col-md-2">
        <input type="number" name="variant_price[]" 
               class="form-control"
               value="<?= $v['price'] ?>">
    </div>

   <div class="col-md-2">
    <select name="variant_unit[]" class="form-control">
        <option value="TON" <?= $v['unit']=='TON'?'selected':'' ?>>TON</option>
        <option value="YARD" <?= $v['unit']=='YARD'?'selected':'' ?>>YARD</option>
        <option value="EACH" <?= $v['unit']=='EACH'?'selected':'' ?>>EACH</option>
        <option value="PIECE" <?= $v['unit']=='PIECE'?'selected':'' ?>>PIECE</option>
        <option value="SQFT" <?= $v['unit']=='SQFT'?'selected':'' ?>>SQFT</option>
        <option value="LNFT" <?= $v['unit']=='LNFT'?'selected':'' ?>>LNFT</option>
    </select>
</div>

    <div class="col-md-3">
        <span onclick="this.closest('.variant-row').remove()" 
              class="remove-btn">Remove</span>
    </div>

</div>

                        <?php } ?>
                    </div>
                    <button type="button" onclick="addVariant()" class="btn btn-sm btn-secondary">
                        + Add Variant
                    </button>
                </div>
            </div>

            <!-- ADDONS -->
            <div class="card mb-3">
                <div class="card-body">
                    <h5>Addons</h5>
                    <div id="addonsContainer">
                        <?php while($a = mysqli_fetch_assoc($addons)){ ?>
                        <div class="addon-row row">
                            <div class="col-md-4">
                                <input type="text" name="addon_name[]" class="form-control" value="<?= $a['name'] ?>">
                            </div>
                            <div class="col-md-3">
                                <input type="number" name="addon_price[]" class="form-control"
                                    value="<?= $a['price'] ?>">
                            </div>
                            <div class="col-md-3">
                                <input type="text" name="addon_unit[]" class="form-control" value="<?= $a['unit'] ?>">
                            </div>
                            <div class="col-md-2">
                                <span onclick="this.closest('.addon-row').remove()"
                                    style="cursor:pointer;color:red">Remove</span>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                    <button type="button" onclick="addAddon()" class="btn btn-sm btn-secondary">
                        + Add Addon
                    </button>
                </div>
            </div>

            <button type="submit" class="btn btn-primary">Update Product</button>

        </form>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>


<?php include 'inc/footer.php'; ?>

<script>
toastr.options = {
    closeButton: true,
    progressBar: true,
    positionClass: "toast-top-right",
    timeOut: "3000"
};

const selectedSorting = <?= json_encode($sortingSelected) ?>;
const currentCategory = <?= $product['category_id'] ?>;
const currentSubcategory = <?= $product['subcategory_id'] ?? 'null' ?>;
// Load categories
// Load categories
fetch('api/get_categories.php')
    .then(res => res.json())
    .then(data => {
        const sel = document.getElementById('categorySelect');
        data.forEach(c => {
            sel.innerHTML += `<option value="${c.id}" ${c.id == currentCategory ? 'selected' : ''}>${c.name}</option>`;
        });

        // load sorting & subcategories
        loadSorting(currentCategory);
        loadSubcategories(currentCategory);
    });

// Function to load subcategories
function loadSubcategories(categoryId) {
    const sel = document.getElementById('subcategorySelect');
    sel.innerHTML = '<option value="">Select Subcategory</option>';

    if (!categoryId) return;

    fetch('api/get_subcategories.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `category_id=${categoryId}`
    })
    .then(res => res.text())
    .then(html => {
        sel.innerHTML = html;

        // set selected if editing
        if (currentSubcategory) sel.value = currentSubcategory;
    });
}

// Load sorting
function loadSorting(catId) {
    fetch(`api/get_sorting_by_category.php?category_id=${catId}`)
        .then(res => res.json())
        .then(groups => {
            const box = document.getElementById('sortingContainer');
            box.innerHTML = '';
            groups.forEach(g => {
                let html = `<div class="col-md-4"><strong>${g.name}</strong>`;
                g.options.forEach(o => {
                    let checked = selectedSorting.map(Number).includes(Number(o.id)) ? 'checked' :
                        '';

                    html += `<div class="form-check">
<input type="checkbox" name="sorting[]" value="${o.id}" ${checked}>
<label>${o.name}</label>
</div>`;
                });
                html += '</div>';
                box.innerHTML += html;
            });
        });
}

document.getElementById('categorySelect').addEventListener('change', e => {
    const catId = e.target.value;
    loadSorting(catId);
    loadSubcategories(catId);

    // reload variants for new category
    currentCategory = catId;
    loadGroupVariants();
});

    
// Add functions
function addVariant() {
    const box = document.getElementById('variantsContainer');

    box.innerHTML += `
    <div class="variant-row row">

        <div class="col-md-3">
            <select name="variant_group_id[]" class="form-control gv-dropdown" required>
                <option value="">Select Group</option>
            </select>
        </div>

        <div class="col-md-2">
            <input type="text" name="variant_label[]" 
                   class="form-control" 
                   placeholder="Label (Red, 1/2 etc)" required>
        </div>

        <div class="col-md-2">
            <input type="number" step="0.01" 
                   name="variant_price[]" 
                   class="form-control" 
                   placeholder="Price" required>
        </div>

        <div class="col-md-2">
            <select name="variant_unit[]" class="form-control">
                <option value="TON">TON</option>
                <option value="YARD">YARD</option>
                <option value="EACH">EACH</option>
                <option value="PIECE">PIECE</option>
                <option value="SQFT">SQFT</option>
                <option value="LNFT">LNFT</option>
            </select>
        </div>

        <div class="col-md-3 d-flex align-items-center">
            <span class="remove-btn" onclick="this.closest('.variant-row').remove()">Remove</span>
        </div>

    </div>
    `;

    loadGroupVariants();
}

function loadGroupVariants() {

    const productId = <?= (int)$product['id'] ?>;

   fetch(`api/get_group_variants.php?category_id=${currentCategory}`)
        .then(res => res.json())
        .then(data => {

            document.querySelectorAll('.gv-dropdown').forEach(drop => {

                const selected = drop.dataset.selected || "";

                // ✅ ALWAYS RESET FIRST
                drop.innerHTML = '<option value="">Select Group</option>';

                if (!data.length) {
                    drop.innerHTML += '<option value="">No groups found</option>';
                    return;
                }

                data.forEach(g => {
                    let sel = (selected == g.id) ? 'selected' : '';
                    drop.innerHTML += `<option value="${g.id}" ${sel}>${g.name}</option>`;
                });

            });

        })
        .catch(err => console.error('Group load error:', err));
}





function addAddon() {
    document.getElementById('addonsContainer').innerHTML += `
    <div class="addon-row row">
        <div class="col-md-4">
            <input name="addon_name[]" class="form-control" placeholder="Addon Name">
        </div>
        <div class="col-md-3">
            <input name="addon_price[]" class="form-control" placeholder="Price">
        </div>
        <div class="col-md-3">
            <select name="addon_unit[]" class="form-select form-control">
                <option value="LNFT">LNFT</option>
                <option value="EACH">EACH</option>
            </select>
        </div>
        <div class="col-md-2">
            <span onclick="this.closest('.addon-row').remove()" class="remove-btn">Remove</span>
        </div>
    </div>`;
}


// Submit
document.getElementById('productForm')
    .addEventListener('submit', e => {
        e.preventDefault();
        fetch('api/update_product.php', {
                method: 'POST',
                body: new FormData(e.target)
            })
            .then(res => res.json())
            .then(r => {
                if (r.status === 'success') {
                    toastr.success(r.message || 'Product updated successfully');

                    // redirect after 1.5s
                    setTimeout(() => {
                        window.location.href = 'show-product.php';
                    }, 1500);

                } else {
                    toastr.error(r.message || 'Update failed');
                }
            });


    });

    // remove existing gallery image (UI only)
$(document).on('click', '.img-remove-btn', function () {
    let box = $(this).closest('.gallery-item');

    // remove hidden input so backend knows
    box.find('input[name="existing_images[]"]').remove();

    // nice fade
    box.fadeOut(300, function () {
        $(this).remove();
    });
});

// 🔥 LOAD GROUP VARIANTS ON PAGE LOAD
document.addEventListener('DOMContentLoaded', function () {
    loadGroupVariants();
});


</script>