<?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'];
$id = $_REQUEST['id'];
$editinward = mysqli_fetch_array(mysqli_query($con, "select  * from item_master where id='$id'"));
?>
<!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">
  <script src="../js/sweet-alert.js"></script>
  <style>
    input {
      text-transform: uppercase;
    }

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

<body>
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header">
        <strong>Edit Inward</strong>
        <a href="inward_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" id="editInwardForm" class="form-horizontal">
          <input type="hidden" name="id" class="form-control" value="<?php echo $editinward['id'] ?>">
          <div class="row form-group">
            <div class="col col-md-3"><label for="text-input" class=" form-control-label">PURCHASE DATE</label></div>
            <div class="col-12 col-md-9"><input type="date" id="po_date" name="po_date"
                value="<?php echo $editinward['po_date'] ?>" class="form-control" autocomplete="off"></div>
          </div>
          <div class="row form-group">
            <div class="col col-md-3"><label for="vendor_name" class="form-control-label">VENDOR NAME</label></div>
            <div class="col-12 col-md-9">
              <select class="form-control select-search" name="vendor_name" id="vendor_name">
                <option value="">CHOOSE VENDOR</option>
                <?php
                $vendors = mysqli_query($con, "SELECT * FROM vendor_master WHERE status='0'");
                while ($vendor = mysqli_fetch_array($vendors)) {
                  $selected = ($vendor['id'] == $editinward['vendor_name']) ? "selected" : "";
                  ?>
                  <option value="<?php echo $vendor['id']; ?>" <?php echo $selected; ?>>
                    <?php echo strtoupper($vendor['vendor_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">BILL/ DC NO</label></div>
            <div class="col-12 col-md-9"><input type="text" id="billno" name="billno"
                value="<?php echo $editinward['billno'] ?>" class="form-control" placeholder="Enter Bill NO"
                autocomplete="off"></div>
          </div>
          <div class="row form-group">
            <div class="col col-md-3"><label for="text-input" class=" form-control-label">GATE ENTRY</label></div>
            <div class="col-12 col-md-9"><input type="text" id="gatentry" name="gatentry"
                value="<?php echo $editinward['gatentry'] ?>" class="form-control" placeholder="Enter Gaten_Entry"
                autocomplete="off"></div>
          </div>
          <div class="row form-group">
            <div class="col col-md-3"><label for="material_name" class="form-control-label">MATERIAL NAME</label></div>
            <div class="col-12 col-md-9">
              <select class="form-control select-search" name="material_name" id="material_name">
                <option value="">CHOOSE MATERIAL NAME</option>
                <?php
                $category_list = mysqli_query($con, "SELECT id,category_type FROM category_master WHERE status='0'");
                while ($category = mysqli_fetch_array($category_list)) {
                  ?>
                  <option value="<?php echo $category['id']; ?>" <?php if ($editinward['material_name'] == $category['id']) {
                       echo "selected";
                     } ?>><?php echo strtoupper($category['category_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">QUANTITY</label></div>
            <div class="col-12 col-md-9">
              <input type="number" id="qty" name="qty" value="<?php echo $editinward['quantity'] ?>"
                class="form-control" placeholder="Enter Quantity" autocomplete="off" oninput="qtychange(this.value)"
                onblur="calculateTotalAmount()">
            </div>
          </div>
          <div class="row form-group">
            <div class="col col-md-3"><label for="text-input" class=" form-control-label">QUM</label></div>
            <div class="col-12 col-md-9">
              <select class="form-control select-search" name="qum" id="qum">
                <option value="">CHOOSE QUM</option>
                <?php
                $qums = mysqli_query($con, "SELECT id,name FROM measurement_master WHERE status='0'");
                while ($qum = mysqli_fetch_array($qums)) {
                  $selected = ($qum['id'] == $editinward['qum']) ? "selected" : "";
                  ?>
                  <option value="<?php echo $qum['id']; ?>" <?php echo $selected; ?>>
                    <?php echo strtoupper($qum['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">DEPARTMENT</label></div>
            <div class="col-12 col-md-9">
              <select class="form-control select-search" name="department" id="department">
                <?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)) {
                  $selected = ($department_det['id'] == $editinward['department']) ? "selected" : "";
                  ?>
                  <option value="<?php echo $department_det['id']; ?>" <?php echo $selected; ?>>
                    <?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-9">
              <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)) {
                  $selected = ($branch_det['id'] == $editinward['branch']) ? "selected" : "";
                  ?>
                  <option value="<?php echo $branch_det['id']; ?>" <?php echo $selected; ?>>
                    <?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-9">
              <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)) {
                  $selected = ($store_det['id'] == $editinward['division']) ? "selected" : "";
                  ?>
                  <option value="<?php echo $store_det['id']; ?>" <?php echo $selected; ?>>
                    <?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">RATE</label></div>
            <div class="col-12 col-md-9"><input type="number" id="value" name="value"
                value="<?php echo $editinward['value'] ?>" oninput="qtys(this.value)" class="form-control"
                placeholder="Enter Value" autocomplete="off" onblur="calculateTotalAmount()"></div>
          </div>
          <div class="row form-group">
            <div class="col col-md-3"><label for="text-input" class=" form-control-label">AMOUNT</label></div>
            <div class="col-12 col-md-9"><input type="number" id="amount" name="amount"
                value="<?php echo $editinward['amount'] ?>" class="form-control" autocomplete="off" Placeholder="AMOUNT"
                readonly></div>
          </div>
          <input type="hidden" id="amounthidden">
          <div class="row form-group">
            <div class="col col-md-3"><label for="text-input" class=" form-control-label">DISCOUNT PERCENTAGE</label>
            </div>
            <div class="col-12 col-md-9"><input type="number" id="discount" name="discount" class="form-control"
                autocomplete="off" Placeholder="DISCOUNT PERCENTAGE" oninput="changeDiscount(this.value)"
                value="<?php echo $editinward['discount'] ?>"></div>
          </div>
          <div class="row form-group">
            <div class="col col-md-3"><label for="cars" class=" form-control-label">GST TYPE:</label></div>
            <div class="col-12 col-md-9">
              <select name="gst_type" id="gst_type" onchange="gsttype(this.value);" class="form-control">
                <option value="">SELECT</option>
                <option value="gst">GST</option>
                <option value="igst">IGST</option>
                <option value="sgst">SGST</option>
                <option value="ugst">UGST</option>
              </select>
            </div>
          </div>
          <div class="row form-group" style="display: none;" id="gst">
            <div class="col col-md-3"><label for="gst_percentage" class="form-control-label">GST PERCENTAGE</label>
            </div>
            <div class="col-12 col-md-9"><input type="number" id="gst_percentage" name="gst_percentage"
                class="form-control" placeholder="Enter GST Percentage" oninput="calculateTotalAmount()"></div>
          </div>
          
          <div class="row form-group">
            <div class="col col-md-3"><label for="total_amount" class="form-control-label">TOTAL AMOUNT</label></div>
            <div class="col-12 col-md-9"><input type="number" id="total_amount" name="total_amount"
                value="<?php echo $editinward['total_amount'] ?>" class="form-control" placeholder="Total Amount"
                readonly></div>
          </div>
          <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').show();
		}else { 
			$('#gst').hide();
		}
	}
  function deleteRow(btn) {
    var row = btn.parentNode.parentNode;
    row.parentNode.removeChild(row);
  }
  function qtychange(qty) {
    var quantity = qty || 0;
    var discountPercentage = parseFloat($("#discount").val()) || 0;
    var value = $("#value").val();
    calculatepercentage(quantity, discountPercentage, value);
  }
  function qtys(value) {
    var quantity = parseFloat($("#qty").val()) || 0;
    var discountPercentage = parseFloat($("#discount").val()) || 0;
    calculatepercentage(quantity, discountPercentage, value);
  }
  function changeDiscount(discount) {
    var quantity = parseFloat($("#qty").val()) || 0;
    var value = $("#value").val();
    calculatepercentage(quantity, discount, value);
  }
  function calculatepercentage(qty, discount, value) {
    var originalAmount = qty * value; // Amount before discount
    var discountAmount = (originalAmount * discount) / 100; // Discount calculation
    var discountedAmount = originalAmount - discountAmount; // Amount after discount
    $('#amount').val(originalAmount.toFixed(2));
    $('#amounthidden').val(discountedAmount.toFixed(2)); // Update Amount Field
    calculateTotalAmount(); // Update total amount with GST
  }
</script>
<script>
  function calculateTotalAmount() {
    const value = parseFloat(document.getElementById('value').value) || 0;
    const amounthidden = parseFloat(document.getElementById('amounthidden').value) || 0;
    const amount = parseFloat(document.getElementById('amount').value) || 0;
    const gstPercentage = parseFloat(document.getElementById('gst_percentage').value) || 0;
    const totalAmount = amounthidden + (amount * gstPercentage / 100);
    document.getElementById('total_amount').value = totalAmount.toFixed(2);
  }
</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>
$(document).on('submit', '#editInwardForm', function(e) {
    e.preventDefault();

    $.ajax({
        url: 'inward_update.php',
        type: 'POST',
        data: new FormData(this),
        contentType: false,
        processData: false,
        success: function(response) {
            if (response.success) {
                swal({
                    title: "Success!",
                    text: response.message,
                    type: "success"
                }, function () {
                    $('#editInwardContainer').slideUp().html('');
                    reloadInwardTable(); // optional table refresh
                });
            } else {
                swal("Failed", response.message, "error");
            }
        },
        error: function(xhr, status, error) {
            swal("Error", "Something went wrong in AJAX: " + error, "error");
        }
    });
});

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