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

if (isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'user') {
    echo "<script>window.location.href='index.php'</script>";
    exit;
}
?>

<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">Add Products</h6>
    </div>

    <div class="container my-4">
        <!-- <h3 class="mb-3">Add Product</h3> -->

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


            <!-- BASIC INFO -->
            <div class="card mb-3">
                <div class="card-body">
                    <h5>Basic Information</h5>
                  <div class="row">
    <div class="col-md-4">
        <label class="form-label">Product Name</label>
        <input type="text" name="name" class="form-control" required>
    </div>

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

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


                    <div class="mt-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3"></textarea>
                    </div>



                    <div class="row mt-3">
                        <div class="col-md-4">
                            <label class="form-label">Base Price</label>
                            <input type="number" step="0.01" name="base_price" class="form-control"
                                placeholder="Optional">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Featured Image</label>
                            <input type="file" name="featured_image" class="form-control" required>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">Gallery Images</label>
                            <input type="file" name="gallery_images[]" class="form-control" multiple>
                        </div>


                    </div>


                    <div class="form-check mt-3">
                        <input class="form-check-input" type="checkbox" name="requires_machinery" value="1">
                        <label class="form-check-label">Requires Machinery (Oversize / Heavy)</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="no_sorting" value="1">
                        <label class="form-check-label">No Sorting (Quarry Slabs)</label>
                    </div>
                </div>
            </div>

            <!-- SORTING OPTIONS -->
            <div class="card mb-3">
                <div class="card-body">
                    <h5>Sorting Options (Filters)</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"></div>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="addVariant()">+ Add Variant</button>
                </div>
            </div>

            <!-- ADDONS -->
            <div class="card mb-3">
                <div class="card-body">
                    <h5>Add‑Ons (Edges / Finishes)</h5>
                    <div id="addonsContainer"></div>
                    <button type="button" class="btn btn-sm btn-secondary" onclick="addAddon()">+ Add Add‑On</button>
                </div>
            </div>

            <button type="submit" class="btn btn-primary">Save Product</button>
        </form>
    </div>
    <?php include 'inc/footer.php'; ?>

    <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>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
toastr.options = {
    closeButton: true,
    progressBar: true,
    positionClass: "toast-top-right",
    timeOut: "3000"
};

/* GLOBAL STORAGE FOR VARIANT GROUPS */
let groupVariants = [];

/* 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.name}</option>`;
    });
});

/* CATEGORY CHANGE (ONLY ONE EVENT NOW) */
document.getElementById('categorySelect').addEventListener('change', function(){

    const catId = this.value;

    if(!catId) return;

    /* LOAD SUBCATEGORIES */
    fetch('api/get_subcategories.php',{
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`category_id=${catId}`
    })
    .then(res=>res.text())
    .then(data=>{
        document.getElementById('subcategorySelect').innerHTML = data;
    });

    /* LOAD SORTING OPTIONS */
    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=>{
                html+=`
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="sorting[]" value="${o.id}">
                    <label class="form-check-label">${o.name}</label>
                </div>`;
            });
            html+='</div>';
            box.innerHTML+=html;
        });
    });

    /* LOAD VARIANT GROUPS */
    loadGroupVariantsByCategory(catId);

});


/* SUBCATEGORY CHANGE -> reload sorting */
document.getElementById('subcategorySelect').addEventListener('change', function(){

    const catId = document.getElementById('categorySelect').value;
    const subId = this.value;

    if(!catId) return;

    fetch(`api/get_sorting_by_category.php?category_id=${catId}&subcategory_id=${subId}`)
    .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=>{
                html+=`
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="sorting[]" value="${o.id}">
                    <label class="form-check-label">${o.name}</label>
                </div>`;
            });
            html+='</div>';
            box.innerHTML+=html;
        });
    });

});


/* LOAD VARIANT GROUPS */
function loadGroupVariantsByCategory(categoryId){

    fetch(`api/get_group_variants.php?category_id=${categoryId}`)
    .then(res=>res.json())
    .then(data=>{
        groupVariants = data;
    })
    .catch(()=>{
        groupVariants = [];
    });

}


/* ADD VARIANT */
function addVariant(){

    const catId = document.getElementById('categorySelect').value;

    if(!catId){
        toastr.warning('Please select category first');
        return;
    }

    if(!groupVariants.length){
        toastr.warning('No variant groups for this category');
        return;
    }

    const box = document.getElementById('variantsContainer');

    let groupOptions='<option value="">Select Group</option>';

    groupVariants.forEach(g=>{
        groupOptions += `<option value="${g.id}">${g.name}</option>`;
    });

    box.insertAdjacentHTML('beforeend',`
    <div class="variant-row row">

        <div class="col-md-3">
            <select name="variant_group_id[]" class="form-control" required>
                ${groupOptions}
            </select>
        </div>

        <div class="col-md-3">
            <input type="text" name="variant_label[]" class="form-control"
            placeholder="Label (e.g. 1/2, Red)" 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-2 d-flex align-items-center">
            <span class="remove-btn" onclick="this.closest('.variant-row').remove()">Remove</span>
        </div>

    </div>
    `);

}


/* ADD ADDON */
function addAddon(){

    const box=document.getElementById('addonsContainer');

    box.insertAdjacentHTML('beforeend',`
    <div class="addon-row row">

        <div class="col-md-4">
            <input type="text" name="addon_name[]" class="form-control" placeholder="Addon Name">
        </div>

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

        <div class="col-md-3">
            <select name="addon_unit[]" class="form-control">
                <option value="LNFT">LNFT</option>
                <option value="EACH">EACH</option>
            </select>
        </div>

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

    </div>
    `);

}


/* SUBMIT FORM */
document.getElementById('productForm').addEventListener('submit', e=>{

    e.preventDefault();

    fetch('api/save_product.php',{
        method:'POST',
        body:new FormData(e.target)
    })
    .then(res=>res.json())
    .then(r=>{
        if(r.status==='success'){
            toastr.success(r.message || 'Product added successfully');
            document.getElementById('productForm').reset();
            document.getElementById('variantsContainer').innerHTML='';
            document.getElementById('addonsContainer').innerHTML='';
        }else{
            toastr.error(r.message || 'Insertion failed');
        }
    });

});
    </script>