<?php
include("../connection.php");
include("../user.php");
$cur_date = date('Y-m-d H:i:s');
$sys_date = date('d-m-Y');
$user = $_SESSION['user'];
$branch_id = $_SESSION['branch_id'];
$ho_access = $_SESSION['ha'];
$location = $_SESSION['location'];
$material_query = mysqli_query($con, "SELECT id, category_type, department,measurement FROM category_master WHERE status='0'");
$materials_by_category = [];
while ($row = mysqli_fetch_assoc($material_query)) {
    $materials_by_category[$row['department']][] = $row;
}
?>
<!doctype html>
<html class="no-js" lang="">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><?php echo TITLE; ?></title>
    <meta name="description" content="Ela Admin - HTML5 Admin Template">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="apple-touch-icon" href="../images/bluebase.png">
    <link rel="shortcut icon" href="../images/bluebase.png">
    <style>
        input {
            text-transform: uppercase;
        }

        textarea {
            text-transform: uppercase;
        }
    </style>
</head>

<body>
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header">
                <strong>Outward Creation</strong>
                <a href="outward_master.php"><button class="btn btn-primary" style="width:50px;float:right;"
                        onclick=""><i class="fa fa-backward"></i></button></a>
            </div>
            <div class="card-body card-block">
                <form method="POST" enctype="multipart/form-data" class="form-horizontal" action="outward_submit.php">
                    <div class="row form-group">
                        <div class="col col-md-3"><label for="text-input" class=" form-control-label">DATE</label></div>
                        <div class="col-12 col-md-9"><input type="date" id="so_date" name="so_date" class="form-control"
                                autocomplete="off" ></div>
                    </div>
                    <div class="row form-group">
                        <div class="col col-md-3"><label for="text-input" class=" form-control-label">MR No.</label>
                        </div>
                        <div class="col-12 col-md-9"><input type="number" id="mr_no" name="mr_no" class="form-control"
                                placeholder="Enter Mr No." autocomplete="off" ></div>
                    </div>
                    <div class="row form-group">
                        <div class="col col-md-3"><label for="text-input" class=" form-control-label">TICKET No.</label>
                        </div>
                        <div class="col-12 col-md-9"><input type="text" id="ticket_no" name="ticket_no"
                                class="form-control" placeholder="Enter Ticket No." autocomplete="off" ></div>
                    </div>

                    <div class="row form-group">
                        <div class="col col-md-3"><label for="text-input" class=" form-control-label">DEPARTMENT</label>
                        </div>
                        <div class="col-12 col-md-9">
                            <select class="form-control select-search" name="department[]" id="department"
                                onchange=changedept(this.value) >
                                <?php
                                $department = mysqli_query($con, "SELECT * FROM type_master where status='0'");
                                ?>
                                <option value="">CHOOSE DEPARTMENT</option>
                                <?php
                                while ($department_det = mysqli_fetch_array($department)) { ?>
                                    <option value="<?php echo $department_det['id']; ?>">
                                        <?php echo strtoupper($department_det['type']); ?>
                                    </option>
                                <?php } ?>
                            </select>
                        </div>
                    </div>
                    <div class="row form-group">
            <div class="col col-md-3"><label for="text-input" class=" form-control-label">BRANCH</label></div>
            <div class="col-12 col-md-6">
              <select class="form-control select-search" name="branch" id="branch" >
                <?php
                $branch = mysqli_query($con, "SELECT * FROM location_master where status='0'");
                ?>
                <option value="">CHOOSE BRANCH</option>
                <?php
                while ($branch_det = mysqli_fetch_array($branch)) { ?>
                  <option value="<?php echo $branch_det['id']; ?>">
                    <?php echo strtoupper($branch_det['location']); ?></option>
                <?php } ?>
              </select>
            </div>
          </div>
          <div class="row form-group">
            <div class="col col-md-3"><label for="text-input" class=" form-control-label">STORE</label></div>
            <div class="col-12 col-md-6">
              <select class="form-control select-search" name="store" id="store" >
                <?php
                $store = mysqli_query($con, "SELECT * FROM branch_master where status='0'");
                ?>
                <option value="">CHOOSE BRANCH</option>
                <?php
                while ($store_det = mysqli_fetch_array($store)) { ?>
                  <option value="<?php echo $store_det['id']; ?>">
                    <?php echo strtoupper($store_det['branch_name']); ?></option>
                <?php } ?>
              </select>
            </div>
          </div>
                    <div class="row form-group">
                        <div class="col col-md-3"><label for="text-input" class=" form-control-label">MATERIAL REQUESTED
                                BY TECHNICIAN NAME</label></div>
                        <div class="col-12 col-md-9">
                            <input type="text" id="technician" name="technician" class="form-control"
                                placeholder="Enter Technician" autocomplete="off" >
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col col-md-3"><label for="text-input" class=" form-control-label">APPROVED BY SHIFT
                                ENGINEER</label></div>
                        <div class="col-12 col-md-9">
                            <input type="text" id="approved_by" name="approved_by" class="form-control"
                                placeholder="Enter approved_by" autocomplete="off" >
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col col-md-3"><label for="text-input" class=" form-control-label">PURPOSE</label>
                        </div>
                        <div class="col-12 col-md-9">
                            <input type="text" id="purpose" name="purpose" class="form-control"
                                placeholder="Enter Purpose" autocomplete="off" >
                        </div>
                    </div>
                    <!-- Material Input Row -->
                    <div class="row form-group">
                        <div class="col-md-3">
                            <label for="material_name" class="form-control-label">MATERIAL NAME</label>
                        </div>
                        <div class="col-md-9">
                            <select class="form-control select-search" id="material_name" name="material_name[]">
                                <option value="">CHOOSE MATERIAL</option>

                            </select>
                        </div>
                    </div>

                    <div class="row form-group">
                        <div class="col-md-3"><label>QUANTITY</label></div>
                        <div class="col-md-3"><input type="number" id="qty" name="qty[]" onkeyup="calculateAmount()"
                                class="form-control"></div>

                        <div class="col-md-2"><label>QUM</label></div>
                        <div class="col-md-4">
                            <select class="form-control" id="qum" name="qum[]">
                                <option value="">CHOOSE</option>
                                <?php
                                $qums = mysqli_query($con, "SELECT id,name FROM measurement_master WHERE status='0'");
                                while ($qum = mysqli_fetch_array($qums)) {
                                    echo '<option value="' . $qum['id'] . '">' . strtoupper($qum['name']) . '</option>';
                                }
                                ?>
                            </select>
                        </div>
                    </div>

                    <div class="row form-group">
                        <div class="col-md-3"><label>RATE</label></div>
                        <div class="col-md-3"><input type="number" id="rate" name="rate[]" onkeyup="calculateAmount()"
                                class="form-control"></div>

                        <div class="col-md-2"><label>AMOUNT</label></div>
                        <div class="col-md-4"><input type="number" id="amount" name="amount[]" class="form-control"
                                readonly>
                        </div>
                    </div>
                    <div class="row-form-group">
                            <button type="button" class="btn btn-primary" onclick="addRow()">ADD</button>
                    </div>

                    <!-- Table -->
                    <table id="items_get" class="table table-bordered">
                        <thead>
                            <tr>
                                <th>DEPARTMENT</th>
                                <th>MATERIAL NAME</th>
                                <th>QUANTITY</th>
                                <th>MEASUREMENT</th>
                                <th>RATE</th>
                                <th>AMOUNT</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>

                    <div>
                        <button type="submit" name="submit" title="Submit" class="btn btn-success btn btn-lg"
                            style="float:right"><i class="fa fa-dot-circle-o"></i> Submit</button>

                    </div>
                </form>
            </div>
        </div>
        <div class="clearfix"></div>

        <footer class="site-footer">

        </footer>

    </div><!-- /#right-panel -->
