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

$id = $_GET['id'] ?? 0;

$data = mysqli_fetch_assoc(mysqli_query($conn, "
SELECT pm.*, p.category_id, p.subcategory_id
FROM product_materials pm
JOIN products p ON p.id = pm.product_id
WHERE pm.id = '$id'
"));

if (!$data) {
    echo "<script>window.location='product_materials.php'</script>";
    exit;
}
?>

<div class="card shadow mb-4">
    <div class="card-header">
        <h5>Edit Product Material</h5>
    </div>

    <div class="card-body">

        <form id="assignForm">

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

            <!-- CATEGORY -->
            <div class="row">
                <div class="col-md-4">
                    <label>Category</label>
                    <select id="categorySelect" class="form-control">
                        <option value="">Select Category</option>
                        <?php
                        $cats = mysqli_query($conn,"SELECT * FROM categories WHERE status='active'");
                        while($c = mysqli_fetch_assoc($cats)){
                        ?>
                        <option value="<?= $c['id'] ?>"
                            <?= $c['id'] == $data['category_id'] ? 'selected' : '' ?>>
                            <?= $c['name'] ?>
                        </option>
                        <?php } ?>
                    </select>
                </div>

                <!-- SUB CATEGORY -->
                <!-- SUB CATEGORY -->
<div class="col-md-4">
    <label>Sub Category</label>
    <select id="subCategorySelect" class="form-control">
        <option value="">Loading...</option>
    </select>
</div>

<!-- PRODUCT -->
<div class="col-md-4">
    <label>Product</label>
    <select name="product_id" id="productSelect" class="form-control" required>
        <option value="">Select Product</option>
    </select>
</div>
</div>

            <!-- MATERIAL -->
            <div class="row mt-3">
                <div class="col-md-6">
                    <label>Material</label>
                    <select name="material_id" class="form-control">
                        <?php
                        $mat = mysqli_query($conn,"SELECT * FROM stone_materials WHERE status='active'");
                        while($m = mysqli_fetch_assoc($mat)){
                        ?>
                        <option value="<?= $m['id'] ?>"
                            <?= $m['id'] == $data['material_id'] ? 'selected' : '' ?>>
                            <?= $m['name'] ?>
                        </option>
                        <?php } ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label>Calculation Type</label>
                    <select name="calc_type" class="form-control">
                        <option value="sqft" <?= $data['calc_type']=='sqft'?'selected':'' ?>>SQFT</option>
                        <option value="lnft" <?= $data['calc_type']=='lnft'?'selected':'' ?>>LNFT</option>
                    </select>
                </div>
            </div>

            <!-- VALUES -->
            <div class="row mt-3">
                <div class="col-md-6">
                    <label>SQFT Value</label>
                    <input type="number" step="0.01" name="sqft_value"
                           class="form-control"
                           value="<?= $data['sqft_value'] ?>">
                </div>

                <div class="col-md-6">
                    <label>LNFT Value</label>
                    <input type="number" step="0.01" name="lnft_value"
                           class="form-control"
                           value="<?= $data['lnft_value'] ?>">
                </div>
            </div>

            <button class="btn btn-primary mt-3">Update</button>

        </form>

    </div>
</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>
    toastr.options = {
    closeButton: true,
    progressBar: true,
    positionClass: "toast-top-right",
    timeOut: "2500"
};

$('#assignForm').submit(function(e){
    e.preventDefault();

    $.ajax({
        url: 'api/update_product_material.php',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(res){

            if(res.status === 'success'){
                toastr.success(res.message);
            } else {
                toastr.error(res.message);
            }

        }
    });

});

$(document).ready(function () {

    let catId = $('#categorySelect').val();
    let selectedSub = "<?= $data['subcategory_id'] ?>";
    let selectedProduct = "<?= $data['product_id'] ?>";

    loadSubOrProducts(catId, selectedSub, selectedProduct);

});

/* CATEGORY CHANGE */
$('#categorySelect').on('change', function () {

    let catId = $(this).val();
    loadSubOrProducts(catId, null, null);

});

/* SUB CATEGORY CHANGE */
$('#subCategorySelect').on('change', function () {

    let subId = $(this).val();

    if (!subId || subId == 0) return;

    $.post('api/get_products.php', {
        sub_category_id: subId
    }, function (res) {
        $('#productSelect').html(res);
    });

});

/* MAIN FUNCTION (SMART HANDLER) */
function loadSubOrProducts(catId, selectedSub, selectedProduct) {

    $.post('api/get_subcategories.php', { category_id: catId }, function (res) {

        $('#subCategorySelect').html(res);

        let hasSub = $('#subCategorySelect option[value!=""]').length > 0;

        if (hasSub) {

            // SELECT SUBCAT
            if (selectedSub && selectedSub != 0) {
                $('#subCategorySelect').val(selectedSub);

                // LOAD PRODUCTS BY SUBCAT
                $.post('api/get_products.php', {
                    sub_category_id: selectedSub
                }, function (res) {
                    $('#productSelect').html(res);

                    if (selectedProduct) {
                        $('#productSelect').val(selectedProduct);
                    }
                });

            }

        } else {

            // NO SUBCATEGORY CASE
            $('#subCategorySelect').html('<option value="0">No Sub Category</option>');

            $.post('api/get_products_by_category.php', {
                category_id: catId
            }, function (res) {
                $('#productSelect').html(res);

                if (selectedProduct) {
                    $('#productSelect').val(selectedProduct);
                }
            });

        }

    });

}
</script>