<?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>
  <?php
  // Prepare QUM options once in PHP
  $qum_options = "";
  $qums = mysqli_query($con, "SELECT id,name FROM measurement_master WHERE status='0'");
  while ($qum = mysqli_fetch_array($qums)) {
    $qum_options .= "<option value='{$qum['id']}'>" . strtoupper($qum['name']) . "</option>";
  }
  ?>
  <script>
    const materials_by_category = <?php echo json_encode($materials_by_category); ?>;
    const qumOptions = `<?php echo $qum_options; ?>`;

    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>`;
    }
}
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 changematerial(row) {
      const selectedMaterial = row.querySelector('[name="material_name[]"]').value;
      const dept = document.getElementById('department').value;
      const result = materials_by_category[dept].find(item => item.id === selectedMaterial);
      row.querySelector('[name="qum[]"]').value = result.measurement;
    }
    
    function gsttype(val) {
		if (val != '') {
			$('#gst').show();
		}else { 
			$('#gst').hide();
		}
	}

    function calcamount(row) {
      const qty = parseFloat(row.querySelector('[name="qty[]"]').value || 0);
      const value = parseFloat(row.querySelector('[name="value[]"]').value || 0);
      row.querySelector('[name="amount[]"]').value = (qty * value).toFixed(2);
      calculateTotalValue();
      changeDiscount();
      calculateTotalAmount();
    }

    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 rate = document.getElementById("rate").value;
  let amount = document.getElementById("amount").value;

  let deptSelect = document.getElementById("department");
  let dept = deptSelect.value;
  let deptText = deptSelect.options[deptSelect.selectedIndex].text;

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

  // Get measurement from materials_by_category
  let qumId = "";
  let qumText = "";
  if (materials_by_category[dept]) {
    const mat = materials_by_category[dept].find(item => item.id === materialId);
    if (mat) {
      qumText = mat.measurement.toUpperCase();
      qumId = mat.measurement;
    }
  }

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

  newRow.innerHTML = `
      <td><input type="hidden" name="department[]" value="${dept}">${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="value[]" 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>
  `;

  // Clear inputs
  material.selectedIndex = 0;
  document.getElementById("qty").value = "";
  document.getElementById("rate").value = "";
  document.getElementById("amount").value = "";
  document.getElementById("qum").selectedIndex = 0;
  deptSelect.selectedIndex = 0;

  calculateTotalValue();
}



    function deleteRow(button) {
      const row = button.closest('tr');
      row.remove();
      calculateTotalValue();
    }

    function calculateTotalValue() {
      let totvalue = 0;
      document.querySelectorAll('#items_get tbody tr').forEach(row => {
        const amount = parseFloat(row.querySelector('[name="amount[]"]').value || 0);
        totvalue += amount;
      });
      document.getElementById('total_amount').value = totvalue.toFixed(2);
    }

    function changeDiscount() {
      const discount = parseFloat(document.getElementById('discount').value || 0);
      const value = parseFloat(document.getElementById('total_amount').value || 0);
      calculatepercentage(discount, value);
    }

    function calculatepercentage(discount, value) {
      const discountAmount = (value * discount) / 100;
      document.getElementById('discount_amount').value = discountAmount.toFixed(2);
      calculateTotalAmount();
    }

    function calculateTotalAmount() {
      const amount = parseFloat(document.getElementById('total_amount').value || 0);
      const gstPercentage = parseFloat(document.getElementById('gst_percentage').value || 0);
      const discount = parseFloat(document.getElementById('discount_amount').value || 0);
      const gstAmount = (amount * gstPercentage) / 100;
      const total = amount + gstAmount - discount;

      document.getElementById('gstamount').value = gstAmount.toFixed(2);
      document.getElementById('final_amount').value = total.toFixed(2);
    }

    $(document).ready(function () {
      $('.select-search').select2({
        placeholder: "-- SELECT --",
        allowClear: true
      });
    });
  </script>

</head>

<body>
  <div class="col-lg-12">
    <div class="card">
      <div class="card-header">
        <strong>Inward Creation</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" class="form-horizontal" action="inward_submit.php">
          <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-6"><input type="date" id="po_date" name="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-6">
              <select class="form-control select-search" name="vendor_name" id="vendor_name" data-live-search="true"
                >
                <option value="">CHOOSE VENDOR</option>
                <?php
                $vendors = mysqli_query($con, "SELECT * FROM vendor_master WHERE status='0'");
                while ($vendor = mysqli_fetch_array($vendors)) {
                  ?>
                  <option value="<?php echo $vendor['id']; ?>"><?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-6"><input type="text" id="billno" name="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-6"><input type="text" id="gatentry" name="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="text-input" class=" form-control-label">DEPARTMENT</label></div>
            <div class="col-12 col-md-6">
              <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-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">
            <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" class="form-control" onkeyup="calculateAmount()"></div>

    <div class="col-md-2"><label>QUM</label></div>
    <div class="col-md-4">
        <select class="form-control" id="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" class="form-control" onkeyup="calculateAmount()"></div>

    <div class="col-md-2"><label>AMOUNT</label></div>
    <div class="col-md-4"><input type="number" id="amount" class="form-control" readonly></div>
</div>

          <table id="items_get" class="table">
            <thead>
              <tr>
                <th scope="col">DEPARTMENT</th>
                <th scope="col">MATERIAL NAME</th>
                <th scope="col">QUANTITY</th>
                <th scope="col">MEASUREMENT</th>
                <th scope="col">RATE</th>
                <th scope="col">AMOUNT</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
          
          <div class="form-group"><button type="button" class="btn btn-primary" onclick="addrow()">ADD</button></div>
          <div class="row form-group">
            <div class="col-md-7"></div>
            <div class="col-md-2"><label for="total_amount" class="form-control-label">TOTAL AMOUNT</label></div>
            <div class="col-md-3"><input type="number" id="total_amount" name="total_amount" class="form-control"
                placeholder="Total Amount" readonly ></div>
          </div>
          <div class="row form-group">
            <div class="col-md-7"></div>
            <div class="col-md-2"><label for="cars" class=" form-control-label">GST TYPE:</label></div>
            <div class="col-md-3">
              <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-md-7"></div>
            <div class="col-md-2"><label for="gst_percentage" class="form-control-label">GST PERCENTAGE</label></div>
            <div class="col-md-3"><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-md-7"></div>
            <div class="col-md-2"><label for="text-input" class=" form-control-label">GST AMOUNT</label></div>
            <div class="col-md-3"><input type="number" id="gstamount" class="form-control" autocomplete="off" disabled>
            </div>
          </div>
          <div class="row form-group">
            <div class="col-md-7"></div>
            <div class="col-md-2"><label for="text-input" class=" form-control-label">DISCOUNT PERCENTAGE</label></div>
            <div class="col-md-3"><input type="number" id="discount" name="discount" class="form-control"
                autocomplete="off" Placeholder="0%" oninput="changeDiscount()"></div>
          </div>
          <div class="row form-group">
            <div class="col-md-7"></div>
            <div class="col-md-2"><label for="text-input" class=" form-control-label">DISCOUNT AMOUNT</label></div>
            <div class="col-md-3"><input type="number" id="discount_amount" class="form-control" autocomplete="off"
                disabled></div>
          </div>
          <div class="row form-group">
            <div class="col-md-7"></div>
            <div class="col-md-2"><label for="total_amount" class="form-control-label">FINAL AMOUNT</label></div>
            <div class="col-md-3"><input type="number" id="final_amount" name="final_amount" class="form-control"
                placeholder="Final 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>