</body>

</html>
<script>
    function gsttype(val) {
        if (val == 'gst') {
            $('#gst').show();
            $('#igst').hide();
            $('#sgst').hide();
            $('#ugst').hide();
        } else if (val == 'igst') {
            $('#igst').show();
            $('#sgst').hide();
            $('#ugst').hide();
            $('#gst').hide();
        } else if (val == 'sgst') {
            $('#sgst').show();
            $('#ugst').hide();
            $('#igst').hide();
            $('#gst').hide();
        } else if (val == 'ugst') {
            $('#ugst').show();
            $('#gst').hide();
            $('#sgst').hide();
            $('#igst').hide();
        }
    }


    function deleteRow(btn) {
        var row = btn.parentNode.parentNode;
        row.parentNode.removeChild(row);
    }

</script>

<script>

</script>
<script>
    $(document).ready(function () {
        $('#asset-select').change(function () {
            // Get the selected value
            const selectedValue = $(this).val();
            // Show or hide the S.NO input based on the selected value
            if (selectedValue === 'asset') {
                $('#serial-number-row').show(); // Show the S.NO row if 'Asset' is selected
            } else {
                $('#serial-number-row').hide(); // Hide the S.NO row for any other selection
            }
        });
    });
</script>
<script>
    function addRow() {
    let material = document.getElementById("material_name");
    let materialText = material.options[material.selectedIndex].text;
    let materialId = material.value;

    let qty = document.getElementById("qty").value;
    let qum = document.getElementById("qum");
    let qumText = qum.options[qum.selectedIndex].text;
    let qumId = qum.value;

    let deptId = document.getElementById("department").value;
    let deptText = $('#department').select2('data')[0]?.text || '';

    let rate = document.getElementById("rate").value;
    let amount = document.getElementById("amount").value;

    if (materialId === "" || qty === "" || qumId === "" || deptId === "") {
        alert("Please fill all fields before adding.");
        return;
    }

    let table = document.getElementById("items_get").getElementsByTagName('tbody')[0];
    let newRow = table.insertRow();

    newRow.innerHTML = `
        <td><input type="hidden" name="department[]" value="${deptId}">${deptText}</td>
        <td><input type="hidden" name="material_name[]" value="${materialId}">${materialText}</td>
        <td><input type="hidden" name="qty[]" value="${qty}">${qty}</td>
        <td><input type="hidden" name="qum[]" value="${qumId}">${qumText}</td>
        <td><input type="hidden" name="rate[]" value="${rate}">${rate}</td>
        <td><input type="hidden" name="amount[]" value="${amount}">${amount}</td>
        <td><button type="button" class="btn btn-danger" onclick="deleteRow(this)">Delete</button></td>
    `;

    // Reset fields
    material.selectedIndex = 0;
    document.getElementById("qty").value = "";
    qum.selectedIndex = 0;
    $('#department').val('').trigger('change');
    document.getElementById("rate").value = "";
    document.getElementById("amount").value = "";
}


    function fa_serial_get() {
        debugger;
        var qty = document.getElementById('qty').value;
        var serialRow = document.getElementById('serial-number-row');
        var serialContainer = document.getElementById('serial-number-container');

        // Clear previous serial number fields
        serialContainer.innerHTML = '';

        if (qty > 0) {
            serialRow.style.display = 'block'; // Show the serial number section

            // Generate input fields based on the quantity entered
            for (var i = 1; i <= qty; i++) {
                var input = document.createElement('input');
                input.type = 'text';
                input.name = 'fa_serial_no'; // Using array notation to store multiple values
                input.id = 'fa_serial_no-' + i;
                input.className = 'form-control'; // Add margin for spacing between inputs
                input.placeholder = 'Enter FA Serial Number ' + i;
                input.autocomplete = 'off';

                serialContainer.appendChild(input);
            }
        } else {
            serialRow.style.display = 'none'; // Hide the serial number section if quantity is 0 or invalid
        }
    }
</script>
<script>
    function calculateAmount() {
        var qty = document.getElementById("qty").value;
        var rate = document.getElementById("rate").value;

        if (qty && rate) {
            var amount = parseFloat(qty) * parseFloat(rate);
            document.getElementById("amount").value = amount.toFixed(2);
        } else {
            document.getElementById("amount").value = "";
        }
    }
    function changedept(dept) {
        const materials = <?php echo json_encode($materials_by_category); ?>;
        const materialSelect = document.getElementById('material_name');

        if (materials[dept]) {
            const options = materials[dept]
                .map(item => `<option value="${item.id}">${item.category_type}</option>`)
                .join('');
            materialSelect.innerHTML = `<option value="">CHOOSE MATERIAL</option>` + options;
        } else {
            materialSelect.innerHTML = `<option value="">No materials available</option>`;
        }
    }

</script>

<script>
    // Initialize Select2
    $(document).ready(function () {
        $('.select-search').select2({
            placeholder: "-- SELECT --",  // Optional placeholder text
            allowClear: true                // Optional: allows clearing the selection
        });
    });
</script>