<style>
/* Style tambahan untuk form-floating agar terlihat lebih elegan */
.form-floating > .form-control:not(:placeholder-shown) ~ label,
.form-floating > .form-control-plaintext:not(:placeholder-shown) ~ label,
.form-floating > .form-select ~ label {
    opacity: .65;
    transform: scale(.85) translateY(-.5rem) translateX(.15rem);
}

/* Memperbaiki tampilan input group dengan form-floating */
.input-group > .form-floating:not(:last-child) > .form-control,
.input-group > .form-floating:not(:last-child) > .form-select {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}
.input-group > .form-floating:not(:first-child) > .form-control,
.input-group > .form-floating:not(:first-child) > .form-select {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
</style>

<div class="modal fade" id="InventoryModal" tabindex="-1" aria-labelledby="InventoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content shadow-lg">
            
            <div class="modal-header bg-primary text-white p-3">
                <h5 class="modal-title fw-bold" id="InventoryModalLabel">
                    <i class="fas fa-box-open me-2"></i> ATK Requisition Form
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            
            <div class="modal-body p-4">
                <form action="<?= base_url('Admin/ATK/Atk_Pengambilan_Controller/tambah'); ?>" method="post">

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label for="atk_pengambilan_peminjam" class="form-label small text-muted">Full Name</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-user"></i></span>
                                <input type="text" class="form-control" id="atk_pengambilan_peminjam" 
                                    name="atk_pengambilan_peminjam" placeholder="Masukkan Nama Lengkap" required>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <label for="atk_pengambilan_divisi" class="form-label small text-muted">Division of Origin</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-building"></i></span>
                                <select class="form-select" id="atk_pengambilan_divisi" name="atk_pengambilan_divisi" required>
                                    <option value="">-- Select Division --</option>
                                    <?php foreach ($divisi as $inventory): ?>
                                        <option value="<?= $inventory->divisi_categories_id; ?>"
                                            <?= set_select('atk_pengambilan_divisi', $inventory->divisi_categories_id); ?>>
                                            <?= $inventory->divisi_categories_nama; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label for="atk_pengambilan_lokasi" class="form-label small text-muted">Location</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-map-marker-alt"></i></span>
                                <select class="form-select" id="atk_pengambilan_lokasi" 
                                    name="atk_pengambilan_lokasi" onchange="getProducts()" required>
                                    <option value="">-- Select Location --</option>
                                    <?php foreach ($lokasi as $loc): ?>
                                        <option value="<?= $loc->inventory_location_id; ?>"
                                            <?= set_select('atk_pengambilan_lokasi', $loc->inventory_location_id); ?>>
                                            <?= $loc->inventory_location_nama; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <label for="atk_product_categories" class="form-label small text-muted">ATK Categories</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-tags"></i></span>
                                <select class="form-select" id="atk_product_categories" 
                                    name="atk_product_categories" onchange="getProducts()" required>
                                    <option value="">-- Select Category --</option>
                                    <?php foreach ($kategori as $inventory): ?>
                                        <option value="<?= $inventory->atk_categories_id; ?>">
                                            <?= $inventory->atk_categories_nama; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label for="atk_pengambilan_product" class="form-label small text-muted">ATK Name</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-box"></i></span>
                                <select class="form-select" id="atk_pengambilan_product" 
                                    name="atk_pengambilan_product" onchange="getStock()" required>
                                    <option value="">-- Select Product --</option>
                                    </select>
                            </div>
                            <div id="stokInfo" class="mt-1 d-flex justify-content-between">
                                <small id="stokTersedia" class="fw-bold text-success"></small>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <label for="atk_pengambilan_jumlah" class="form-label small text-muted">Quantity Taken</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-sort-numeric-up"></i></span>
                                <input type="number" class="form-control" id="atk_pengambilan_jumlah" 
                                    name="atk_pengambilan_jumlah" placeholder="Masukkan Jumlah" 
                                    min="1" required oninput="validateStock()">
                            </div>
                            <small id="stokError" class="fw-bold text-danger mt-1"></small>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label for="notes" class="form-label small text-muted">Notes</label>
                        <div class="form-floating">
                            <textarea class="form-control" id="notes" name="notes" rows="3" 
                                placeholder="Tambahkan catatan khusus..." style="height: 100px" **required**></textarea>
                            <label for="notes">Tambahkan catatan khusus (misalnya: untuk keperluan proyek X)</label>
                        </div>
                    </div>

                    <div class="modal-footer mt-4 p-0 border-top-0">
                        <button type="button" class="btn btn-secondary shadow-sm" data-bs-dismiss="modal">
                            <i class="fas fa-times me-1"></i> Close
                        </button>
                        <button type="submit" class="btn btn-primary shadow-sm" id="submitBtn">
                            <i class="fas fa-cart-plus me-1"></i> Save Requisition
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var stokTersedia = 0;

// Fungsi untuk memuat ulang produk ketika Kategori atau Lokasi berubah
function getProducts() {
    var categoryId = $("#atk_product_categories").val();
    var lokasiId 	= $("#atk_pengambilan_lokasi").val(); 

    // Reset pilihan dan stok
    $("#atk_pengambilan_product").html('<option value="">-- Select Product --</option>');
    $("#stokTersedia").text("");
    $("#atk_pengambilan_jumlah").val("");
    validateStock(); // Matikan tombol save jika tidak ada produk

    // Hanya panggil AJAX jika Kategori DAN Lokasi sudah dipilih
    if (categoryId !== "" && lokasiId !== "") {
        $.ajax({
            url: "<?= site_url('Admin/ATK/Atk_Pengambilan_Controller/getProductsByCategory') ?>",
            type: "POST",
            data: { 
                category_id: categoryId,
                location_id: lokasiId 	
            },
            dataType: "json",
            beforeSend: function() {
                 $("#stokTersedia").html('<i class="fas fa-spinner fa-spin me-1"></i> Loading products...');
            },
            success: function(response) {
                $("#stokTersedia").text(""); // Clear loading text
                if (response.length === 0) {
                     $("#stokTersedia").text("No products found in this location/category.");
                     $("#stokTersedia").removeClass("text-success").addClass("text-danger");
                } else {
                     $("#stokTersedia").text("");
                     $("#stokTersedia").removeClass("text-danger").addClass("text-success");
                }
                
                $.each(response, function(index, item) {
                    $("#atk_pengambilan_product").append(
                        '<option value="' + item.atk_product_id + '" data-stock="' + item.atk_product_stok + '">' + item.atk_product_nama + ' (' + item.atk_product_stok + ' units available)</option>'
                    );
                });
            },
            error: function() {
                 $("#stokTersedia").html('<span class="text-danger">Error loading products.</span>');
            }
        });
    }
}


function getStock() {
    var selectedProduct = $("#atk_pengambilan_product option:selected");
    stokTersedia = parseInt(selectedProduct.data("stock")) || 0;
    
    // Tampilkan stok yang tersedia dengan jelas
    if (stokTersedia > 0) {
        $("#stokTersedia").text("Available Stock: " + stokTersedia + " units");
        $("#stokTersedia").removeClass("text-danger").addClass("text-success");
    } else if (stokTersedia === 0) {
        $("#stokTersedia").text("Available Stock: 0 units");
        $("#stokTersedia").removeClass("text-success").addClass("text-danger");
    } else {
        $("#stokTersedia").text("");
    }
    
    // Reset Quantity dan jalankan validasi
    $("#atk_pengambilan_jumlah").val("");
    validateStock();
}

function validateStock() {
    var jumlahDiambil = parseInt($("#atk_pengambilan_jumlah").val()) || 0;
    
    if ($("#atk_pengambilan_product").val() === "") {
        $("#stokError").text("Please select a product first.");
        $("#submitBtn").prop("disabled", true);
    } else if (jumlahDiambil === 0 || isNaN(jumlahDiambil)) {
        $("#stokError").text("");
        $("#submitBtn").prop("disabled", false);
    } else if (jumlahDiambil > stokTersedia) {
        $("#stokError").text("Quantity (" + jumlahDiambil + ") exceeds available stock (" + stokTersedia + ")!");
        $("#submitBtn").prop("disabled", true);
    } else {
        $("#stokError").text("");
        $("#submitBtn").prop("disabled", false);
    }
}
</script>