<?php
// admin/invoice/addAll.php
header('Content-Type: text/html; charset=utf-8');
ini_set('display_errors', 1);
error_reporting(E_ALL);

include("../../classes/manager.class.php");
$m = new Manager();

$customerId   = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$customerMart = isset($_GET['customer']) ? (int)$_GET['customer'] : 0;

$catId = 0;
if ($customerId) {
  $cust = CustomerSetup::GetCustomerSetupById($customerId);
  if ($cust && isset($cust->category_id)) $catId = (int)$cust->category_id;
}

// Try to filter by product category if the column exists; otherwise fallback to all active
global $db;
$hasCatCol = $db->query_first("SHOW COLUMNS FROM ".TABLE_PRODUCTSETUP." LIKE 'category_id'");
$filter = " WHERE status='active' ";
if ($hasCatCol && $catId > 0) {
  $filter .= " AND category_id='{$catId}' ";
}
$filter .= " ORDER BY product_order";

$prods = ProductSetup::GetProductSetupList($filter);
if (!$prods) { echo ""; exit; }

foreach ($prods as $p) {
  $pid = (int)$p->id;

  // availability from FIFO stock
  $sum = $db->query_first("SELECT SUM(remaining_qty) AS rem 
                           FROM ".TABLE_STOCK." 
                           WHERE product_id='{$pid}' AND remaining_qty>0");
  $availability = ($sum && isset($sum->rem)) ? (int)$sum->rem : 0;

  $carton_pieces = (int)$p->carton_pieces;
  $unit          = htmlspecialchars($p->unit);
  $tp_rate       = number_format((float)$p->tp_rate, 2, '.', '');
  $sp_rate       = isset($p->sp_rate) ? number_format((float)$p->sp_rate, 2, '.', '') : $tp_rate;
  ?>
  <tr id="tr<?php echo $pid; ?>">
    <td></td>
    <td style="width:30px;height:30px;font-size:12px;line-height:15px;margin-top:11px;" class="mini-stat-icon orange darken-2">
      <i id="trashing<?php echo $pid; ?>" style="cursor:pointer;font-size:18px;margin-top:7px;" class="mdi-action-delete"></i>
    </td>
    <td>
      <input class="form-control" style="width:100%!important;" type="text" readonly value="<?php echo htmlspecialchars($p->name); ?>">
      <input type="hidden" name="products[]" value="<?php echo $pid; ?>">
    </td>
    <td id="carton">
      <input <?php echo ($carton_pieces==0?'disabled':''); ?> value="0"
             style="width:100%!important;" required maxlength="10"
             onkeypress="return isNumberKey(event)" class="form-control"
             type="text" name="totcarton<?php echo ($carton_pieces==0?'1':''); ?>[]" id="totcarton">
    </td>
    <td>
      <input style="width:100%!important;" required maxlength="10"
             onkeypress="return isNumberKey(event)" class="form-control" type="text"
             onchange="handleChange<?php echo $pid; ?>(this);" value="0" name="qty[]" id="qty">
    </td>
    <td>
      <input value="<?php echo $carton_pieces; ?>" type="hidden" name="carton_piece[]" id="cartonval">
      <input class="form-control" style="width:100%!important;" type="text" readonly value="<?php echo $unit; ?>">
      <input type="hidden" name="units[]" value="<?php echo $unit; ?>">
    </td>
    <td>
      <input style="width:100%!important;" required maxlength="10"
             onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text"
             name="unitcost[]" value="<?php echo $tp_rate; ?>" id="unitcost">
    </td>
  <!--  <td id="distributorField">
      <input style="width:100%!important;" required maxlength="10"
             onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text"
             name="unitdistributor[]" value="0.00" id="unitdistributor">
    </td> -->
    <td>
      <input style="width:100%!important;" required maxlength="10"
             onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text"
             name="unitsale[]" value="<?php echo $sp_rate; ?>" id="unitsale">
    </td>
    <td id="subTotal"></td>
  </tr>
  <script>
    $('#trashing<?php echo $pid; ?>').on('click', function () {
      $(this).closest('tr').remove();
      numbering(); Calculate();
    });
    function handleChange<?php echo $pid; ?>(input){
      var total = <?php echo (int)$availability; ?>;
      if (input.value < 0) input.value = 0;
      if (input.value > total) {
        input.value = total;
        if (window.dialog && dialog.alert) {
          dialog.alert({ title:"Stock Availability", message:"Stock not available, max "+ total, button:"Close", animation:"fade" });
        } else {
          alert("Stock not available, max " + total);
        }
        return false;
      }
    }
  </script>
  <?php
}
