<?php
// admin/invoice/addItem.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();

if (!isset($_GET['id']) || !ctype_digit($_GET['id'])) {
  http_response_code(400);
  echo "Missing or invalid product id";
  exit;
}

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

$qry = ProductSetup::GetProductSetupById($productId);
if (!$qry) {
  http_response_code(404);
  echo "Product not found";
  exit;
}

global $db;

// ---------------------------------------------------
// 1) Get customer's category_id
// ---------------------------------------------------
$catId = 0;
if ($customerId > 0) {
    $cust = CustomerSetup::GetCustomerSetupById($customerId);
    if ($cust && isset($cust->category_id)) {
        $catId = (int)$cust->category_id;
    }
}

// ---------------------------------------------------
// 2) Find latest invoice_rate for this category
//    (no status filter -> avoids mismatch issues)
// ---------------------------------------------------
$invoiceRateId = 0;
if ($catId > 0) {
    $rateRow = $db->query_first("
        SELECT id 
        FROM " . TABLE_INVOICE_RATE . " 
        WHERE customer_category_id = '{$catId}'
        ORDER BY create_date DESC
        LIMIT 1
    ");
    if ($rateRow && isset($rateRow->id)) {
        $invoiceRateId = (int)$rateRow->id;
    }
}

if ($invoiceRateId <= 0) {
    http_response_code(400);
    echo "No invoice rate defined for this customer's category.";
    exit;
}

// ---------------------------------------------------
// 3) Fetch rate detail for THIS product & rate
//    (no >0 filter on prices to avoid dropping rows)
// ---------------------------------------------------
$rateDetail = $db->query_first("
    SELECT *
    FROM " . TABLE_INVOICE_RATE_DETAIL . "
    WHERE invoice_rate_id = '{$invoiceRateId}'
      AND product_id      = '{$productId}'
    LIMIT 1
");

if (!$rateDetail) {
    http_response_code(400);
    echo "No invoice rate defined for this product in the selected customer's category.";
    exit;
}

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

$carton_pieces = (int)$qry->carton_pieces;
$unit          = htmlspecialchars($qry->unit);

// Prices from invoice_rate_detail instead of product_setup
$tp_rate = number_format((float)$rateDetail->unit_cost_price, 2, '.', '');
$sp_rate = number_format((float)$rateDetail->unit_sale_price, 2, '.', '');
?>
<tr id="tr<?php echo $productId; ?>">
  <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 $productId; ?>" 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($qry->name); ?>">
    <input type="hidden" name="products[]" value="<?php echo $productId; ?>">
  </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 $productId; ?>(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 style="display:none;">
    <input type="hidden"
           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 $productId; ?>').on('click', function () {
    $(this).closest('tr').remove();
    numbering(); 
    Calculate();
  });
  function handleChange<?php echo $productId; ?>(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>
