<?php include '../global-connect/global-connect.php';
include '../functions/inc.php';
include_once '../functions/shipping-expense-helper.php';

$searchpage=1;


$mess="";
session_start();
if(isset($_COOKIE[$info1000['software_version'].'user'])) {
$user=$_COOKIE[$info1000['software_version'].'user'];
$role=$_COOKIE[$info1000['software_version'].'role'];
$loginuser=$_COOKIE[$info1000['software_version'].'uid'];
$onrecord_id=$_COOKIE[$info1000['software_version'].'onrecord_id'];
$on_record = 1;
$current_company=$_COOKIE[$info1000['software_version'].'multi_company'];
$current_company2=$_COOKIE[$info1000['software_version'].'multi_company2'];


$current_zone=$_COOKIE[$info1000['software_version'].'current_zone'];
$current_warehouse=$_COOKIE[$info1000['software_version'].'current_warehouse'];

 
$current_costcenter=$_COOKIE[$info1000['software_version'].'cost_center']; 
$current_costcenter2=$_COOKIE[$info1000['software_version'].'cost_center2']; 
$po_qtyimpact = !empty($info3000['po_qtyimpact']) && (int)$info3000['po_qtyimpact'] === 1;

 


   
include '../functions/limit-multi.php';
$data = mysqli_query($conn,"SELECT * FROM employee e, user u where e.id=u.id && username='$user'") or die(mysqli_error($conn));
  
 $numcolumn = mysqli_num_fields($data);
 
 while($info = mysqli_fetch_array( $data )) 
 { 
 
 
  $en_vendor = mysqli_get_var("Select vendor_all from employee where id='$loginuser' ");
  $en_brand = mysqli_get_var("Select brand_all from employee where id='$loginuser' "); 
 
 

 
 
if (isset($_POST['submit'])) {



$old_si = test_input($_POST['old_si']);
$brand_input = isset($_POST['inv_brand']) ? $_POST['inv_brand'] : (isset($_POST['brandfilter']) ? $_POST['brandfilter'] : mysqli_get_var("SELECT brand_id FROM purchasing WHERE id='$old_si' "));
$brand_id = brandwise_normalize_id($brand_input);
$old_brand_id = brandwise_normalize_id(mysqli_get_var("SELECT brand_id FROM purchasing WHERE id='$old_si' "));
$old_paid = test_input($_POST['old_paid']);
$old_am = test_input($_POST['old_a']);
$old_tax = mysqli_get_var("Select SUM(debit-credit) from cash_transaction where arefer='$old_si' && `show`='1' && account_id='9' && transaction_type='2'  ");
$old_pending = $old_am - $old_paid;
$employee_id = test_input($_POST['employee_id']);   



$data9 = mysqli_query($conn,"SELECT * FROM cash_transaction WHERE arefer='$old_si' && (transaction_type=2 || transaction_type=34 ) && `show`=1   ") or die(mysqli_error($conn));

while($info9 = mysqli_fetch_array( $data9 )) 
 {
     
    $lcostcenter = $info9['cost_center'];
    $ldebit = $info9['debit'];
    $lcredit = $info9['credit']; 
    $laccount = $info9['account_id']; 

 $sql = "Update accounts_type Set balance=balance+'$lcredit'-'$ldebit' where id='$laccount' && costcenter_id='$lcostcenter'  && company_id='$current_company2' ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));   
     
 }

 $sql = "UPDATE  cash_transaction set `show`=0 where  arefer='$old_si'  && (transaction_type=2 || transaction_type=34 ) ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));   



$sales_id = test_input($_POST['sales_id']); 

if($sales_id == '')
  $sales_id = 19;

 $credit_account  = $_POST['credit_account'];
  $tax_account  = $_POST['tax_account'];    


$emp_id = test_input($_POST['emp_id']);



$dop = test_input($_POST['dop']);

$customer_id = test_input($_POST['vendor']);    


$old_customer_id = test_input($_POST['old_vendor_id']); 
















$notes = test_input($_POST['notes']);   
$bank = test_input($_POST['bank']); 
$inventory_execution = 1;

$memo= $notes;



if(isset($_POST['subc']))   
$subc = test_input($_POST['subc']); 
else $subc=0;

if(isset($_POST['discount_type']))
$discount_type = test_input($_POST['discount_type']);   
$discount_type=0;


$broken = test_input($_POST['broken']); 
$moisture = test_input($_POST['moisture']); 


$total_truck = test_input($_POST['total_truck']);   


$payment_terms = $_POST['payment_terms2'];
$delivery_terms = $_POST['delivery_terms2'];
$delivery_condition = $_POST['delivery_terms2'];
if($delivery_condition=='') $delivery_condition=0;



$create_by = test_input($_POST['create_by']);
$create_time = $_POST['create_time'];
$verified_by = test_input($_POST['verified_by']);
$verified_time = test_input($_POST['verified_time']);
$edit_by = $loginuser;
$edit_time = date("Y-m-d H:i:s");


if($create_time=='') { $create_time = date("Y-m-d H:i:s"); }
if($verified_time=='') { $verified_time = date("Y-m-d H:i:s"); }
if($create_by=='') { $create_by = $loginuser; }
if($verified_by=='') { $verified_by = $loginuser; }

$filesystem = test_input($_POST['filesystem']);
$filesystem2 = test_input($_POST['filesystem']);

 if(0) {    
 
$filesystem2 = mysqli_get_var("Select id from file_system where  name='$filesystem'  ") ;
 
if($filesystem2=='') {
    
$sql2 = "Insert into file_system (name,dealer_id,last_update)  VALUES ('$filesystem','$customer_id','$current_date')" ;
$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));


$data10 = mysqli_query($conn,"SELECT MAX(id) AS id FROM file_system") or die(mysqli_error($conn));
$info10 = mysqli_fetch_array( $data10 );
$filesystem2= $info10['id'];
     }  }
     
     
if($filesystem2=='') { $filesystem2=0; }     




if(empty($verified_time)){
    $verified_time=date("Y-m-d H:i:s");
}
// echo "Verified Time: ".$verified_time;

$lpo = test_input($_POST['lpo']);       

$serial = test_input($_POST['number']);     
if($serial==NULL || $serial=='')
$serial="0";
else $serial = test_input($_POST['number']);

$dcdate = test_input($_POST['dcdate']);     



$date = test_input($_POST['date']); 
if($date==NULL || $date=='')
$date=date("Y-m-d H:i:s");
else $date = test_input($_POST['date']);

$recurring_type = test_input($_POST['recurring_type']);
$recurring_qty = test_input($_POST['recurring_qty']);

if($recurring_type==1)
{
$recurring_date = date('Y-m-d H:i:s', strtotime("$date +".$recurring_qty." days")); 
}
else if($recurring_type==2)
{
$recurring_date = date('Y-m-d H:i:s', strtotime("$date +".$recurring_qty." months"));
}
else if($recurring_type==3)
{
$recurring_date = date('Y-m-d H:i:s', strtotime("$date +".$recurring_qty." years"));
}
else {
$recurring_date = $date;
    }



$cost_center = test_input($_POST['cost_center']);
$service_invoice = test_input($_POST['service_invoice']);
$discount = test_input($_POST['discount']); 

 if(isset($_POST['shipping']))
$shipping = test_input($_POST['shipping']); 
else $shipping =0;

 if(isset($_POST['tax']))
 {
$tax= test_input($_POST['tax']);
$atax= test_input($_POST['tax']);
}
 else {
     $tax=0; $atax=0;
 }

$order_id = test_input($_POST['order_id']); 

$grn_id = test_input($_POST['grn_id']); 
$allowed_pi_products = array();
if($po_qtyimpact) {
    if($order_id > 0) {
        $allowed_po_products_result = mysqli_query($conn,"SELECT DISTINCT prd_id FROM po_details WHERE order_id='$order_id'") or die(mysqli_error($conn));
        while($allowed_po_product = mysqli_fetch_array($allowed_po_products_result)) {
            $allowed_pi_products[(string)$allowed_po_product['prd_id']] = true;
        }
    }

    if($old_si > 0) {
        $allowed_invoice_products_result = mysqli_query($conn,"SELECT DISTINCT prd_id FROM purchasing_details WHERE order_id='$old_si'") or die(mysqli_error($conn));
        while($allowed_invoice_product = mysqli_fetch_array($allowed_invoice_products_result)) {
            $allowed_pi_products[(string)$allowed_invoice_product['prd_id']] = true;
        }
    }
}

$pending = test_input($_POST['pending_amount']*$_POST['currency_rate']);
$paid = test_input($_POST['paid']*$_POST['currency_rate']); 

 $slc_currency_rate = test_input($_POST['slc_currency_rate']);  

if($slc_currency_rate=='') $slc_currency_rate=0;


$company_invoice_num=test_input($_POST['company_invoice_num']);

if($company_invoice_num=='') $company_invoice_num=0;

$on_record5 = $_POST['on_record5'];

if($on_record5!='') { 
$on_record= $on_record5; 


}

else {


 if(isset($_POST['on_record']))
 { 
 
 $on_record = test_input($_POST['on_record2']);     
if($on_record==NULL || $on_record==0 || $on_record==''){
$on_record= mysqli_get_var("Select max(on_record) from purchasing ");  $on_record = $on_record+1; }
else {$on_record = test_input($_POST['on_record2']); }
 }
 else { $on_record=0; }

}






$data3 = mysqli_query($conn,"SELECT *  FROM purchasing_grn where id='$grn_id' ") or die(mysqli_error($conn));
$info3 = mysqli_fetch_array( $data3 );

$broker_id = $_POST['broker_id']; if($broker_id=='') $broker_id = 0;
$sauda_id = $info3['sauda_id']; if($sauda_id=='') $sauda_id = 0;
$dod = $info3['dod']; if($dod=='') $dod = 0;
$truck_type = $info3['truck_type']; if($truck_type=='') $truck_type = 0;


$total = test_input($_POST['total']);   

$pending_amount = $total-$old_paid; 







 $sql = "Delete from `purchasing` where id='$old_si'";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


// After Delete function 

// If not matched with form customer {{

// Customer fifo Function old customer id }}

if($old_customer_id!=$customer_id){
    supplierpaymentfifoclear($old_customer_id, $old_brand_id);  
}

// end






if(!$po_qtyimpact && $inventory_execution==1 && $grn_id==0) {


$data25 = mysqli_query($conn,"Select prd_id, qty, batch_id from purchasing_details WHERE order_id = '$old_si'") or die(mysqli_error($conn));
 $ocogs=0; 
while($info25 = mysqli_fetch_array( $data25 ))
{
$c2=$info25['prd_id'];
$q2=$info25['qty'];
$b2=$info25['batch_id'];


$c3 = mysqli_get_var("Select stock_effect from inventory WHERE id = '$c2'");    
if($c3==0) { $c3=$c2; }




$sql = "UPDATE  warehouse_transaction set `deleted`=1  where `item_id`='$c3' && `tran_type`='5' && `arefer`='$old_si'";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


$sql = "UPDATE inventory SET qty = qty-'$q2' WHERE id = '$c3'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


 $sql = "UPDATE inventory_batch SET qty = qty - '$q2' WHERE prd_id='$c3' &&  id = '$b2'" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));



}
}




$sql = "Delete from batch_references where tran_type='3' AND ref_id IN (SELECT id FROM purchasing_details WHERE order_id='$old_si')";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Delete from `purchasing_details` where order_id='$old_si'";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Delete from `pshipping` where sid='$old_si' && po=2";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


$month_id = test_input($_POST['month_id']); 


$currency = test_input($_POST['currency']); 
$currency_rate = test_input($_POST['currency_rate']);   
$currency_total = test_input($total);


// Date 11/5/2025
if($info3000['en_importexpense_currency'] == 0){
    $total = $total * 1;
}else{
    $total = $total * $currency_rate;
}

// Date end
// $total = test_input($_POST['currency_rate']*$total);

$kanta_weight = test_input($_POST['kanta_weight']); 
$factory_weight = test_input($_POST['factory_weight']); 


$party_id = $_POST['party_id'];
if($party_id == ''){
  $party_id = 0;
}

$daily_id = $_POST['daily_id'];
$no_of_trucks = $_POST['no_of_trucks'];

$distributor_to_id = ($_POST['distributor_to_id']) ? $_POST['distributor_to_id'] : 0;
$distributor_from_id = ($_POST['distributor_from_id']) ? $_POST['distributor_from_id']: 0;

$due_date = $_POST['due_date'];
if($info3000['en_sama']==1)
{
  $due_date = $_POST['due_date'];
}
else
{
  $due_date = "";
}


$vendor_id2 = $_POST['vendor_id2'];
if($vendor_id2=='') $vendor_id2=0;


$vendor_id3 = $_POST['vendor_id3'];
if($vendor_id3=='') $vendor_id3=0;

$create_time = test_input($_POST['create_time']);


  $shipping_value = test_input($_POST['shipping_value']);
    if($shipping_value==''){$shipping_value=0;}

$sql2 = "Insert into purchasing


(shipping, id, emp_id, sauda_id,  broker_id, dod, truck_type,  payment_terms, delivery_terms, delivery_condition, vendor_id, vendor_id2, vendor_id3, po_id, grn_id, total_amount,pending_amount,shipping_charges, tax_applied, discount,datetime,on_record, dop,  notes,serial, serial_date, inventory_execution, month_id, cost_center, service_invoice, recurring_type, recurring_date, recurring_qty,  currency, currency_rate, currency_total,  broken, moisture, create_by, create_time, verified_by, verified_time, edit_by, edit_time, filesystem_id, total_truck, party_id, sales_account, credit_account,  tax_account,  kanta_weight, factory_weight, daily_id, no_of_trucks, company_id,distributor_to_id,distributor_from_id,slc_currency_rate,company_invoice_no, due_date, brand_id)
VALUES ('$shipping_value', '$old_si','$emp_id', '$sauda_id', '$broker_id', '$dod', '$truck_type',  '$payment_terms', '$delivery_terms','$delivery_condition','$customer_id','$vendor_id2','$vendor_id3','$order_id','$grn_id','$total','$total','$shipping','$atax','$discount','$date','$on_record','$dop','$notes','$serial','$dcdate', '$inventory_execution', '$month_id', '$cost_center', '$service_invoice', '$recurring_type', '$recurring_date', '$recurring_qty', '$currency', '$currency_rate', '$currency_total', '$broken', '$moisture', '$create_by', '$create_time', '$verified_by', '$verified_time', '$edit_by', '$edit_time','$filesystem2', '$total_truck', '$party_id', '$sales_id', '$credit_account', '$tax_account','$kanta_weight','$factory_weight', '$daily_id', '$no_of_trucks', '$current_company', '$distributor_to_id', '$distributor_from_id', '$slc_currency_rate','$company_invoice_num', '$due_date', '$brand_id')" ;

$retval = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));

 
$sid= $old_si;

$total_recovery = mysqli_get_var("SELECT SUM(amount) FROM `ppayment_record` WHERE `invoice_id`='$old_si' && invoice_type=1   ");

if($total_recovery<=$total) { 

$pp = $total - $total_recovery;

$sql2 = "UPDATE purchasing set pending_amount='$pp' where id='$old_si' " ;
$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));


  } else {

$pp = $total_recovery - $total ;

$sql2 = "UPDATE purchasing set pending_amount='0' where id='$old_si' " ;
$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));

$result = mysqli_query($conn,"SELECT * FROM `ppayment_record` WHERE `invoice_id`='$old_si' && invoice_type=1  order by id DESC ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)){  
    $payment_id= $row['payment_id'];
    $amount= $row['amount'];
    $clear_type= $row['clear_type'];
    $cpid= $row['id'];
    
    $balance = $amount - $pp;
    
    if($balance<=0) { $remain=0; $tom = $amount; } else { $remain = $amount - $pp ; $tom = $pp; }
    
    $pp = $pp - $amount;
    
    
    
    
    $sql = "INSERT into `unadjust_ppayment_record` (payment_id, amount, clear_type) VALUES ('$payment_id', '$tom', '$clear_type') ";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


$sql = "Update `ppayment_record` set amount='$remain' where `id`='$cpid' ";
 $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

 if($pp<=0) break;

}


// $sql = "Delete from `ppayment_record` where `invoice_id`='$old_si' && invoice_type=1 ";
// $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

  }


if($info2000['meditech_singleinvoice']==1) {
    
$sql = "Update purchasing_grn set completed=0 where id in (Select grn_id from `pi_grn_link` where pi_id='$sid') ";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


$sql = "Delete from `pi_grn_link` where pi_id='$sid'";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


    
    
if (isset($_POST['grn_list'])) {

  for($i=0 ;$i < count($_POST['grn_list']); $i++) {

$c= $_POST['grn_list'][$i]; 


$sql2 = "update purchasing_grn set completed=1 where id='$c'" ;

$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));


$sql2 = "Insert into pi_grn_link

(pi_id, grn_id )
VALUES ('$sid','$c')" ;

$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));

  }
  }
}

$retval = mysqli_query($conn, " DELETE FROM rice_field_details WHERE sid = '$sid' AND stype = '6' " ) or die(mysqli_error($conn));
if (!empty($_POST['fid']) && is_array($_POST['fid'])) {
    foreach ($_POST['fid'] as $kk => $fid) {
        $values = $_POST['values'][$kk] ?? '';

        if ($values !== '') {
            $sql = "INSERT INTO rice_field_details (sid, fid, value, stype)
                    VALUES ('$sid', '$fid', '$values', '6')";
            $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
        }
    }
}




$rice_len = count(isset($_FILES['riceimage'])?$_FILES['riceimage']:[]);
$sql = "SELECT fid,(a.id) as idd,a.stype FROM `rice_field_details` as a ,rice_field as b  where a.fid = b.id and sid ='$sid' and b.itype='5' order by fid";
$res = mysqli_query($conn,$sql);

$kl=0;
while ($rowr = mysqli_fetch_array($res)) {
    $fidd = $rowr['fid'];
    $idd = $rowr['idd'];
   


   $stype = $rowr['stype']; 
 $ricefield_image_name = $sid.'_5_'.$fidd.'_'.$stype;
   if (!empty($_FILES["riceimage"]["name"][$kl])) {
       $file_name=$_FILES["riceimage"]["name"][$kl];
       $temp_name=$_FILES["riceimage"]["tmp_name"][$kl];
       $imgtype=$_FILES["riceimage"]["type"][$kl];

       if (GetImageExtension2($imgtype)) {
           $dir = "ricefield_images";
           if (!is_dir($dir)) {
               mkdir($dir);
           }
           $time = time();
           $ext = pathinfo($file_name, PATHINFO_EXTENSION);
           $f_name= $ricefield_image_name.'.'.$ext;
           $target_path = $dir.'/'.$f_name;

           if(move_uploaded_file($temp_name, $target_path)) {
               $values = $f_name;
               $sql = " update rice_field_details  set value='$values' where fid = '$fidd' and id='$idd' ";
               $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
           } else {
               echo "<script>alert('File is Invalid')</script>";
           }
       } else {
           echo "<script>alert('File extension is wrong')</script>";
       }
       $kl++;
   }
}
//edit rice


if($info3000['costing_weight'] == 1){
    $total_pcs_amount = 0;
    $total_weight_ = 0;
}
if (isset($_POST['products'])) {
    for($i=0 ;$i < count($_POST['products']); $i++) {
        $posted_product_id = $_POST['products'][$i];
        if($po_qtyimpact && !isset($allowed_pi_products[(string)$posted_product_id])) {
            continue;
        }
        $prdgross = $prdgross + $_POST['products_total'][$i];      
        if($info3000['costing_weight'] == 1){
        $total_pcs_amount = $_POST['products_pcs'][$i];
            $wei = isset($_POST['custom_field1'][$i]) ? (float)$_POST['custom_field1'][$i] : 0;
            if($wei <= 0){
                $wei = 1;
            }
            $total_weight_ = $total_weight_ +  ( $total_pcs_amount * $wei) ;
        
        }
   }
}   


if (isset($_POST['rice_discount']) && $info4000['ricecost_cogs']==1) {
 
 
$sql2 = "Delete from rice_purchase_discount where sid='$sid' && page='3'";

$retval = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn)); 


$data9 = mysqli_query($conn,"SELECT * FROM cash_transaction WHERE arefer IN (Select id from purchasing where pay_id='$sid' && truck_type=2 ) && (transaction_type=2 || transaction_type=34 ) && `show`=1   ") or die(mysqli_error($conn));

while($info9 = mysqli_fetch_array( $data9 )) 
 {
     
    $lcostcenter = $info9['cost_center'];
    $ldebit = $info9['debit'];
    $lcredit = $info9['credit']; 
    $laccount = $info9['account_id']; 

 $sql = "Update accounts_type Set balance=balance+'$lcredit'-'$ldebit' where id='$laccount' && costcenter_id='$lcostcenter'  && company_id='$current_company2' ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));   
     
 }



$sql = "UPDATE  cash_transaction set `show`=0 where  arefer IN (Select id from purchasing where pay_id='$sid' && truck_type=2 ) && cost_center='$lcostcenter' && (transaction_type=2 || transaction_type=34)";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


$sql2 = "Delete from purchasing_details where order_id IN (Select id from purchasing where pay_id='$sid' && truck_type=2 ) ";

$retval = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn)); 


$sql2 = "Delete from  purchasing where pay_id='$sid' && truck_type=2  ";

$retval = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn)); 



$max_id = $sid;
$expense_invoice_ids = array();
$expense_invoice_refs = array();
$expense_invoice_serials = array();
$expense_invoice_fifo_synced = array();


 //Date 11/5/2025
for($i=0 ;$i < count($_POST['rice_discount']); $i++) {
// Date End


$c= $_POST['rice_discount'][$i];      
$qty=$_POST['rice_discount_value'][$i];

if($info4000['ricecost_cogs']==1) {

    $rice_type = mysqli_get_var("Select amount_type from rice_discount where id = '$c' ");
    if($rice_type==1){
        if($_POST['rice_discount_value'][$i]!=0){
            $rice_charges_qty = ($prdgross/100)*($_POST['rice_discount_value'][$i]);    
        }
    }else{
      $rice_charges_qty = $_POST['rice_discount_value'][$i];
    }  

    $rice_charges += (float)$rice_charges_qty;;
}


$toggleclass=$_POST['addclass'][$i];


if($toggleclass=="")
{

$toggleclass=0;
}


if($qty!="")
{
    
 $sql25 = "Insert into rice_purchase_discount

(sid,type_id, amount, page,toggleclass)
VALUES ('$sid','$c','$qty', 3,'$toggleclass')" ;

$retval25 = mysqli_query($conn, $sql25 );



if($info4000['ricecost_cogs']==1)  {
    
//  }

$service_label = mysqli_get_var("Select label from rice_discount where id='$c' ") ;

$service_id = mysqli_get_var("Select service_id from rice_discount where id='$c' ") ;

$pvendor_id = mysqli_get_var("Select vendor_id from rice_discount where id='$c' ") ;



$coa_id = mysqli_get_var("Select coa_id from rice_discount where id='$c' ") ;

$coa_id2 = mysqli_get_var("Select coa_id2 from rice_discount where id='$c' ") ;

$specialclass = mysqli_get_var("Select specialclass from rice_discount where id='$c' ") ;
$specialclass2 = mysqli_get_var("Select specialclass2 from rice_discount where id='$c' ") ;
$specialclass_search = strtolower(trim($specialclass.' '.$specialclass2));

if (strpos($specialclass_search, 'usdcost') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'localcost') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'pkr_expence_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'agent_charges_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'transportation_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'shpping_charges_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'port_charges_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'examination_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'duty') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'assesment_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'miscellancous_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}

if (strpos($specialclass_search, 'convertion_rate_difference_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'fright_charges_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'insurance_charges_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'commission_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'packing_material_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}

if (strpos($specialclass_search, 'dealeraccount') !== false) {
if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}

if (strpos($specialclass_search, 'investoraccount') !== false) {
if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}

 if($service_id!= 0 && $pvendor_id != 0  && $qty>0)
             {
                $expense_amount = (float)$qty;

                if($info4000['en_nooriinternational']==1 && strpos($specialclass_search, 'brokery_bags') !== false) {
                    $expense_amount = $expense_amount * (float)$_POST['total_carton'];
                }

                $currency_amount = $expense_amount;
                if (strpos($specialclass_search, 'usdcost') !== false) {
                    $calculate_rate = $currency_amount * (float)$currency_rate;
                } else if (strpos($specialclass_search, 'localcost') !== false) {
                    $calculate_rate = $currency_amount;
                } else if($info3000['en_importexpense_currency'] == 0){
                    $calculate_rate = $currency_amount;
                } else {
                    $calculate_rate = $currency_amount * (float)$currency_rate;
                }

                $invoice_key = (string)$pvendor_id;
                if(!isset($expense_invoice_ids[$invoice_key])) {
                    $daily_id = get_max_daily_id("purchasing", $date, 0, $service_invoice, $current_company, $cost_center, $distributor_id);
                    $sql2 = "INSERT INTO purchasing (po_id,  broker_id, sauda_id, datetime, pending_amount, vendor_id, total_amount, currency_total, sales_account, type_component, daily_id, create_time, cost_center, company_id, serial,pr_id,currency,currency_rate, notes, pay_id,truck_type, brand_id)
                    VALUES ('0', '0', '0', '$date', '$calculate_rate', '$pvendor_id','$calculate_rate', '$currency_amount', '$coa_id', '3', '$daily_id', '$current_time', '$cost_center', '$current_company', '$serial','3','2','1','$service_label','$sid',2, '$brand_id')" ;

                    $retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));
                    $max_id = mysqli_get_var("SELECT MAX(id) AS id FROM purchasing");
                    $expense_invoice_ids[$invoice_key] = $max_id;

                    $data20 = mysqli_query($conn,"SELECT max(ref_id) as max from cash_transaction") or die(mysqli_error($conn));
                    $info20 = mysqli_fetch_array( $data20 );
                    $expense_invoice_refs[$invoice_key] = $info20['max']+1;
                    $expense_invoice_serials[$invoice_key] = mysqli_get_var("SELECT COALESCE(MAX(serial_code),0)+1 FROM cash_transaction WHERE 1=1 AND cost_center = '$cost_center' AND sales_type='1' $serialby_month1  $serialby_year1  ");

                    if($info4000['en_vgm']==1){
                        $ricedata  =mysqli_get_var("SELECT GROUP_CONCAT(a.label,': ',b.value) as rice_data  FROM `rice_field_details` as b ,rice_field as a
                        WHERE a.id=b.fid and  b.sid in($sid) and b.stype='6'");
                        if ($ricedata!='') {
                            $note = mysqli_get_var("select notes from purchasing where id ='$max_id'");
                            $note = $note.' '.$ricedata;
                            $sql = "UPDATE purchasing SET notes = '$note' WHERE id = '$max_id'" ;
                            $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
                        }
                    }
                } else {
                    $max_id = $expense_invoice_ids[$invoice_key];
                    mysqli_query($conn, "UPDATE purchasing SET pending_amount = pending_amount + '$calculate_rate', total_amount = total_amount + '$calculate_rate', currency_total = currency_total + '$currency_amount' WHERE id = '$max_id'") or die(mysqli_error($conn));
                }

                $tax_type = mysqli_get_var("SELECT is_taxable FROM services WHERE id = '$service_id' ");
                $sql = "INSERT INTO purchasing_details (order_id, prd_id, packing, packing2, prd_amount, `tp`, qty, warehouse_id, tax_type) VALUES ('$max_id', '$service_id', '1', '1', '$currency_amount', '$currency_amount', '1', '1', '$tax_type')";
                $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

                if($info2000['enable_unadjustpaymentp']==0 && !isset($expense_invoice_fifo_synced[$invoice_key])) {
                    supplierpaymentfifoclear($pvendor_id, $brand_id);
                    $expense_invoice_fifo_synced[$invoice_key] = 1;
                }

                $ref_id = $expense_invoice_refs[$invoice_key];
                $serial_code = $expense_invoice_serials[$invoice_key];
                $daily_id = get_max_daily_id("cash_transaction", $date, 0, $service_invoice, $current_company, $cost_center, $distributor_id);

                if($coa_id2!=0) {
                    $sql = "INSERT INTO cash_transaction (datetime, account_id, debit, credit, ref_id, description, transaction_type, arefer, cost_center, on_record, sales_type,  user_type, user_id , create_time, create_by, company_id, serial_code, filesystem_id, daily_id, verified_by, verified_time )
                    VALUES ('$date', '$coa_id2', '0', '$calculate_rate', '$ref_id', '$service_label',  2, '$max_id', '$cost_center', '0', '1', '0', '0', '$current_time', '$loginuser' , '$current_company2', '$serial_code', '0', '$daily_id', '$loginuser', '$current_time')" ;
                    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

                    $sql = "Update accounts_type Set balance=balance-'$calculate_rate' where id='$coa_id2' && costcenter_id='$cost_center'  $caccounts_company";
                    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
                }

                if($coa_id!=0) {
                    $sql = "INSERT INTO cash_transaction (datetime, account_id, credit, debit,  ref_id, description, transaction_type, arefer, cost_center, on_record, sales_type,  user_type, user_id , create_time, create_by, company_id, serial_code, filesystem_id, daily_id, verified_by, verified_time )
                    VALUES ('$date', '$coa_id', '0', '$calculate_rate', '$ref_id', '$service_label',  2, '$max_id', '$cost_center', '0', '1', '0', '0', '$current_time', '$loginuser' , '$current_company2', '$serial_code', '0', '$daily_id', '$loginuser', '$current_time')" ;
                    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

                    $sql = "Update accounts_type Set balance=balance+'$calculate_rate' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
                    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
                }

                if($info4000['ricecost_cogs']==1 && $info3000['en_ajk'] == 0) {
                    $purchase_account = $sales_id;
                    $check_inventory = mysqli_get_var("select count(id) as count from cash_transaction where account_id = '$purchase_account' and ref_id = '$ref_id' and transaction_type = 2 And arefer = '$max_id' ");
                    if($check_inventory==0){
                        $sql = "INSERT INTO cash_transaction (datetime, account_id, debit, credit, ref_id, description, transaction_type, arefer, cost_center, on_record, sales_type,  user_type, user_id , create_time, create_by, company_id, serial_code, filesystem_id, daily_id, verified_by, verified_time )
                        VALUES ('$date', '$purchase_account', '$currency_amount', '0', '$ref_id', 'Inventory Effect',  2, '$max_id', '$cost_center', '0', '1', '0', '0', '$current_time', '$loginuser' , '$current_company2', '$serial_code', '0', '$daily_id', '$loginuser', '$current_time')" ;
                        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

                        $sql = "Update accounts_type Set balance=balance+'$currency_amount' where id='$purchase_account' && costcenter_id='$cost_center'  $caccounts_company";
                        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
                    }else{
                        $sql = "Update cash_transaction Set debit = debit+'$currency_amount' where account_id = '$purchase_account' and ref_id = '$ref_id' and transaction_type = 2 And arefer = '$max_id' " ;
                        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

                        $sql = "Update accounts_type Set balance=balance+'$currency_amount' where id='$purchase_account' && costcenter_id='$cost_center'  $caccounts_company";
                        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
                    }
                }
            }

} } } } 






$tr = test_input($_POST['tr']);

if($tr=='y')
{
    
if (isset($_POST['shipping_details'])) {
 
 
  foreach ($_POST['shipping_details'] as $n) {  

$tr_num = $_POST[$n.'tr_num'];
$tr_name = $_POST[$n.'tr_name'];
$tr_qty = $_POST[$n.'tr_qty'];
$tr_date = $_POST[$n.'tr_date'];


if($tr_date==NULL || $tr_date=='')
$tr_date=date("Y-m-d H:i:s");
else $tr_date = test_input($_POST[$n.'tr_date']);


if($tr_num!='' || $tr_name!='')
{
    
$sql25 = "Insert into pshipping

(sid,num,name,qty,datetime,po)
VALUES ('$sid','$tr_num','$tr_name','$tr_qty','$tr_date',2)" ;

$retval25 = mysqli_query($conn, $sql25 )  or die(mysqli_error($conn));



}
    }
}

}



$data20 = mysqli_query($conn,"SELECT max(wref_id) as max from warehouse_transaction") or die(mysqli_error($conn));
  
$info20 = mysqli_fetch_array( $data20 );
 $wref_id=$info20['max']+1;
 
 
    
if (isset($_POST['products'])) {
 
  for($i=0 ;$i < count($_POST['products']); $i++){
      
$c= $_POST['products'][$i];   
if($po_qtyimpact && !isset($allowed_pi_products[(string)$c])) {
    continue;
}
$qty=$_POST['products_pcs'][$i];
$description=test_input($_POST['products_description'][$i]);

$custom_field1=$_POST['custom_field1'][$i];
$custom_field2=$_POST['custom_field2'][$i];
$custom_field3=$_POST['custom_field3'][$i];
$custom_field4=$_POST['custom_field4'][$i];
$custom_field5=$_POST['custom_field5'][$i];
$custom_field6=$_POST['custom_field6'][$i];


$uom=$_POST['uom'][$i];
if($uom == '')
    $uom = 0;
    
    
    if(isset($_POST['products_foc'][$i])) {
$pfoc=$_POST['products_foc'][$i];
}
else {
    $pfoc=0;
    }
    
    
    
if($_POST['price_slc'][$i]!='') { $custom_field1=$_POST['price_slc'][$i]; } 

$pamount=$_POST['products_total'][$i];
$packing=$_POST['products_packing'][$i];
$discount=$_POST['products_discount'][$i];

$unitcos=$_POST['unitcos'][$i];


 
$munit=$_POST['munit'][$i];
$con_rate=$_POST['con_rate'][$i];
$munit = ($munit) ? $munit : 0;
$con_rate = ($con_rate) ? $con_rate : 0;





if(isset($_POST['products_warehouse'][$i])) {
$pwarehouse=$_POST['products_warehouse'][$i];
}
else {
    $pwarehouse=0;
    }
    

    


    
    
    
if(isset($_POST['products_batch'][$i])) {
    
    
$batch_old=$_POST['batch_old'][$i];

if($batch_old==1) {
$pbatch=$_POST['products_batch'][$i];
}
else {

$pbatch=$_POST['products_batch'][$i];
$pexpiry=$_POST['products_expiry'][$i];

$sql = "Insert into inventory_batch
(batch_code, prd_id, exp_date)
VALUES ('$pbatch','$c','$pexpiry')";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$pbatch = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0"); 

    
    }   
    }
else {
    $pbatch=0;
    }   
$taxtype=$_POST['taxtype'][$i];
$ptax=$_POST['products_tax'][$i];
$ptax2=$_POST['products_tax2'][$i];
$ptax3=$_POST['products_tax3'][$i];
$aptax=$_POST['products_tax'][$i];


$discount=$_POST['products_discount'][$i];
$discount2=$_POST['products_discount2'][$i];
$discount3=$_POST['products_discount3'][$i];
$discount4=$_POST['products_discount4'][$i];
$pscheme=$_POST['products_scheme'][$i];
$pscheme_qty=$_POST['products_scheme_qty'][$i];
if($pscheme_qty==''){$pscheme_qty = 0;}

$packing2=$_POST['packing2'][$i];
if($info4000['en_engineering']==1){
    $stitch_pcss=$_POST['stitch_pcs'][$i];
  
  $piperate=$_POST['pipe'][$i];
  $custom_field4 = $piperate;
    $packing2 = $stitch_pcss;
      $packing2 = ($stitch_pcss=='')?'0':$stitch_pcss;
    
    
    
  }

$mrp_price=$_POST['mrp_price'][$i];
$tax_mrp=$_POST['tax_mrp'][$i];

if($qty!=0)
{
    
    
    


if($ptax!=0 || $ptax!=0 || $ptax!=0 ) { 

    
$taxpercent = ($ptax + $ptax2 + $ptax3);
$singlep = ($_POST['unitcos'][$i]) * $qty;
// $pptax = $taxpercent * $singlep;


$gross = mysqli_get_var("SELECT tp * qty as gross FROM purchasing_grn_details where order_id='$serial' and prd_id='$c' ");
$discount3_final = $gross/100 * $discount3;
$discount2_final = $gross/100 * $discount2;
$discount_final = $gross/100 * $discount;

$is_taxable = mysqli_get_var("SELECT is_taxable FROM inventory WHERE id = '$c' ");
if($is_taxable == 3){
    if($tax_mrp==1) { 
        if($info2000['simple_mrptax']==1) { 
            $mrp_tot = $qty*$mrp_price; 
            $mrp_tot = $mrp_tot - $discount3;
            $mrp_tot = $mrp_tot - ($qty * ($discount/100));
            $mrptax = $mrp_tot*(1+($taxpercent/100));  
            $atax = $mrptax - $mrp_tot;   
        } else {   
            $mrp_tot = $qty*$mrp_price; 
            $mrp_tot = $mrp_tot - $discount3;
            $mrp_tot = $mrp_tot - ($qty * ($discount/100));
            $mrptax = $mrp_tot/(1+($taxpercent/100));  
            $atax = $mrp_tot - $mrptax; 
        }   
        $tatax = $tatax + $atax; 
    } else {
        // $taxpercent = ($ptax + $ptax2 + $ptax3)/100;
        // $singlep = ($_POST['unitcos'][$i]) * $qty;
        // $singlep1 = $singlep * ($discount/100);
        // $singlep3 = $singlep * $discount3;
        // $atax = ($singlep - ($singlep1+$singlep3)) * $taxpercent;

            // $taxpercent = ($ptax + $ptax2 + $ptax3)/100;
        // $singlep = ($_POST['unitcos'][$i]) * $qty;
        // $singlep1 = $singlep * ($discount/100);
        // $singlep3 = $singlep * $discount3;
        // $atax = ($singlep - ($singlep1+$singlep3)) * $taxpercent;

        $taxpercent = ($ptax + $ptax2 + $ptax3)/100;
        $atax=$amount_after_discount * $taxpercent;
    }
}else{
    if($tax_mrp==1) { 
        if($info2000['simple_mrptax']==1) { 
            $mrp_tot = $qty*$mrp_price;  
            $mrptax = $mrp_tot*(1+($taxpercent/100));  
            $atax = $mrptax - $mrp_tot;   
        } else {   
            $mrp_tot = $qty*$mrp_price;  
            $mrptax = $mrp_tot/(1+($taxpercent/100));  
            $atax = $mrp_tot - $mrptax; 
        }   
        $tatax = $tatax + $atax; 
    } else { 
        /*$atax = $pamount-($gross-$discount1-$discount2-$discount3); 
        $tatax = $tatax + $atax;*/
        $taxpercent = ($ptax + $ptax2 + $ptax3)/100;
        $singlep = ($_POST['unitcos'][$i]) * $qty;
        $atax = $taxpercent * $singlep;  
    }
}

$pptax = $atax;

$total_tax=$total_tax+$pptax;

}


if(is_decimal($total_tax)){  $total_tax = number_format($total_tax,$info2000['total_decimal'], '.', ''); }



$totbags = (int)$totbags + (int)$custom_field1;

$tota = $tota + $pamount;
    
$rate_in_carton = $_POST['rate_in_carton'][$i]; 
    
if($info1000['en_pos']==1) {

$sale_price=$_POST['sale_price'][$i];
    
$sql = "UPDATE inventory SET `mrp_price`='$sale_price' WHERE id = '$c'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    
    
}
    
if($info4000['en_engineering']==1){

    if($rate_in_carton=='3'){
        
        $qty = $custom_field1;
        
    }}
    
    
    $w_unit_cost = $pamount/$qty;


// Date 11/5/2025
// if($info4000['ricecost_cogs']==1) {
// // $arice_charges = $rice_charges * ($pamount/$prdgross);
// $arice_charges = $rice_charges / ($total_pcs_amount * $total_weight_) ;

// $arice_charges_to = $arice_charges + $pamount;
// // $w_unit_cost = $arice_charges_to/$qty;
// $w_unit_cost = $arice_charges + $w_unit_cost;

// $brice_charges = $brice_charges + $arice_charges;
    

// // echo $w_unit_cost;
// // return;

// }
if($info4000['ricecost_cogs']==1) {

$arice_charges = $rice_charges * ($pamount/$prdgross);

if($info3000['costing_weight'] == 1){
  $weight_per_unit = isset($_POST['custom_field1'][$i]) ? (float)$_POST['custom_field1'][$i] : 0;
  if($weight_per_unit <= 0){
    $weight_per_unit = 1;
  }
  if($total_weight_ <= 0){
    $total_weight_ = 1;
  }
  $weighted_charge_share = $rice_charges * (($qty * $weight_per_unit) / $total_weight_);
  $w_unit_cost = $w_unit_cost + ($weighted_charge_share / $qty);
}else{  
  $arice_charges_to = $arice_charges + $pamount;
  $w_unit_cost = $arice_charges_to/$qty;
}

$brice_charges = $brice_charges + $arice_charges;

}
if($info3000['en_importexpense_currency'] == 0){
    $w_unit_cost = $w_unit_cost * 1;
}else{
    $w_unit_cost = $w_unit_cost * $_POST['currency_rate'];
}


// Date end
// $w_unit_cost = $w_unit_cost * $_POST['currency_rate'];


if (!isset($w_unit_cost) || $w_unit_cost === '' || $w_unit_cost === null || strtoupper($w_unit_cost) === 'NAN') {
    $w_unit_cost = 0;
}



if($info4000['en_razik']==0)  {
$totinventory = $totinventory+($w_unit_cost*$qty);  

} else {

$totinventory = $totinventory+$total;   

}

$smartbatch_enabled = ($info3000['en_smartbatch']==1 && isset($_POST['smartbatch_data'][$i]) && trim($_POST['smartbatch_data'][$i])!='');
$smart_batches = array();
if($smartbatch_enabled) {
  $smart_batches = json_decode($_POST['smartbatch_data'][$i], true);
  if(!is_array($smart_batches) || count($smart_batches)==0) {
    $smartbatch_enabled = false;
  }
}
if($smartbatch_enabled) {
  $unit_price = 0;
  if ($qty > 0) {
    $unit_price = $pamount / $qty;
  }
  foreach($smart_batches as $sb_item) {
    if(!is_array($sb_item)) { continue; }
    $sb_batch_code = isset($sb_item['batch']) ? trim($sb_item['batch']) : '';
    $sb_qty = isset($sb_item['qty']) ? floatval($sb_item['qty']) : 0;
    if($sb_batch_code=='' || $sb_qty<=0) { continue; }
    $sb_batch_id = mysqli_get_var("SELECT id FROM inventory_batch WHERE prd_id='$c' AND batch_code='$sb_batch_code' AND type_component=0 LIMIT 1");
    if($sb_batch_id=='') { $sb_batch_id = 0; }
    $sb_total = $unit_price * $sb_qty;
    $sql = "Insert into purchasing_details

    (order_id,prd_id,prd_amount,`tp`, mrp_price, tax_mrp, custom_field1, custom_field2, custom_field3,custom_field4, custom_field5, custom_field6, qty, packing, packing2,discount,discount2,discount3,discount4,scheme,scheme_qty, tax_applied,tax_applied2,tax_applied3, tax_type,  warehouse_id, batch_id, details2,  rate_in_carton, uom, foc, unit)

    VALUES ('$sid','$c','$sb_total' ,'$unitcos','$mrp_price', '$tax_mrp','$custom_field1','$custom_field2','$custom_field3','$custom_field4','$custom_field5','$custom_field6','$sb_qty','$packing','$packing2','$discount','$discount2','$discount3','$discount4','$pscheme','$pscheme_qty', '$aptax','$ptax2','$ptax3', '$taxtype','$pwarehouse', '$sb_batch_id', '$description'
    , '$rate_in_carton', '$uom','$pfoc', '$munit')";

    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    $purchase_detail_id = mysqli_insert_id($conn);
    $sql_ref = "Insert into batch_references
    (ref_id, tran_type, prd_id, qty, batch_id, batch_code, warehouse_id, uom)
    VALUES ('$purchase_detail_id','3','$c','$sb_qty','$sb_batch_id','$sb_batch_code','$pwarehouse','$uom')";
    $retval_ref = mysqli_query($conn, $sql_ref ) or die(mysqli_error($conn));
  }
} else {
  $sql = "Insert into purchasing_details

  (order_id,prd_id,prd_amount,`tp`, mrp_price, tax_mrp, custom_field1, custom_field2, custom_field3,custom_field4, custom_field5, custom_field6, qty, packing, packing2,discount,discount2,discount3,discount4,scheme,scheme_qty, tax_applied,tax_applied2,tax_applied3, tax_type,  warehouse_id, batch_id, details2,  rate_in_carton, uom, foc, unit)

  VALUES ('$sid','$c','$pamount' ,'$unitcos','$mrp_price', '$tax_mrp','$custom_field1','$custom_field2','$custom_field3','$custom_field4','$custom_field5','$custom_field6','$qty','$packing','$packing2','$discount','$discount2','$discount3','$discount4','$pscheme','$pscheme_qty', '$aptax','$ptax2','$ptax3', '$taxtype','$pwarehouse', '$pbatch', '$description'
  , '$rate_in_carton', '$uom','$pfoc', '$munit')";

  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}

if(!$po_qtyimpact && $info3000['en_hapaperhub'] == 1 && !empty($custom_field1)) 
{
    $data22 = mysqli_query($conn,"SELECT batch_no from warehouse_transaction where arefer = '$sid' && tran_type = '5' && item_id = '$c' ") or die(mysqli_error($conn));
        
    while($info22 = mysqli_fetch_array( $data22 )) 
    { 
        $batchnumber = $info22['batch_no'];
        $sql = "Delete from `inventory_batch` where prd_id='$c' && id = '$batchnumber' ";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        
        $sql = "Delete from `warehouse_transaction` where item_id='$c' && arefer = '$sid' && tran_type = '5' && batch_no = '$batchnumber' ";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    }
    
    $current_date = date('d/m/Y');
    $batch_values = explode(',', $custom_field1);
    $batch_total_qty = array_sum(array_map('trim', $batch_values)); 

    foreach($batch_values as $batch_value_raw) 
    {
        $batch_single_value = trim($batch_value_raw);
        if(empty($batch_single_value)) continue;

        $new_batch_code = $current_date . '-' . $batch_single_value;

        $check_batch_sql = "SELECT id, qty FROM inventory_batch 
                      WHERE prd_id = '$c' 
                      AND batch_code = '$new_batch_code' 
                      AND type_component = 0";
        $check_batch_result = mysqli_query($conn, $check_batch_sql);

        if(mysqli_num_rows($check_batch_result) > 0) 
        {
            $batch_row = mysqli_fetch_assoc($check_batch_result);
            $current_batch_id = $batch_row['id'];
            
            $check_tran_sql = "SELECT id, qty FROM warehouse_transaction 
                           WHERE item_id = '$c' 
                           AND batch_no = '$current_batch_id' 
                           AND warehouse_id = '$pwarehouse'";
            $tran_result = mysqli_query($conn, $check_tran_sql);

            if(mysqli_num_rows($tran_result) > 0) 
            {
                $tran_row = mysqli_fetch_assoc($tran_result);
                $existing_tran_qty = (float)$tran_row['qty'];
                $new_tran_qty = $existing_tran_qty + $batch_total_qty;

            
                
                $update_tran_sql = "UPDATE warehouse_transaction 
                               SET qty = '$new_tran_qty' 
                               WHERE id = '".$tran_row['id']."'";
                mysqli_query($conn, $update_tran_sql) or die(mysqli_error($conn));
            } 
            else 
            {       
                echo 'arrive';
                return;
                $insert_tran_sql = "INSERT INTO warehouse_transaction
                         (item_id, qty, item_cost, warehouse_id, company_id, tran_type, 
                          `datetime`, `wref_id`, arefer, atran_type, cvuser, batch_no, packing)
                         VALUES 
                         ('$c', '$batch_total_qty', '$w_unit_cost', '$pwarehouse', '$current_company2',
                          '5', '$date', '$wref_id', '$sid', '1', '$customer_id', '$current_batch_id', '$packing')";
                mysqli_query($conn, $insert_tran_sql) or die(mysqli_error($conn));
            }
        } 
        else 
        {
            echo 'not arrive';
                return;
            
            $insert_batch_sql = "INSERT INTO inventory_batch
                           (batch_code, prd_id, qty, exp_date, type_component)
                           VALUES ('$new_batch_code', '$c', '$batch_total_qty', NULL, 0)";
            mysqli_query($conn, $insert_batch_sql) or die(mysqli_error($conn));

            $new_batch_id = mysqli_insert_id($conn);
            
            $insert_new_tran_sql = "INSERT INTO warehouse_transaction
                     (item_id, qty, item_cost, warehouse_id, company_id, tran_type, 
                      `datetime`, `wref_id`, arefer, atran_type, cvuser, batch_no, packing)
                     VALUES ('$c', '$batch_total_qty', '$w_unit_cost', '$pwarehouse', '$current_company2',
                      '5', '$date', '$wref_id', '$sid', '1', '$customer_id', '$new_batch_id', '$packing')";
            
            mysqli_query($conn, $insert_new_tran_sql) or die(mysqli_error($conn));
        }
    }


}


if($info1000['rate_incartonp']==1) { $unitcos2 = $unitcos/$packing; } else { $unitcos2 = $unitcos; }



    
if(!$po_qtyimpact && $inventory_execution==1 && $grn_id==0 && $info3000['en_hapaperhub'] == 0) {


    
$c2 = mysqli_get_var("Select stock_effect from inventory WHERE id = '$c'"); 
if($c2==0) { $c2=$c; }

$sql = "UPDATE inventory SET qty=qty+'$qty' where id='$c2'";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


if($info1000['en_inventorybatch']==1) {

$sql = "UPDATE inventory_batch SET qty = qty + '$qty' WHERE prd_id='$c2' &&  id = '$pbatch'" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}

$noentrywarhose = 0;

if ($info1000['en_recurringinvoices']==1) {
   

$sioldcount = mysqli_get_var("SELECT count(id) FROM `purchasing` where recurring_type>0 and id != '$old_si' and po_id ='$order_id' and id<'$old_si'");




    $noentrywarhose = 0;
    if ($sioldcount>0) {
      $noentrywarhose = 1;
    }
}


if ($noentrywarhose!=1) {

if($info4000['en_umarsons']==1) {  $qty = $qty - $pfoc; }

$actual_qty = $qty + $pfoc;

$sql2 = "Insert into warehouse_transaction
(item_id, qty, item_cost, warehouse_id, company_id, tran_type, `datetime`, `wref_id`, arefer, atran_type, cvuser,  batch_no, foc )
VALUES ('$c2','$actual_qty','$w_unit_cost','$pwarehouse','$current_company2','5','$date','$wref_id','$sid','1','$customer_id','$pbatch', '$pfoc')" ;

$retval2 = mysqli_query($conn, $sql2) or die(mysqli_error($conn));

}


}


}

if(!$po_qtyimpact && $info4000['ricecost_cogs']==1) {
if($w_unit_cost == '' || $w_unit_cost == null){
    $w_unit_cost = 0;
}
$sql = "update warehouse_transaction  set item_cost='$w_unit_cost' where arefer='$grn_id' AND item_id='$c' AND tran_type=26 && deleted=0 ";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "update warehouse_transaction  set item_cost='$w_unit_cost' where arefer='$sid' AND item_id='$c' AND tran_type=5 && deleted=0 ";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    

}



if($info4000['en_shopify']==1 && 1==2) {

updatestocked(0,$c2);

} 



}


 //Update Costing WRT Rice amounts
 if($info4000['ricecost_cogs']==1 && 1==2) {
    
    if($info2000['rice_discount']==1) {
      if (isset($_POST['rice_discount']) ) {
        $total_rice = 0;
        for($i=0 ;$i < count($_POST['rice_discount']); $i++) {
          $total_rice+=$_POST['rice_discount_value'][$i];
        }   
  
        if($info3000['weight_cost']==1){
          $total_prd_qty = mysqli_get_var("select sum(qty) as total_qty from purchasing_details where order_id = '$sid' ");
          $r_final_cost = $total_rice/$total_prd_qty;
        }else{
          $total_prd_amount = mysqli_get_var("select sum(prd_amount) as total_amount from purchasing_details where order_id = '$sid' ");
          $r_final_cost = $total_rice/$total_prd_amount;
        }         
  
        for($i=0 ;$i < count($_POST['products']); $i++) {
            
            
          $c= $_POST['products'][$i];     
          if($po_qtyimpact && !isset($allowed_pi_products[(string)$c])) {
            continue;
          }
  
          if($info3000['weight_cost']==1){
            $qty=$_POST['products_pcs'][$i];
            $rice_added_cost = $r_final_cost * $qty;
          }else{
            $amount=$_POST['products_total'][$i];
            $rice_added_cost = $r_final_cost * $amount;
          }
  
          if(!$po_qtyimpact && $info1000['en_grn']==1){
            if($rice_added_cost == '' || $rice_added_cost == null){
                $rice_added_cost = 0;
            }

            $sql = "update warehouse_transaction  set item_cost=item_cost+'$rice_added_cost' where arefer='$grn_id' AND item_id='$c' AND tran_type=26 && deleted=0 ";
            $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));  
          }
         
          
          
          if(!$po_qtyimpact) {
            $sql = "update warehouse_transaction  set item_cost=item_cost+'$rice_added_cost' where arefer='$sid' AND item_id='$c' AND tran_type=5 && deleted=0 ";
            $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));  
          }
  
        }
      }
    }    
  
  
  }
  

}





$data20 = mysqli_query($conn,"SELECT max(ref_id) as max from cash_transaction") or die(mysqli_error($conn));
  
$info20 = mysqli_fetch_array( $data20 );
 $ref_id=$info20['max']+1;  


$total_tax = $_POST['invoice_tax'];


$total_paid = $total - $total_tax;


if($info1000['rate_incartonp']==0) {
    $adisc = mysqli_get_var("SELECT SUM(tp*qty) AS disc1 FROM purchasing_details WHERE order_id='$sid' ");
    $adiscless = mysqli_get_var("SELECT SUM(((tp*qty*(1-(discount/100)))*(1-(discount2/100)))) AS disc1 FROM purchasing_details WHERE order_id='$sid' "); 
    $adiscless2 = mysqli_get_var("SELECT SUM(qty*discount3) AS disc1 FROM purchasing_details WHERE order_id='$sid' "); 

    $adisc = $adisc - $adiscless;
    $adisc = abs($adisc - $adiscless2);
}
else {
    $adisc = mysqli_get_var("SELECT SUM(tp*(qty/packing)) AS disc1 FROM purchasing_details WHERE order_id='$sid'");
    $adiscless = mysqli_get_var("SELECT SUM(((tp*(qty/packing)*(1-(discount/100)))*(1-(discount2/100)))*(1-(discount4/100))) AS disc1 FROM purchasing_details WHERE order_id='$sid' ");     
    $adisc = $adisc - $adiscless;
}

if(is_decimal($adisc)){  $adisc = number_format($adisc,$info2000['total_decimal'], '.', ''); }

$total_paid = $total_paid + $adisc;




if($adisc!=0){
    $sql = "Insert into cash_transaction 
    (datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
    VALUES ('$date','11','$adisc','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

    $sql = "Update accounts_type Set balance=balance+'$adisc' where id='11'  && costcenter_id='$cost_center' $caccounts_company";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}




if(1==2)
{


$sql = "Insert into cash_transaction
(datetime, account_id, debit,  ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
VALUES ('$date','8','$total' ,'$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Update accounts_type Set balance=balance+'$total_paid' where id='8'   && costcenter_id='$cost_center' $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


    
    }
else {

$sql = "Insert into cash_transaction
(datetime, account_id, debit,  ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
VALUES ('$date','$sales_id','$total','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sales_id22 = mysqli_get_var("SELECT MAX(id) as cc FROM cash_transaction WHERE 1=1 ");

$sql = "Update accounts_type Set balance=balance+'$total' where id='$sales_id'   && costcenter_id='$cost_center' $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));



}

// Date 11/5/2025
if($info4000['ricecost_cogs']==1 && $arice_charges!=0 && $info4000['en_razik']==0 && $info3000['en_ajk']==0)  {
//Date End
$ricediscountexpense_account = $info4000['ricediscountexpense_account'];
    
$sql = "Insert into cash_transaction
(datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, cost_center )
VALUES ('$date','$ricediscountexpense_account','$rice_charges','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Update accounts_type Set balance=balance-'$rice_charges' where id='$ricediscountexpense_account'  && costcenter_id='$cost_center'  $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}

if($total_tax!=0  && $info4000['en_razik']==0)
{
    


$sql = "Insert into cash_transaction
(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
VALUES ('$date','$tax_account','$total_tax','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Update accounts_type Set balance=balance+'$total_tax' where id='$tax_account'   && costcenter_id='$cost_center' $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));



}




$sql = "Insert into cash_transaction
(datetime, account_id, credit,  ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
VALUES ('$date','$credit_account','$total','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


$sql = "Update accounts_type Set balance=balance-'$total' where id='$credit_account'   && costcenter_id='$cost_center' $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));   
    
    


if($info2000['enable_unadjustpaymentp']==0) {
    
    supplierpaymentfifoclear($customer_id, $brand_id); 
    
}


$phonenum = mysqli_get_var("Select cell from user WHERE id = '$customer_id'");
$smsname = mysqli_get_var("Select fname from user WHERE id = '$customer_id'");
$smsname2 = mysqli_get_var("Select lname from user WHERE id = '$customer_id'");

if($info1000['customer_sms']==1)
{

 
$message = "Dear ".$smsname." ".$smsname2.",
   ".((isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_invoice_label'] : 'Purchase Invoice')." (".$sid.") has been edited. Old amount was Rs.".$old_am." New amount Rs.".$total.".
Thank You";


$length11= strlen($phonenum);

 
 if($length11==11)
 {

send_sms($phonenum,$message,$debug);

 }

}


if($info1000['admin_sms']==1)
{



$message = "Dear ".$smsname." ".$smsname2.",
     ".((isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_invoice_label'] : 'Purchase Invoice')." (".$sid.") has been edited. Old amount was Rs.".$old_am." New amount Rs.".$total.".
Thank You";


 $data2 = mysqli_query($conn,"SELECT * from admin_no ") or die(mysqli_error($conn));
        
while($info2 = mysqli_fetch_array( $data2 )) 
 { 
 $phonenum = $info2['no'];

$length11= strlen($phonenum);
 
 if($length11==11)
 {

send_sms($phonenum,$message,$debug);
 }

 }
}



if($info2000['rice_discount']==1) {

if (isset($_POST['rice_discount']) && $info4000['ricecost_cogs']==0) {
 
 
$sql2 = "Delete from rice_purchase_discount where sid='$sid' && page='3'";

$retval = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn)); 

 
 
for($i=0 ;$i < count($_POST['rice_discount']); $i++) {

$c= $_POST['rice_discount'][$i];      
$qty=$_POST['rice_discount_value'][$i];


$less=$_POST['rice_type'][$i];
$amount_type=$_POST['rice_percent'][$i];
$specialclass=$_POST['specialclass'][$i];
$coa_id=$_POST['coa_id'][$i];
$dept_id = mysqli_get_var("SELECT dept_id FROM accounts_type WHERE id = '$coa_id' ");

if($qty!="")
{
    
$qty = ($qty);  

if ($info3000['en_zopaskitchen']==1)
{
    switch ($specialclass2) {
        case 'asset_value':
            $asset_value = $qty;
            $ramount = $asset_value;
            break;

        case 'duty_per':
            $duty_value = ($amount_type == 1) ? ($asset_value * $qty / 100) : $qty;
            $ramount = $duty_value;
            break;

        case 'add_cduty_per':
            $add_cduty_value = ($amount_type == 1) ? ($asset_value * $qty / 100) : $qty;
            $ramount = $add_cduty_value;
            break;

        case 'sales_tax_per':
            $sales_tax_value = ($amount_type == 1)
                ? (($asset_value + $duty_value + $add_cduty_value) * $qty / 100)
                : $qty;
            $ramount = $sales_tax_value;
            break;

        case 'rd_per':
            $rd_value = ($amount_type == 1) ? ($asset_value * $qty / 100) : $qty;
            $ramount = $rd_value;
            break;

        case 'add_stax_per':
            $add_stax_value = ($amount_type == 1)
                ? (($asset_value + $sales_tax_value) * $qty / 100)
                : $qty;
            $ramount = $add_stax_value;
            break;

        case 'gst_per':
            $gst_value = ($amount_type == 1) ? ($sales_tax_value * $qty / 100) : $qty;
            $ramount = $gst_value;
            break;

        case 'itax_per':
            $itax_value = ($amount_type == 1)
                ? (($asset_value + $duty_value + $add_cduty_value + $sales_tax_value + $rd_value + $add_stax_value + $gst_value) * $qty / 100)
                : $qty;
            $ramount = $itax_value;
            break;

        case 'freight':
            $freight_value = $qty * $price;
            $ramount = $freight_value;
            break;

        case 'clearance':
            $clearance_value = $qty * $price;
            $ramount = $clearance_value;
            break;

        case 'expense_per':
            $expense_value = ($amount_type == 1) ? ($price * $qty / 100) : $qty;
            $ramount = $expense_value;
            break;

        default:
            $ramount = $qty;
            break;
    }

    // $ramount = $ramount * $currency_rate;

    if($dept_id != 37)
    {
        $sql = "Insert into cash_transaction
        (datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
        VALUES ('$date','$coa_id','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
        
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        
        $sql = "Update accounts_type Set balance=balance-'$ramount' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        
        $sql = "Insert into cash_transaction
        (datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
        VALUES ('$date','$sales_id','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
        
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        
        $sql = "Update accounts_type Set balance=balance+'$ramount' where id='$sales_id' && costcenter_id='$cost_center'  $caccounts_company";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    }   
}

else if($specialclass=='single_impact'  ) {
    
    
    
    
    if($less==0) {
    
if($amount_type==0) { $ramount = $qty; } else { $ramount = $aarice * ($qty/100); $aarice = $aarice - $ramount;   }  
    

$ramount = $ramount * $_POST['currency_rate'];  

if($dept_id != 37){
    
    
    $sql = "Insert into cash_transaction
    (datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
    VALUES ('$date','$coa_id','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
    
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

    $sql = "Update accounts_type Set balance=balance+'$ramount' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    
    
        $sql = "Update cash_transaction Set debit=debit-'$ramount' where id='$sales_id22' ";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

        $sql = "Update accounts_type Set balance=balance-'$ramount' where id='$sales_id' && costcenter_id='$cost_center'  $caccounts_company";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    

    
}       } else {

if($amount_type==0) { $ramount = $qty; } else { $ramount = $aarice * ($qty/100); $aarice = $aarice + $ramount;   }  

$ramount = $ramount * $_POST['currency_rate'];  

if($dept_id != 37 ){


    $sql = "Insert into cash_transaction
    (datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
    VALUES ('$date','$coa_id','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

    $sql = "Update accounts_type Set balance=balance-'$ramount' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    
    
        $sql = "Update cash_transaction Set debit=debit+'$ramount' where id='$sales_id22' ";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

        $sql = "Update accounts_type Set balance=balance+'$ramount' where id='$sales_id' && costcenter_id='$cost_center'  $caccounts_company";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


        
    }       }   
    
    
    
    
    
    
    
    
}

else  if(($specialclass!='brokery_rs' && $specialclass!='brokery_percentage') || $broker_id==0 ) {
    
    
if($less==1) {


if($specialclass=='brokery_rs') {

$abrokery_rs = $abrokery_rs +  ($qty * $totbags);

 $ramount = ($qty * $totbags);
    
    }
    
else if($specialclass=='brokery_percentage') {

$abrokery_percentage = $abrokery_percentage +  (($qty/100) * $tota);

$ramount = (($qty/100) * $tota);
    
    }    else {
    

if($amount_type==0) { $ramount = $qty; } else { $ramount = $aarice * ($qty/100); $aarice = $aarice - $ramount;   }  

    }
    
if($dept_id != 37){
    $sql = "Insert into cash_transaction
    (datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
    VALUES ('$date','$coa_id','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


    $sql = "Update accounts_type Set balance=balance-'$ramount' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));



    if($info3000['en_mft'] == 1){
        $sql = "Insert into cash_transaction
        (datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
        VALUES ('$date','$credit_account','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


        $sql = "Update accounts_type Set balance=balance+'$ramount' where id='$credit_account' && costcenter_id='$cost_center'  $caccounts_company";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    }else {
        $sql = "Insert into cash_transaction
        (datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
        VALUES ('$date','$coa_id','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


        $sql = "Update accounts_type Set balance=balance+'$ramount' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    }

}

    
    
    } else {


if($specialclass=='brokery_rs') {

$abrokery_rs = $abrokery_rs +  ($qty * $totbags);

$ramount = ($qty * $totbags);
    
    }
    
else if($specialclass=='brokery_percentage') {

$abrokery_percentage = $abrokery_percentage +  (($qty/100) * $tota);

$ramount = (($qty/100) * $tota);
    
    }    else {

if($amount_type==0) { $ramount = $qty; } else { $ramount = $aarice * ($qty/100); $aarice = $aarice + $ramount;   }  

    }

if($dept_id != 37){
    $sql = "Insert into cash_transaction
    (datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
    VALUES ('$date','$coa_id','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

    $sql = "Update accounts_type Set balance=balance+'$ramount' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        

    if($info3000['en_mft'] == 1){
        $sql = "Insert into cash_transaction
        (datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
        VALUES ('$date','$credit_account','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


        $sql = "Update accounts_type Set balance=balance-'$ramount' where id='$credit_account' && costcenter_id='$cost_center'  $caccounts_company";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    }else{
        $sql = "Insert into cash_transaction
        (datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
        VALUES ('$date','$coa_id','$ramount','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


        $sql = "Update accounts_type Set balance=balance-'$ramount' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    }

    
}   
        }   
    
    
    
} else {
    
    if($specialclass=='brokery_rs') {

$abrokery_rs = $abrokery_rs +  ($qty * $totbags);

    
    }
    
else if($specialclass=='brokery_percentage') {

$abrokery_percentage = $abrokery_percentage +  (($qty/100) * $tota);

    
    }   
    
    
    }
    
    
    
    
    
    
    
    
$sql25 = "Insert into rice_purchase_discount

(sid,type_id, amount, page)
VALUES ('$sid','$c','$qty', 3)" ;

$retval25 = mysqli_query($conn, $sql25 );

} } } }

if($info4000['en_vgm']==1){

   
    $ricedata  =mysqli_get_var("SELECT GROUP_CONCAT(a.label,': ',b.value) as rice_data  FROM `rice_field_details` as b ,rice_field as a
    WHERE a.id=b.fid and  b.sid in($sid) and b.stype='6'");
    if ($ricedata!='') {
        $note = mysqli_get_var("select notes from purchasing where id ='$sid'");
        $note = $note.' '.$ricedata;
        $sql = "UPDATE purchasing SET notes = '$note' WHERE id = '$sid'" ;
        $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    }
    }

if(!$po_qtyimpact && $grn_id > 0) {
    shipping_expense_sync_grn_item_costs(
    $conn,
    $grn_id,
    $sid,
    $currency_rate,
    $info3000['en_importexpense_currency'],
    $info3000['costing_weight'],
    1
    );
}

if(! $retval )
{
  $mess = "<div class='alert alert-warning alert-border-left alert-dismissible fade show'><button type='button' class='btn btn-warning btn-xs'>Warning</button> Purchase ID already Exist</div>";
}
else
 {
 $mess = '<div class="alert alert-success alert-border-left alert-dismissible fade show"><button type="button" class="btn btn-success btn-xs">Success</button> <a target="_blank" class="btn btn-warning btn-xs" href="'.$info1000['printview_slug'].'print-pi.php?sid='.$sid.'">Print Receipt</a>  </div>';
}


}
 
 ?>
 

<?php include('../layout/header.php'); ?>

<?php include('../layout/sidebar.php'); ?>

 

 <form name="sendmail" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="slip" >     


    <!--main content start--> 
     <!-- Vertical Overlay-->
    <div class="vertical-overlay"></div>

    <!-- ============================================================== -->
    <!-- Start right Content here -->
    <!-- ============================================================== -->
    <div class="main-content">

        <div class="page-content">
            <div class="container-fluid">
        <!-- page start-->
<!-- start page title -->
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-galaxy-transparent">
            <h4 class="mb-sm-0">Edit <?php echo ((isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_invoice_label'] : 'Purchase Invoice') ?> &nbsp;&nbsp;&nbsp; (Invoice #: <?php if($info3000['en_customdailyid']==1) { $sid = $_GET['sid']; echo $numb = mysqli_get_var("Select daily_id from purchasing where id='$sid' "); } else { echo $sid = $_GET['sid']; } ?>)</h4>

            <div class="page-title-right">
                <ol class="breadcrumb m-0">
                    <li class='breadcrumb-item'><a href="javascript: void(0);">Home</a></li>
                    <li class='breadcrumb-item active'>Edit <?php echo ((isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_invoice_label'] : 'Purchase Invoice') ?> &nbsp;&nbsp;&nbsp; (Invoice #: <?php if($info3000['en_customdailyid']==1) { $sid = $_GET['sid']; echo $numb = mysqli_get_var("Select daily_id from purchasing where id='$sid' "); } else { echo $sid = $_GET['sid']; } ?>)</li>
                </ol>
            </div>

        </div>
    </div>
</div>
<!-- end page title -->
        <div class="row">
            <div class="col-sm-12">
                <div class="card card-height-100">
                    <div class="card-header">
                      Edit <?php echo ((isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_invoice_label'] : 'Purchase Invoice') ?>  &nbsp;&nbsp;&nbsp; (Invoice #: <b><?php if($info3000['en_customdailyid']==1) {  $sid = $_GET['sid']; echo $numb = mysqli_get_var("Select daily_id from purchasing where id='$sid' "); } else { echo $sid = $_GET['sid']; } ?></b>) 
                        <span class="tools pull-right">
                          <input type="number" style="width:40px; border-radius:5px; border:1px solid #e2e2e4; padding-left:5px; padding-right:5px;" id="totpc" value="0" readonly required /> Total Items &nbsp;&nbsp;&nbsp;
               <input name="on_record" type="checkbox" id="on_record"  <?php $id=$_GET['sid']; $on_record = mysqli_get_var("Select on_record from purchasing where id='$id' "); if ($on_record!=0) { echo 'checked'; } ?> /> On Record
                     
                            <a href="javascript:;" class="fa fa-chevron-down"></a>
                            <a href="javascript:;" class="fa fa-cog"></a>
                            <a href="javascript:;" class="fa fa-times"></a>
                         </span>
                    </div>
                    <div class="card-body">
                       <!--Own Text -->
         <?php echo $mess; ?>
        
                      
 

<div class="display_box row g-3">
  
 <?php  
  if(isset($_GET['sid']))
{
    
$id=$_GET['sid'];


 
    
//echo "SELECT * from purchasing where id='$id'";
$data5 = mysqli_query($conn,"SELECT * from purchasing where id='$id'") or die(mysqli_error($conn));

while($info5 = mysqli_fetch_array( $data5 )) 
 { 

$taxapply=$info5['tax_applied'];
$pending =$info5['pending_amount'];

?>





<div class="row g-3">
    <!-- <div class="col-12 col-lg-2">
        <div class="card card-height-100 h-100">
            <div class="card-body"> -->

                       <!--Own Text -->
   
 <input name="amount_received" type="hidden"  value="0" id="amount_received"/> 



   <div  <?php if($info2000['en_filesystem']==0) { echo 'style="display:none;"'; } ?> >   
<?php echo $info2000['filesystem_label']; 

$data4 = mysqli_query($conn,"SELECT id, name, custom_code  from file_system  WHERE inactive=0 order by name") or die(mysqli_error($conn)); 
  echo "<select name='filesystem' required  id='filesystem' tabindex='1' class='filesystem reportselect form-control' required   >
  <option value='0' >Select ".$info2000['filesystem_label']."</option> ";
   while($info4 = mysqli_fetch_array( $data4 )) 
   { 
    $selected = '';
    if($info5['filesystem_id'] == $info4['id'])
      $selected = 'selected';
   echo "<option value='".$info4['id']."' ".$selected.">".$info4['name']." | ".$info4['custom_code']." </option>";
  }

  echo "</select><br>";
?>
<!-- <input name="filesystem" type="text"   value="<?php $filesystem = $info5['filesystem_id']; echo $record_check = mysqli_get_var("Select name from file_system where  `id` = '$filesystem' "); ?>"  class="form-control filesystem" /> -->
<br>
</div>
   
      
    <input name="daily_id" type="hidden" id="daily_id" value="<?php echo $info5['daily_id']; ?>" />
    <input name="create_by" type="hidden" id="create_by" value="<?php echo $info5['create_by']; ?>" />
  <input name="create_time" type="hidden" id="create_time" value="<?php echo $info5['create_time']; ?>" />
   <input name="verified_by" type="hidden" id="create_by" value="<?php if(isset($_GET['verify']))
{ echo $loginuser; } else { echo $info5['verified_by']; } ?>" />
  <input name="verified_time" type="hidden" id="create_time" value="<?php echo $info5['verified_time']; ?>" />

<?php  
$sauda_id = $info5['sauda_id'];
$bag_packing_weight = mysqli_get_var("SELECT weight FROM bag_packing WHERE id IN (SELECT bag_packing FROM truck_received WHERE id IN (SELECT arrival_truck_id FROM purchasing_grn WHERE id = '".$info5['grn_id']."' ) ) ");
// print_r($info5);
if($bag_packing_weight == '')
    $bag_packing_weight = 1;
?>
<input type="hidden" name="sauda_broken_id" value="<?php echo mysqli_get_var("SELECT broken FROM sauda WHERE id = '$sauda_id' ") ?>" id="sauda_broken_id">
<input type="hidden" name="sauda_moisture_id" value="<?php echo mysqli_get_var("SELECT moisture FROM sauda WHERE id = '$sauda_id' ") ?>" id="sauda_moisture_id"> 
<input type="hidden" value="<?php echo $bag_packing_weight; ?>" id="bag_packing_weight"> 
<input type="hidden" name="sauda_chalky_id" value="<?php echo mysqli_get_var("SELECT chalky FROM sauda WHERE id = '$sauda_id' ") ?>" id="sauda_chalky_id">
<input type="hidden" name="sauda_damage_id" value="<?php echo mysqli_get_var("SELECT damage FROM sauda WHERE id = '$sauda_id' ") ?>" id="sauda_damage_id">
<input type="hidden" name="sauda_filling_id" value="<?php echo mysqli_get_var("SELECT sauda_kind FROM sauda WHERE id = '$sauda_id' AND sauda_kind NOT IN (SELECT id FROM sauda_terms WHERE order_pending = 1) ") ?>" id="sauda_filling_id">
<input type="hidden" name="total_freight_value" value="<?php echo $total_freight_value = mysqli_get_var("SELECT freight_total FROM truck_received WHERE id = (SELECT arrival_truck_id FROM purchasing_grn WHERE id = '".$info5['grn_id']."' )  "); ?>" id="total_freight_value">

  <input name="broker_id"  type="hidden" id="broker_id"  value="<?php echo $info5['broker_id']; ?>"  />                  
  <input name="old_si" type="hidden" id="old_si" value="<?php echo $id; ?>" />
<input name="month_id" type="hidden" id="month_id" value="<?php echo $info5['month_id']; ?>" />

<input name="emp_id" type="hidden" id="emp_id" value="<?php echo $info5['emp_id']; ?>" />

<input name="order_id" type="hidden" id="order_id" value="<?php echo $info5['po_id']; ?>" />



<input name="grn_id" type="hidden" id="grn_id" value="<?php echo $info5['grn_id']; ?>" />

<div style="display:none;">
Employee <input name="employee_id" type="hidden" id="employee_id" value="<?php echo $info5['emp_id']; ?>"  />
<input type="text" class="form-control" value="<?php 
$vendor_id=$info5['emp_id'];

$data7 = mysqli_query($conn,"SELECT company_name, fname, lname from user where id='$vendor_id'") or die(mysqli_error($conn));
$info7 = mysqli_fetch_array( $data7 ); 
echo $info7['company_name']." ( ".$info7['fname']." ".$info7['lname']."  ) "; ?>"  readonly />
 <br />
</div>



<?php
 if($info3000['en_snd_purchase']){
   $distributor_from_all = mysqli_get_var("Select distributor_from_all from employee where id='$loginuser' ");  
// print_r($info5);
  ?>




 <div class="form-group">

  <label class="col-lg-2 control-label"><?php echo $info3000['distributer_customer_label']; ?></label><br>

 <select name="distributor_from_id" required class="form-control reportselect" id="dist_from_id">
 <?php   if(1) { ?>  <option value=""  selected >Select <?php echo $info3000['distributer_customer_label']; ?></option> <?php } ?>
 
  <?php
  


    $data2 = mysqli_query($conn,"SELECT * from distributor WHERE 1=1 $limit_current_distributer ");
  
    
while($info2 = mysqli_fetch_array( $data2 )) 
 {
  if ($info5['distributor_from_id']==$info2['id'])
     {
       ?>
      <option selected value="<?php echo $info2['id'];?>" ><?php echo $info2['dsrcode']." ".$info2['fname']." ".$info2['lname'].' ('.$info2['company_name'].')';?></option>
      
      <?php 
     }
     else{
 
  ?><option value="<?php echo $info2['id'];?>" ><?php echo $info2['dsrcode']." ".$info2['fname']." ".$info2['lname'].' ('.$info2['company_name'].')';?></option>
  
  <?php 
      }
   }
  ?>
  </select> 
</div>
<br>
 <div class="form-group">

  <label class="col-lg-2 control-label"><?php echo $info3000['distributer_vendor_label']; ?></label><br>

 <select name="distributor_to_id" class="form-control reportselect" id="dist_to_id">
 <?php   if(0) { ?>  <option value="a"  selected >All</option> <?php } ?>
 
  <?php
  
if($distributor_from_all==1) {
$data2 = mysqli_query($conn,"SELECT * from distributor");
}
else {
$data2 = mysqli_query($conn,"SELECT * from distributor where id IN (Select did from salesman_reportdistributor where eid='$loginuser' AND type=1)");
}
    
while($info2 = mysqli_fetch_array( $data2 )) 
 {

     if ($info5['distributor_to_id']==$info2['id'])
     {
       ?>
      <option selected value="<?php echo $info2['id'];?>" ><?php echo $info2['dsrcode']." ".$info2['fname']." ".$info2['lname'].' ('.$info2['company_name'].')';?></option>
      
      <?php 
     }
     else{


      ?>
      <option value="<?php echo $info2['id'];?>" ><?php echo $info2['dsrcode']." ".$info2['fname']." ".$info2['lname'].' ('.$info2['company_name'].')';?></option>
      
    <?php
       } 
   }
  ?>
  </select> 
</div>


<input   type="hidden" name="vendor"  id="vendor" value="0"  />


<?php }
   else {
    ?>
<div class="<?php echo $info3000['formlayout_column'];?>">
<?php echo $info3000['distributer_vendor_label']; ?> 
<input name="old_vendor_id"  type="hidden" id="vendor"     value="<?php $vid=$info5['vendor_id'];  echo $info5['vendor_id']; ?>" readonly />


<input name="vendorname" class="form-control"  type="hidden" id="vendorname"  value="<?php 
$vendor_id=$info5['vendor_id'];

$data7 = mysqli_query($conn,"SELECT company_name, fname, lname from user where id='$vendor_id'") or die(mysqli_error($conn));
$info7 = mysqli_fetch_array( $data7 ); 
echo $info7['company_name']." ( ".$info7['fname']." ".$info7['lname']."  ) "; ?>" readonly />



<?php

$qeruy2="SELECT *, c.id AS cid from vendor c, user u WHERE u.id=c.id AND u.inactive=0  $climit_user $climit_zone order by u.company_name";
if($info2000['customervendor_same'] == 1)
{   
    $data4 = mysqli_query($conn,"SELECT *, v.id AS cid from customer v, user u WHERE u.id=v.id $vv AND u.inactive=0  $climit_user $climit_zone   order by u.company_name") or die(mysqli_error($conn));     
}
else
{
    $data4 = mysqli_query($conn,"SELECT *, v.id AS cid from vendor v, user u WHERE u.id=v.id $vv AND u.inactive=0  $vlimit_user $vlimit_zone   order by u.company_name") or die(mysqli_error($conn));     
}

    echo "<select name='vendor'  id='vendor' required  class=' combobox cid teacher form-control'   >";
    echo "<option value=''>Select a ".$info3000['distributer_vendor_label']."...</option>";

     while($info4 = mysqli_fetch_array( $data4 )) 
     { 
     if($info4['cid']==$info5['vendor_id']) { echo "<option value='".$info4['cid']."' selected='selected' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; } else { echo "<option value='".$info4['cid']."' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; }
    }

    echo "</select>";
?>








<?php  }?>
<!-- <br>
<br> -->
</div>

<?php if($info2000['en_bwl']==1){ ?>
 <div class="form-group">

  <?php echo "Company Invoice Number" ?>

  <input type="text" name="company_invoice_num" id="company_invoice_num" class="form-control" value="<?php echo $info5['company_invoice_no']  ?>"></div>


<?php } ?>


 <div <?php if($info2000['en_ricetrade']==0) { echo ' style="display:none"'; } ?> > 
<?php

$broker_id = $info5['broker_id']; if($broker_id=='') $broker_id = 0;

?>
<div style=" <?php if($info3000['en_broker']==0) { echo "display:none;"; } ?>">
<?php 
 if($broker_id!=0)
{
    
?>


<label>Broker</label>
<input type="text" class="form-control" value="<?php 


$data7 = mysqli_query($conn,"SELECT company_name, fname, lname from user where id='$broker_id'") or die(mysqli_error($conn));
$info7 = mysqli_fetch_array( $data7 ); 
echo $info7['company_name']." ( ".$info7['fname']." ".$info7['lname']."  ) "; ?>" readonly />   
<br>
<br>
    
<?php   } else { ?>


<label>Broker</label>
<input type="text" class="form-control" value="<?php echo $info1000['company_name']; ?>" readonly />

<br>
<br>
  
<?php } ?>
</div>
</div>
<?php
$count_inventory = mysqli_get_var("SELECT COUNT(id) FROM inventory where inactive=0");
$use_ajax_search = 0;
if($count_inventory > 500){
  $use_ajax_search = 1;
}
if(isset($info3000['search_cher']) && (int)$info3000['search_cher'] === 0){
  $use_ajax_search = 0;
}
?>
<?php if($info2000['multiple_batch']==0 && $info5['grn_id']==0 && !$po_qtyimpact) { ?>
    <div class="<?php echo $info3000['formlayout_column'];?>">
Search <?php echo $info1000['product_label']; ?><br>
 <?php
 $selected_product_brand = isset($_POST['inv_brand']) ? test_input($_POST['inv_brand']) : ((isset($info5['brand_id']) && (int)$info5['brand_id']>0) ? $info5['brand_id'] : 'a');
 $brand_product_filter = "";
 if($selected_product_brand!='' && $selected_product_brand!='a') {
    $selected_product_brand = (int)$selected_product_brand;
    $brand_product_filter = " && brand_id='$selected_product_brand' ";
 }
 $brand_user_filter = "";
 if($en_brand==0) {
    $brand_user_filter = " && brand_id IN (Select aid from salesman_reportbrand where eid='$loginuser') ";
 }
 if($use_ajax_search==0){
   $data = mysqli_query($conn,"SELECT id,name, sku, details, barcode  from inventory where inactive=0 $brand_product_filter $brand_user_filter $climit_product  order by name") or die(mysqli_error($conn));
   $data2 = mysqli_query($conn,"SELECT id,name from deal ") or die(mysqli_error($conn));
 }
$product_search_class = ($use_ajax_search==1) ? "form-control purchase-product-ajax" : "combobox form-control";
echo "<select name='teacher_id' id='product_search' accesskey='s' class='".$product_search_class."' data-minimum-input-length='".((isset($info3000['search_cher']) && (int)$info3000['search_cher'] >= 0 && (int)$info3000['search_cher'] <= 5) ? (int)$info3000['search_cher'] : 0)."' >";
echo "<option value=''>Select a ".$info1000['product_label']."</option>";
 if($use_ajax_search==0){
 while($info = mysqli_fetch_array( $data )) 
 { 
   echo "<option value='".$info['id']."' >".$info['barcode'].' '.$info['sku'].' '.$info['name'].' '.$info['details']."</option>";
 }

 while($info2 = mysqli_fetch_array( $data2 )) 
 { 
   echo "<option value='".$info2['id']."' >".$info2['name']."</option>";
 }
 }

echo "</select>";?>
</div>
<?php } ?> 

                       
                       <!--Own Text End -->
            <!-- </div>
        </div> -->
    <!-- </div> -->
    <!-- </div> -->




    <!-- <div class="col-12 col-lg-2">
        <div class="card card-height-100 h-100">
            <div class="card-body"> -->
                       <!--Own Text -->
                       
  

        
        

<div class="<?php echo $info3000['formlayout_column']?>">
Date Time<input name="date"  type="date" <?php if($info1000['en_backdatedposting']==0) { echo 'max="'.$max_date.'" min="'.$min_date.'"'; } ?>  value="<?php $odatetime=date('Y-m-d', strtotime($info5['datetime']));
 echo $odatetime;?>" id="date" class="form-control" />
</div>

<?php if($info3000['en_sama']==1)
{ ?>
<div class="<?php echo $info3000['formlayout_column']?>">
Due Date <input name="due_date" id="due_date" <?php if($info1000['en_backdatedposting']==0) { echo 'max="'.$max_date.'" min="'.$min_date.'"'; } ?> value="<?php echo $info5['due_date'];
 ?>" type="date" class="form-control" min="<?php echo date('Y-m-d'); ?>" />
</div>
<?php } ?>

<?php if($info2000['en_extra_party'] == 1){ ?>
Party Name<br>
<?php $data4 = mysqli_query($conn,"SELECT *, c.id AS cid from customer c, user u WHERE u.id=c.id AND u.inactive=0 $climit_user $climit_zone order by u.fname") or die(mysqli_error($conn)); 

echo "<select name='party_id' id='party_id'  class='reportselect teacher party_id form-control'   >
<option value='0' >Select Party Name..</option> ";
 while($info4 = mysqli_fetch_array( $data4 )) 
 {
 $selected = '';
  if($info4['cid'] == $info5['party_id'])
    $selected = 'selected'; 
 echo "<option value='".$info4['cid']."' ".$selected.">".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>";
}

echo "</select>";
?>
<br>
<?php } ?>

 
 
  <?php if ($info5['on_record']==0) { ?>
  <input name="on_record2"  type="hidden"  class="form-control" id="onrecord"  value="0" required /> 
   <?php 
  }else {  ?>
    
 
 
  <input name="on_record2"  type="hidden"  class="form-control" id="onrecord"  value="<?php echo $info5['on_record']; ?>" required /> 
    <span id="ord" ></span>
 
 <?php } ?>
   
  
 
<!-- <span id="ord" ></span> -->
 
  
  
  <div class="<?php echo $info3000['formlayout_column']?>" style=" <?php  if($info1000['en_lpo']==0) { echo "display:none;"; } ?>"><br>

LPO #<br>
  <input name="lpo"  type="number"  class="form-control" id="lpo"  value="<?php if($info5['lpo']!=0) echo $info5['lpo']; else echo 0?>"   required/> 
<br>             
</div> 
 
 
 
<div class="<?php echo $info3000['formlayout_column']?>" style=" <?php  if($info2000['custom_onrecord']==0) { echo "display:none;"; } ?>" required>
Invoice #<br>
  <input name="on_record5"  class="form-control"   type="text" id="on_record5"  value="<?php echo $info5['on_record'];?>"    /> 
<br>             </div> 


 
<div class="<?php echo $info3000['formlayout_column']?>" style=" <?php  if($info1000['en_servicesales']==0) { echo "display:none;"; } ?>">

<?php echo $info3000['sales_type_label'];?><br>
<?php $data4 = mysqli_query($conn,"SELECT * from sales_type where 1=1 && purchase_display=1 $climit_invoicetype ") or die(mysqli_error($conn)); 

echo "<select name='service_invoice' id='service_invoice'  class=' form-control' required >";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 if($info5['service_invoice']==$info4['id']) {
     echo "<option value='".$info4['id']."' selected >".$info4['name']."</option>"; 
 }
 else {
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}
 }

echo "</select>";
 ?>
      <br>       </div> 


<div class="<?php echo $info3000['formlayout_column'];?>">
<?php echo $info1000['costcenter_label']; ?> <?php $data4 = mysqli_query($conn,"SELECT * from cost_center where active=1 $climit_costcenter $xlimit_costcenter ") or die(mysqli_error($conn)); 

echo "<select name='cost_center' id='combobox'  class='teacher form-control' required  >";

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 
 if($info5['cost_center']==$info4['id'])
 {echo "<option value='".$info4['id']."' selected='selected' >".$info4['name']."</option>";
     }
   else {echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}
 }

echo "</select>";

?>
                       
                       <!--Own Text End -->
            </div>

<div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if($info2000['brand_filter']==0 && !brandwise_enabled()) { echo ' style=" display:none;"';} ?>>
Brand
<?php
  $bb_brand = "";
  if($en_brand==0) {
    $bb_brand = " && id IN (Select aid from salesman_reportbrand where eid='$loginuser') ";
  }
  $selected_inv_brand = isset($_POST['inv_brand']) ? test_input($_POST['inv_brand']) : (isset($_POST['brandfilter']) ? test_input($_POST['brandfilter']) : ((isset($info5['brand_id']) && (int)$info5['brand_id']>0) ? $info5['brand_id'] : (isset($_SESSION['brandfilter']) ? test_input($_SESSION['brandfilter']) : 'a')));
  $brand_required = brandwise_enabled() ? " required " : "";
  $data_brand = mysqli_query($conn, "SELECT id, name from product_brands where 1=1 $bb_brand $climit_productbrand order by name") or die(mysqli_error($conn));
  echo "<select id='inv_brand' name='inv_brand' class='combobox reportselect form-control' $brand_required >";
  echo "<option value='a' ".(($selected_inv_brand=='a' || $selected_inv_brand=='') ? "selected" : "").">Select Brand</option>";
  while($info_brand = mysqli_fetch_array($data_brand)) {
    $bsel = ($selected_inv_brand == $info_brand['id']) ? " selected " : "";
    echo "<option value='".$info_brand['id']."' $bsel>".$info_brand['name']."</option>";
  }
  echo "</select>";
  echo "<input type='hidden' name='brandfilter' id='brandfilter' value='".$selected_inv_brand."' />";
?>
</div>
        <!-- </div>
    </div> -->
        
<!--         
    <div class="col-12 col-lg-2">
        <div class="card card-height-100 h-100">
            <div class="card-body"> -->
                       <!--Own Text -->
                       
<div class="<?php echo $info3000['formlayout_column'];?>" style="display:none" <?php if($info2000['en_mastqalandar']==0) echo ' ';  ?> >
<b>Broken (%)</b><br>
  <input name="broken" value="<?php echo $info5['broken'];?>"  class="form-control" required  type="number" id="" />  
</div>  


<div class="<?php echo $info3000['formlayout_column'];?>">
<b>Moisture (%)</b><br>
  <input name="moisture" value="<?php echo $info5['moisture'];?>"  class="form-control"  required  type="number" id="" />  

</div>     
           

  
<div class="<?php echo $info3000['formlayout_column'];?>" <?php if($info1000['en_grn']==1 || $info4000['po_dcdate']==0) echo ' style="display:none"';  ?> >
DC No.<br>
  <input name="number" value="<?php if($info5['serial']!=0) echo $info5['serial']; else echo 0;?>"  class="form-control"  type="number" id="number"  required/>  
<span id="serial" ></span>
</div>
<div class="<?php echo $info3000['formlayout_column'];?>">
DC Date<br>
  <input name="dcdate"  type="date"  class="form-control" id="dcdate"  <?php if ($info5['serial_date'] > 0){  $odatetime=date('Y-m-d', strtotime($info5['serial_date']));
 echo "value='".$odatetime."'"; }?> /> 

<!-- <br> -->
</div>

<?php if($info3000['en_noorani'] == 1){ ?> 
<div >
    Supplier Invoice number
    <input type="text" name="vendor_invoice_no" class="form-control" value="<?php echo $info5['vendor_invoice_no'] ?>">
    <br>
    <br>
    Supplier Invoice Date
    <input type="date" name="vendor_invoice_date" class="form-control" value="<?php if($info5['vendor_invoice_date'] != "" ) echo date('Y-m-d', strtotime($info5['vendor_invoice_date'])); ?>">
</div>
<br>
<?php } ?>

<div class="<?php echo $info3000['formlayout_column'];?>">
Total Amount<br>

 <input name="total"   id="total_amount" type="text"      class="total-display form-control" value="<?php echo $info5['total_amount'];?>" readonly/>  

</div>
 





<div <?php if ($info4000['en_razik']==0 && $info3000['vendor_comission']==0) { echo ' style="display:none;"'; } ?> class="<?php echo $info3000['formlayout_column'];?>">
<!-- <?php if($info3000['vendor_comission']==0) { echo $bba = 'Tax '.$info1000['vendor2_label']; } else { echo $bba = 'Dealer ';  }   ?><br /> -->
<?php echo $info3000['vendor2_label']; ?><br />
        <?php 
           if($en_vendor==0) { $vv= " && v.id IN (Select aid from salesman_reportvendor where eid='$loginuser') ";}

         if($info2000['customervendor_same'] == 1)
        {
            $data4 = mysqli_query($conn,"SELECT *, v.id AS cid from customer v, user u WHERE u.id=v.id $vv AND u.inactive=0 $climit_user $climit_zone order by u.company_name") or die(mysqli_error($conn));
        }
        else
        {
            $data4 = mysqli_query($conn,"SELECT *, v.id AS cid from vendor v, user u WHERE u.id=v.id $vv AND u.inactive=0  $vlimit_user $vlimit_zone   order by u.company_name") or die(mysqli_error($conn));    
        }

        echo "<select name='vendor_id2'  required  class=' combobox teacher form-control'   >";
        echo "<option value='0'>Select a ".$info3000['vendor2_label']."...</option>";

         while($info4 = mysqli_fetch_array( $data4 )) 
         { 
         if($info4['cid']==$info5['vendor_id2']) { echo "<option value='".$info4['cid']."' selected='selected' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; } else { echo "<option value='".$info4['cid']."' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; }
        }

        echo "</select>";

    
?>

</div>




<div <?php if ($info3000['vendor_comission']==0) { echo ' style="display:none;"'; } ?> class="<?php echo $info3000['formlayout_column'];?>">
<?php echo $info3000['vendor3_label']; ?><br />
        <?php 
           if($en_vendor==0) { $vv= " && v.id IN (Select aid from salesman_reportvendor where eid='$loginuser') ";}

         if($info2000['customervendor_same'] == 1)
        {
            $data4 = mysqli_query($conn,"SELECT *, v.id AS cid from customer v, user u WHERE u.id=v.id $vv AND u.inactive=0 $climit_user $climit_zone order by u.company_name") or die(mysqli_error($conn));
        }
        else
        {
            $data4 = mysqli_query($conn,"SELECT *, v.id AS cid from vendor v, user u WHERE u.id=v.id $vv AND u.inactive=0  $vlimit_user $vlimit_zone   order by u.company_name") or die(mysqli_error($conn));    
        }

        echo "<select name='vendor_id3'  required  class=' combobox teacher form-control'   >";
        echo "<option value='0'>Select a ".$info3000['vendor3_label']."...</option>";

         while($info4 = mysqli_fetch_array( $data4 )) 
         { 
         if($info4['cid']==$info5['vendor_id3']) { echo "<option value='".$info4['cid']."' selected='selected' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; } else { echo "<option value='".$info4['cid']."' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; }
        }

        echo "</select>";

    
?>

</div>

                  
    
    
     <div  <?php if($info2000['en_mastqalandarshipment']==0) { echo ' style=" display:none;"'; } ?> class="<?php echo $info3000['formlayout_column'];?>">
 <br>

 
 <label>Total <?php $sauda_id =  $info5['sauda_id']; if($sauda_id=='0') echo 'Truck(s)'; else { echo $pwarehouse = mysqli_get_var("Select name from truck_type where id IN (Select truck_type from sauda where id='$sauda_id' )  ");  } ?></label>
  <input name="total_truck" value="<?php echo $info5['total_truck'];?>" type="number"   required   class="form-control" />                         
 
 </div>                       
    
   
   <div style=" <?php  if($info4000['invoice_cartonratep']==0) { echo "display:none;"; } ?>" class="<?php echo $info3000['formlayout_column'];?>">


<br>


   
   Kanta Weight<br>
  <input name="kanta_weight" value="<?php echo $info5['kanta_weight']; if($info5['kanta_weight']=='') echo 0; ?>"  class="form-control"  required  type="number" id="kanta_weight" />  

<br>  Factory Weight<br>
  <input name="factory_weight" value="<?php echo $info5['factory_weight']; ?>"  class="form-control"  required  type="number" id="factory_weight" />  
<br> <br>
</div>      
   
   
    <div  <?php if($info2000['en_paymentterms']=="0" ) { echo ' style=" display:none;"'; } ?> >
 
 <br>
<br>

<label>Payment Terms</label>

<?php $data4 = mysqli_query($conn,"SELECT * from payment_terms where 1=1  ") or die(mysqli_error($conn)); 

echo "<select name='payment_terms2'   class=' form-control' required >";

if($info2000['en_paymentterms']=="0"){ echo "<option value='0' >Select Payment Terms</option>"; }

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 
if($info4['id']==$info5['payment_terms']) {
 echo "<option value='".$info4['id']."' selected >".$info4['name']."</option>";

    } else {

   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
    }
 }
echo "</select>";
 ?>
           
 
 </div>
 
 
  <div  <?php if($info2000['en_shippingterms']=="0" ) { echo ' style=" display:none;"'; } ?> >
 

<label>Delivery Terms</label>

<?php $data4 = mysqli_query($conn,"SELECT * from delivery_terms where 1=1  ") or die(mysqli_error($conn)); 

echo "<select name='delivery_terms2'  class=' form-control' required >";

if($info2000['en_shippingterms']=="0"){ echo "<option value='0' >Select Delivery Terms</option>"; }

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 
if($info4['id']==$info5['delivery_terms']) {
 echo "<option value='".$info4['id']."' selected >".$info4['name']."</option>";

    } else {

   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
    }
   

 }
echo "</select>";
 ?>
           
 
 </div>
           
    
    
    
   <div  <?php if($info2000['display_dop']=="0" ) { echo ' style=" display:none;"'; } ?> >
 

 
 <label>Mode of Payment</label>
  <input name="dop" value="<?php echo $info5['dop'];?>" type="number"   required   class="form-control" />                         
 
 </div>   
    
<div <?php if($info3000['show_no_of_trucks'] != 1){ echo "style='display:none;'"; } ?> >
  <label>No. of Trucks</label>
  <input name="no_of_trucks" readonly value="<?php echo $info5['no_of_trucks'] ?>" type="number" required   class="form-control" />  

</div>  

<div <?php if($info3000['en_rice_bag_deduction'] != 1){ echo "style='display:none;'"; } ?> >
    <label>Average Weight of Bag</label>
    <input name="" id="weight_of_bag" readonly value="0" type="number" required   class="form-control" />
</div>   

<div <?php if($info3000['en_rice_bag_deduction'] != 1){ echo "style='display:none;'"; } ?> >
    <br>
    <label>Moiture Deduction On Bags</label>
    &nbsp; <input type="checkbox" class="moisture_deduction_bags" value="1" />
</div>  

       
    <div class="multi_currency <?php echo $info3000['formlayout_column'];?>" <?php if($info2000['multi_currency']==0) { echo ' style=" display:none;"';} ?>  >


<label>Currency</label>

<?php $data4 = mysqli_query($conn,"SELECT * from currency where 1=1  ") or die(mysqli_error($conn)); 

echo "<select name='currency' id='currency'  class=' form-control' required >";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 
 if($info4['id']==$info5['currency']) {
  echo "<option value='".$info4['id']."' selected >".$info4['name']."</option>";     
     } else {
 
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}
 }
echo "</select>";
 ?>
 </div>


 <div class="<?php echo $info3000['formlayout_column'];?>">
 <label>Currency Rate</label>

<div class="currencyfilter"><input type="text" name="currency_rate" class="form-control income_count" value="<?php echo $info5['currency_rate']; ?>" /></div>

</div>  

<?php if($info3000['en_goodluck']==1) {   ?>
<div class="<?php echo $info3000['formlayout_column'];?>">   
 <br>
 <label>SLC Currency Rate</label>

<div class="slc_currencyfilter"><input type="text" name="slc_currency_rate" class="form-control" value="<?php echo $info5['slc_currency_rate']; ?>" <?php echo $read_only;?> /></div>

</div>  
<?php } ?>
      
               
               
                   <div <?php if($info2000['en_ricetrade']==0  && $info4000['salepurchase_accountdynamic']==0  && $info2000['en_appollo']==0) { echo ' style=" display:none;" ';  } ?> > 
    
  <label>Purchase Account</label>
    <br>
    <?php 
    $data4 = mysqli_query($conn,"SELECT id, a_code, name from accounts_type where  1=1  && id!='$unadjust_account'   $caccounts_company  group by id, a_code, name   order by a_code ")or die(mysqli_error($conn)); 
    echo "<select name='sales_id'   class='form-control  reportselect'   >";
    while($info4 = mysqli_fetch_array( $data4 )) { 
        if($info4['id']==$info5['sales_account']) {
            echo "<option value='".$info4['id']."' selected >".$info4['a_code']." ".$info4['name']."</option>"; 
        } else {
            echo "<option value='".$info4['id']."' >".$info4['a_code']." ".$info4['name']."</option>"; 
        }
    }
    echo "</select>"; ?>
    <br><br>
        <div <?php if($info3000['dynamic_creditaccount']==0) { echo ' style=" display:none;" ';  } ?> >
        <label>Credit Account</label> <br>
                    <?php $data4 = mysqli_query($conn,"SELECT id, a_code, name from accounts_type where 1=1  $caccounts_company  group by id, a_code, name   order by a_code ")or die(mysqli_error($conn)); 
                      echo "<select name='credit_account' required  class='form-control reportselect'   >";
                      echo "<option value='' >Select Credit Account</option>"; 
                      while($info4 = mysqli_fetch_array( $data4 )) { 
                        $selected = '';
                         if($info4['id'] ==$info5['credit_account'])
                            $selected = 'selected';
                        echo "<option value='".$info4['id']."' ".$selected.">".$info4['a_code']." ".$info4['name']."</option>"; 
                      }
                      echo "</select>";
                      ?>
                    <br><br>
                  </div>
                     <div class="<?php echo $info3000['formlayout_column'];?>"  <?php if($info3000['dynamic_creditaccount']==0) { echo ' style=" display:none;" ' ;  } ?>>
                     <label>Tax Account </label><br>
        <?php $data4 = mysqli_query($conn,"SELECT id, a_code, name  from accounts_type where  1=1  $caccounts_company  group by id, a_code, name  order by a_code ")or die(mysqli_error($conn)); 
            echo "<select name='tax_account' required  class='form-control reportselect'   >";
            echo "<option value='' >Select Tax Account</option>"; 
            while($info4 = mysqli_fetch_array( $data4 )) { 
                $selected = '';
                if($info4['id'] ==$info5['tax_account'])
                    $selected = 'selected';
                echo "<option value='".$info4['id']."' ".$selected.">".$info4['a_code']." ".$info4['name']."</option>"; 
            }
            echo "</select>";
        ?><br><br>  
                     </div>
                
</div>

               
                       <!--Own Text End -->
                <!-- </div>
            </div> -->
        </div>
    </div>

<!-- pk start work -->
<div class="col-md-12">
    <div class="card card-height-100 h-100">
        <div class="card-body">
              
              
               <?php
                    if($info2000['meditech_singleinvoice']==1) {    $result = mysqli_query($conn, "SELECT * FROM purchasing_grn WHERE vendor_id='$vendor_id' && approval!=0 && ( completed=0 || id IN ( Select grn_id from pi_grn_link where pi_id='$id') ) ")or die(mysqli_error($conn));
                        
                             ?>
                    <table width="100%" border="1" cellspacing="0" cellpadding="5" class="table table-striped table-hover align-middle">
                
                            <tr>
                                <td>GRN</td>
                                <td>PO</td>
                                <td>Amount</td>
                                 <td>Action</td> 
                            </tr>
                            <?php
                                while($myrow = mysqli_fetch_array($result)){
                                ?>
                                <tr>
                                    <td><?php echo $myrow['id']; ?></td>
                 
                   <td><?php echo $myrow['po_id']; ?></td>
                 
                  <td><?php echo number_format($myrow['currency_total']); ?></td>   
                                    <td>
                                      <input type="checkbox" name="grn_list[]"  class="grn_list" value="<?php echo $myrow['id']; ?>" <?php if($myrow['completed']==1) { echo 'checked'; } ?> >
                                     
                                    </td>
                                
                                </tr>
                            <?php
                            }   
                        ?>
                </table>
                
                <br>
<br>
<?php }
                        ?>
                        
            
              
              
              
              
                        <div class="row g-3 align-items-end">
<?php
                     
            $result = mysqli_query($conn, "SELECT * from rice_field where  en_purchase = 1   $climit_rice_field && `inventory`=1  AND pi = 1 order by orderby ASC ")or die(mysqli_error($conn));
            $count_rows = mysqli_num_rows($result);
            $again = 1;
            if($count_rows > 0){
              $again = 0;
            ?>
<?php
         while($myrow = mysqli_fetch_array($result)){
         $field_id = (int)$myrow['id'];
         $text = 'number';
         $step = ' step="0.0001"';
         $text_name = 'values[]';
         $value = mysqli_get_var("SELECT value FROM rice_field_details WHERE sid = '$id' AND fid = '".$myrow['id']."' AND stype = 6 order by id");
         if($value == ''){
             $value = $myrow['value'];
         }
?>
    <div class="col-12 col-sm-6 col-lg-3">
        <label class="form-label"><?php echo $myrow['label']; ?></label>
        <input type="hidden" name="fid[]" value="<?php echo $field_id; ?>">
<?php
         if($myrow['itype'] == 1){
             $text = 'text';
             $step = '';
         } else if($myrow['itype'] == 3){
             $text = 'date';
             $step = '';
         } else if($myrow['itype'] == 10){
             $text = 'time';
             $step = '';
         } else if($myrow['itype'] == 2){
             $value = mysqli_get_var("SELECT value FROM rice_field_details WHERE sid = '$id' AND fid = '".$myrow['id']."' AND stype = 6 order by id");
             if($value == ''){
                 $value = $myrow['value'];
             }
             $str_sel = $myrow['value'];
             $arry_sel = explode("|", $str_sel);
             $text = 'hidden';
             $step = '';
             $text_name = 'values_disabled[]';
?>
        <select class="form-control <?php echo $myrow['class']; ?>" name="values[]" <?php if($myrow['required'] == 1){ echo 'required'; } ?>>
            <option value="" <?php echo ($value=='')?"selected":''; ?>>Select</option>
            <?php foreach($arry_sel as $rice_sel){ ?>
                <option value="<?php echo $rice_sel; ?>" <?php echo ($value==$rice_sel)?'selected':''; ?>><?php echo $rice_sel; ?></option>
            <?php } ?>
        </select>
<?php
         } else if($myrow['itype'] == 4){
             if($value == ''){
                 $value = $myrow['value'];
             }
             $text = 'hidden';
             $step = '';
             $text_name = 'values_disabled[]';
?>
        <textarea class="form-control <?php echo $myrow['class']; ?>" name="values[]" <?php if($myrow['required'] == 1){ echo 'required'; } ?>><?php echo $value; ?></textarea>
<?php
         } else if($myrow['itype'] == 5){
             $rice_id = $myrow['id'];
             if($value == ''){
                 $value = $myrow['value'];
             }
             $text = 'hidden';
             $step = '';
             $text_name = 'values_disabled[]';
?>
        <script>
            (function(){
                const input = document.getElementById('image_<?php echo $myrow['id']; ?>');
                if (input && '<?php echo $value; ?>') {
                    const file = new File(['<?php echo $value; ?>'], '<?php echo $value; ?>', { type: 'text/plain', lastModified: Date.now() });
                    const transfer = new DataTransfer();
                    transfer.items.add(file);
                    input.files = transfer.files;
                }
            })();
            function resetimage(id){
                $(".arrival_image_" + id).html('');
            }
        </script>
        <input type="file" onclick="resetimage(<?php echo $myrow['id']; ?>)" name ="riceimage[]" maxlength="255" id="image_<?php echo $myrow['id']; ?>" class="form-control filess ricefield_image <?php echo $myrow['class']; ?>" value="<?php echo $value; ?>" <?php if($myrow['required'] == 1){ echo 'required'; } ?>>
        <div id="asettext_<?php echo $myrow['id']; ?>">
            <input type="hidden" name="values[]" value="<?php echo ($value=='')?'Not Upload':$value; ?>"/>
            <?php if($value!=''){ ?>
                <span class="arrival_image_<?php echo $myrow['id']; ?>"><img src="ricefield_images/<?php echo $value; ?>" height="150" width="225" class="img-thumbnail" /></span>
            <?php } ?>
        </div>
<?php
         }
?>
        <input type="<?php echo $text; ?>"<?php echo $step; ?> class="form-control <?php echo $myrow['class']; ?>" name="<?php echo $text_name; ?>" value="<?php echo $value; ?>" <?php if($myrow['required'] == 1){ echo 'required'; } ?>>
    </div>
<?php
     }
?>
</div>
<?php
     }
    ?>
  
              </div>
            <!-- </div>
        </div>
    </div> -->
</div>
<!-- pk end work --> 


<div id="psearch" class="psearch"> </div>

<div class="cartcustom-overlay col-md-12" >
<table width="100%" cellpadding="5"  class="table table-striped table-hover align-middle" id="acart">
 <thead>
            <tr>
                <th width="20%"><div><?php echo $info1000['product_label']; ?></div></th> 
                 <th <?php if($info1000['hide_qavailable']==1 || $info3000['en_aico']==1) echo ' style="display:none;"';  ?> ><div><?php echo $info3000['qta_avl_label']; ?></div></th>
                 <th ><div><?php echo $info1000['multi_unit_labelp']; ?></div></th>
                 <?php  if($info2000['uom_display']==1) { ?> <th align="center"><?php echo $info2000['uom_label']; ?></th><?php } ?>
                 <th <?php if($info1000['no_purchasepacking']==1 || $info2000['pcs_hidec']==1) echo ' style="display:none;"';  ?>  ><div><?php echo $info1000['single_unit_label']; ?></div></th>
           
      <th <?php if($info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info2000['customfield1c_display'];  ?></div></th>
<th <?php if($info4000['en_customfield2c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info4000['customfield2c_label'];  ?></div></th>
  <th <?php if($info4000['en_customfield3c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info4000['customfield3c_label'];  ?></div></th>                        
<th <?php if($info3000['en_customfield4c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info3000['customfield4c_label'];  ?></div></th>
  <th <?php if($info3000['en_customfield5c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info3000['customfield5c_label'];  ?></div></th>
<th <?php if($info3000['en_customfield6c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info3000['customfield6c_label'];  ?></div></th>           


             <th <?php if($info3000['en_goodluck']==0 || $info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?> ><div><?php echo $info2000['customfield1c_display'];  ?></div></th>
              <th <?php if($info3000['en_goodluck']==0 || $info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?> ><div><?php echo $info2000['customfield1c_display']." Difference  ";  ?></div></th>

           
                  <?php if($info1000['en_warehouse']==1) {  echo  '  <th ><div>'.$info2000['warehouse_label'].'</div></th> '; } ?>
                 
                
                <th <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  ><div>Stock Level</div></th>
       <th <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  ><div>Sale  Price</div></th>
      
                
       <?php if($info1000['batch_with_brand']==1) {  echo  '  <th ><div>Brand</div></th> '; } ?>
                <?php if($info1000['en_inventorybatch']==1) {  echo  '  <th ><div>'.$info1000['batch_label'].'</div></th> '; } ?>
                  <?php if($info1000['en_expirydisplay']==1) {   echo  '  <th ><div>Expiry </div></th> '; } ?>        
         
               
                 <th <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>  ><div><?php echo $info1000['packing_label']; ?></div></th>
                 <th ><div><?php echo $info4000['price_labelp']; ?></div></th>
      <th <?php if($info4000['separate_mrpcolumnp']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info4000['mrp_label']; ?></div></th> 
       <?php if( $info4000['itemmulti_unit']==1) { 
                    echo '<th ><div>Unit</div></th>
                    <th style="display:none;" ><div>Unit Rate</div></th>'; 
                } ?>
      
         <?php  if($info4000['invoice_cartonratep']==1) {  ?>
            <th ><div>Rate Apply</div></th>
            <?php } ?>
           
           <th <?php if($info2000['en_ricetrade']==0) echo ' style="display:none;"';  ?> ><div><?php echo $info2000['itemcustomunit_label']; ?></div></th>
           
                  <?php if($info1000['vendor_discount1']==1) {  echo  '  <th ><div>'.$info1000['disc1_label'].'</div></th> '; } ?> 
             <?php if($info1000['vendor_discount2']==1) {  echo  '  <th ><div>'.$info1000['disc2_label'].'</div></th> '; } ?>
                <?php if($info1000['vendor_discount4']==1) {  echo  '  <th ><div>'.$info1000['disc3_label'].'</div></th> '; } ?>
       
        <?php if($info4000['vendor_foc']==1) {  echo  '  <th ><div>'.$info4000['customerfoc_label'].'</div></th> '; } ?> 
              
           <?php if($info1000['vendor_discount3']==1) {  echo  '  <th ><div>'.$info1000['toffer_label'].'</div></th> '; } ?> 
          <?php if($info1000['vendor_scheme']==1) {  echo  '  <th ><div>'.$info1000['scheme_label'].'</div></th> '; } ?>   
                
                  <th <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?> ><div><?php echo $info1000['total_unit_label']; ?></div></th>
    <?php if($info4000['display_taxamount']==1){   ?>    
            <th>Exclusive of GST Amount</th>    
            <?php } ?> 
       <?php if($info1000['vendor_tax1']==1) {  echo  '  <th ><div>'.$info1000['tax1_label'].'</div></th> '; } ?> 
        <?php if($info1000['vendor_tax2']==1) {  echo  '  <th ><div>'.$info1000['tax2_label'].'</div></th> '; } ?> 
         <?php if($info1000['vendor_tax3']==1) {  echo  '  <th ><div>'.$info1000['tax3_label'].'</div></th> '; } ?>  

         <?php if($info4000['display_taxamount']==1){    ?>    
            <th><?php echo $info4000['taxamount_label']; ?></th>    
            <?php } ?>         
             

                 <th width="80px" ><div>Total</div> </th> 
                 <th></th> 
          </tr>
          
          </thead>
          <tbody>
           <?php
           $use_grouped_items = ($info3000['en_smartbatch']==1);
           if($use_grouped_items) {
             $data2 = mysqli_query($conn,"SELECT MIN(d.id) as id, MAX(d.prd_id) as prd_id, MAX(d.prd_id) as pid, MAX(d.prd_id) as did, SUM(d.qty) AS pqty, SUM(d.prd_amount) as prd_amount, MAX(d.packing) as dp, MAX(d.packing2) as packing2, MAX(d.packing2) as pac2, MAX(d.batch_id) as batch_id, MAX(d.custom_field1) as cf1, MAX(d.custom_field2) as cf2, MAX(d.custom_field3) as cf3, MAX(d.custom_field4) as custom_field4, MAX(d.custom_field5) as custom_field5, MAX(d.custom_field6) as custom_field6, MAX(d.tax_mrp) as ptax_mrp, MAX(d.mrp_price) as pmrp_price, MAX(d.discount) as dd, MAX(d.tax_applied) AS ta, MAX(d.tax_applied2) AS ta2, MAX(d.tax_applied3) AS ta3, MAX(d.discount2) as dd2, MAX(d.discount3) as dd3, MAX(d.discount4) as dd4, MAX(d.tax_type) as tax_type, MAX(d.tp) as tp, MAX(d.warehouse_id) AS warehouse_id2, MAX(d.details2) as details2, MAX(d.rate_in_carton) as rate_in_carton, MAX(d.uom) as uom, MAX(d.foc) as pfoc, MAX(d.unit) as dunit, MAX(p.name) as name, MAX(p.brand_id) as brand_id, MAX(p.min_qty) as min_qty, MAX(p.max_qty) as max_qty, MAX(p.mrp_price) as mrp_price from purchasing_details d, inventory p WHERE p.id=d.prd_id AND d.order_id='$id' group by d.prd_id order by MIN(d.id) ") or die(mysqli_error($conn));
           } else {
             $data2 = mysqli_query($conn,"SELECT *, d.batch_id, d.packing2,  d.custom_field1 as cf1, d.custom_field2 as cf2, d.custom_field3 as cf3, d.tax_mrp as ptax_mrp, d.mrp_price as pmrp_price, d.prd_id as pid,  d.qty AS pqty, d.packing as dp, d.packing2 as pac2, d.discount as dd, d.tax_applied AS ta, d.tax_applied2 AS ta2, d.tax_applied3 AS ta3, d.discount2 as dd2, d.discount3 as dd3, d.discount4 as dd4,  d.prd_id AS did, d.warehouse_id AS warehouse_id2, p.brand_id as brand_id from purchasing_details d, inventory p WHERE p.id=d.prd_id AND d.order_id='$id' order by d.id  ") or die(mysqli_error($conn));
           }
        
    
    $totc=0;
    $totp=0;
    $tots=0;
        
while($info2 = mysqli_fetch_array( $data2 )) 
 { 
 
  if($info2000['scheme_directfoc']==0) { 
$sscheme = $info2['scheme_qty'];
 } else {
    
$sscheme = 0;    
     }
 
 
 
 ?>

<?php   if(1==1)  { ?>
             
          <tr class="carttr">     
                <td >
                    <input type="hidden" id="brandidd<?php echo $info2['prd_id'];?>"
                            value="<?php echo $info2['brand_id'];?>" />
                    <input name="products[]" type="hidden" class="products singleitem" value="<?php echo $info2['prd_id'];?>" />  <?php echo $info2['name'];?> 
         <input type="hidden" id="<?php echo "pptax".$info2['id'];?>" name="taxtype[]" value="<?php echo $info2['tax_type'];?>"  />        
                               <div  <?php if($info1000['item_description']==0) echo ' style="display:none;"';   ?>  >
          <textarea name="products_description[]" class="form-control" placeholder="Details.."><?php echo nextlineinput($info2['details2']); ?></textarea> 
        </div> 
                
                </td>
               
                <td  <?php if($info1000['hide_qavailable']==1 || $info3000['en_aico']==1) echo ' style="display:none;"';  ?> ><?php
                
                $sp = $info2['warehouse_id2'];
    $stocksingle = $info2['prd_id'];
    $batch_id=$info2['batch_id'];
    
    if($info2000['qta_inpacking']==0) { $a=' SUM(qty) '; } else { $a=' SUM(qty/packing) '; }
    
    $minus = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=0 && w.deleted=0 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' "); 
   
    $plus = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=1 && w.deleted=0 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' "); 
 $minus3 = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && w.deleted=0 && (w.tran_type=1 || w.tran_type=21) && verified_by=0 && t.type=1 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' "); 

// echo $sbalance=$plus-$minus-$minus2-$minus3; 

$sbalance = get_available_quantity($stocksingle, $sp, 0, 0, $batch_id); 
echo number_format($sbalance, 2);

?> 
</td>
                <td >
    <?php 

    


$discount=$info2['dd']/100; 
$discount2=$info2['dd2']/100; 
$discount4=$info2['dd4']/100;
 
// $discount3=$info2['dd3']/100; 
$toffer = $info2['dd3']*($info2['pqty']-$sscheme);

$tax= $info2['ta']/100;
$tax2= $info2['ta2']/100;
$tax3= $info2['ta3']/100;


$discount=1-$discount;  
$discount2=1-$discount2;  
$discount4=1-$discount4;  
//$discount3=1-$discount3;  


$aaqty = $info2['pqty']-$info2['scheme_qty'];

 $sb = $info2['prd_amount'];
 $m = $aaqty * $discount * $discount2 * $discount4 ;


if($info2['tax_type']==2)
{


$tottax=1 + $tax + $tax2 + $tax3;  

$tamount = $info2['prd_amount']/$tottax;

 $n = 0;


$nm = $n + $m ;
$x = ($tamount  + ($toffer*$discount*$discount2*$discount4) ) / $nm;

}
else if($info2['tax_type']==1)
{
 $n = $info2['pqty'] * ($tax + $tax2 + $tax3);  
 $nm = $n + $m ;
$x = ($info2['prd_amount'] + ($toffer*$discount*$discount2*$discount4)   ) / $nm;
 }
else {

 $n = 0;
 
 $nm = $n + $m ;
$x = ($info2['prd_amount']  + ($toffer*$discount*$discount2*$discount4)   ) / $nm;
 
    } 




$price= $x;


if($info1000['rate_incartonp']==1) {  
$price=$price*$info2['dp'];
 } 

$quant_tot=$info2['pqty']+$quant_tot;




$price=round($price,  $info1000['pproductdecimal'] );

    
    
    $totc=$totc+$mpc;?> 
    <?php if($info2000['en_ricetrade_advance'] == 1){ ?>
    <input type="hidden" name="bag_weight[]" class="bag_weight" value="<?php echo mysqli_get_var("SELECT bag_weight FROM sauda WHERE id = '".$info5['sauda_id']."' "); ?>">
    <input type="hidden" name="bag_rate[]" class="bag_rate" value="<?php echo mysqli_get_var("SELECT bag_rate FROM sauda WHERE id = '".$info5['sauda_id']."' "); ?>">
    <?php } else{ ?>
    <input type="hidden" name="bag_weight[]" class="bag_weight" value="0">
    <input type="hidden" name="bag_rate[]" class="bag_rate" value="0">
    <?php } ?>
   <input type="number" step="0.0001" required   name="stitch_pcs[]" size="4" value="<?php 
 if($info3000['en_manualcustomfieldqty']==1) { echo round($info2['cf2']/$info2['dp']); } else  if($info4000['en_engineering']==1){
      
      echo $info2['packing2'];
      
  }else{
  
  if(is_decimal($info2['pqty'])) { echo (($info2['pqty']-$sscheme)/$info2['dp']); } else { echo floor(($info2['pqty']-$sscheme)/$info2['dp']); } 
  }  ?>"   class="searchqty packing income_count totalorder searchp" <?php if($info2000['multiple_batch']==1) { echo 'readonly'; } ?> id="ctn<?php echo $info2['id'];?>"  />
               
                </td>
        
        <?php  if($info2000['uom_display']==1) { ?> 
        <td>
          <?php if($info3000['en_uom_selection'] == 1){ ?>
            <select class="form-control reportselect" name="uom[]" required="">
              <?php 
              $data4 = mysqli_query($conn, "SELECT * FROM product_unit") or die(mysqli_error($conn)); 
              while($info4 = mysqli_fetch_array($data4)){
                ?><option value="<?php echo $info4['id'] ?>" <?php if($info2['uom'] == $info4['id']){ echo "selected"; } ?> ><?php echo $info4['name']; ?></option><?php
              }
              ?>
            </select>
          <?php } else{ ?>
          <input type="hidden" name="uom[]" value="<?php echo $info2['unit'];  ?>">
          <?php echo mysqli_get_var("SELECT name FROM product_unit WHERE id = '".$info2['unit']."' "); ?>
          <?php } ?>
        </td>
        <?php } else{ ?>
          <input type="hidden" name="uom[]" value="<?php echo $info2['unit'];  ?>">
        <?php } ?>                
        
         <td  <?php if($info1000['no_purchasepacking']==1 || $info2000['pcs_hidec']==1) echo ' style="display:none;"';  ?> >
         
         
         <input type="text"   size="4" value="<?php if(is_decimal($info2['pqty'])) { echo 0; } else {  echo floor(($info2['pqty']-$sscheme)%$info2['dp']); } ?>"   class="change income_count totalorder"  id="pcs<?php echo $info2['id'];?>"/>
         
         </td>
       
                                   <td <?php if($info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?> ><input name="custom_field1[]" id="customfield<?php echo $info2['id'];?>" type="text" value="<?php echo $info2['cf1']; ?>"   class="form-control customfield1 mycf  " <?php if ($info3000['en_hapaperhub'] == 1) { echo 'style="max-width: 200px !important; width: 200px !important;"'; } ?> /> </td>  
                              

           <td <?php if($info4000['en_customfield2c']==0) echo ' style="display:none;"';  ?> ><input  style="width:100px;"  name="custom_field2[]"     id="customfield<?php echo $info2['id'];?>" type="text" value="<?php echo $info2['cf2']; ?>"  tabindex="1" class="form-control  <?php if($info3000['ctn_customfieldrate']==0) { ?>income_count<?php } ?>  customfield2" /> </td>   
                                 
                               <td <?php if($info4000['en_customfield3c']==0) echo ' style="display:none;"';  ?> ><input  style="width:100px;"   name="custom_field3[]"     id="customfield<?php echo $info2['id'];?>" type="text" value="<?php echo $info2['cf3']; ?>"  tabindex="1" class="form-control income_count customfield3" /> </td>  
                              
                               <td <?php if($info3000['en_customfield4c']==0) echo ' style="display:none;"';  ?> ><input  style="width:100px;"  name="custom_field4[]"     id="customfieldddd<?php echo $info2['id'];?>" type="text" value="<?php echo $info2['custom_field4']; ?>"  tabindex="1" class="form-control income_count customfield4" /> </td>  
                               
                               
                                  <td <?php if($info3000['en_customfield5c']==0) echo ' style="display:none;"';  ?> ><input name="custom_field5[]"     id="customfieldccd<?php echo $info2['id'];?>" type="text" value="<?php echo $info2['custom_field5']; ?>"  tabindex="1" class="form-control income_count customfield5" /> </td>
       

<td <?php if($info3000['en_customfield6c']==0) echo ' style="display:none;"';  ?> ><input name="custom_field6[]"     id="customfieldccdd<?php echo $info2['id'];?>" type="text" value="<?php echo $info2['custom_field6']; ?>"  tabindex="1" class="form-control income_count customfield6" /> </td>

                                   
       
            <td <?php if($info2000['en_customfield1c']==0 || $info3000['en_goodluck']==0) echo ' style="display:none;"';  ?> ><input name="price_slc[]"      type="text"  id="price_slc<?php echo $info2['id'];?>"  tabindex="1" class="form-control price_slc income_count" value="<?php $diff_slc=$info2['custom_field1']; echo $diff_slc ; ?>" /> </td>

         <td <?php if($info2000['en_customfield1c']==0 || $info3000['en_goodluck']==0) echo ' style="display:none;"';  ?> ><input name="slc_amt[]"  readonly    type="text"  tabindex="1" id="slc_amt<?php echo $info2['id'];?>" class="form-control slc_amt income_count"  value="<?php echo  $diff_slc * $info2['qty']; ?>"/> </td>  

       
       
         <?php if($info1000['en_warehouse']==1) { ?>
             <td><select name="products_warehouse[]"   class='teacher warehouse combobox'  ><?php $data4 = mysqli_query($conn,"SELECT * from inventory_warehouse  where 1=1  $wlimit_warehouse $climit_warehouse ") or die(mysqli_error($conn)); 

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 
 if($info2['warehouse_id2']==$info4['id'])
 {
   echo "<option value='".$info4['id']."' selected >".$info4['name']."</option>";
}
else {
       echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
    }

 }



?>
</select></td>

<?php } ?>
              
     <td <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  >
      
         Min Qty <b><?php echo $info2['min_qty'];?></b><br>
           Max Qty <b><?php echo $info2['max_qty'];?></b>  
      
      </td>
       <td <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  >
      
           <input  tabindex="1" name="sale_price[]" type="text"  required class="  <?php if($info1000['open_ratecolumn']==1) { echo 'change15';  } else { echo 'edit-input'; } ?>  income_count  " value="<?php echo $info2['mrp_price'];?>"  size="4"  />
      
      </td>
              
              
              

      <?php if($info1000['en_inventorybatch']==1 ) { ?>

<?php if($info1000['batch_with_brand']==1){
$batch_id = $info2['batch_id'];
$batch_name = mysqli_get_var("Select name from product_brands where id IN (select brand_id from inventory_batch where id = '$batch_id')");
?>
<td>
<input type="text" name="batch_brand[]"
  readonly
value="<?php echo $batch_name; ?>" tabindex="1"
class="change71 batch71 form-control"
id="<?php echo "batch_brand".$pid;?>" />
</td>
<?php } ?>

<?php
$smartbatch_entries = array();
$smartbatch_count = 0;
$smartbatch_json = '[]';
$smartbatch_first_batch = 0;
$smartbatch_first_expiry = '';
if($info3000['en_smartbatch']==1) {
  $pid = $info2['pid'];
  $data_sb = mysqli_query($conn,"SELECT d.batch_id, d.qty, b.batch_code, b.exp_date FROM purchasing_details d LEFT JOIN inventory_batch b ON d.batch_id=b.id WHERE d.order_id='$id' AND d.prd_id='$pid' order by d.id") or die(mysqli_error($conn));
  while($sb = mysqli_fetch_array($data_sb)) {
    $smartbatch_entries[] = array('batch' => $sb['batch_code'], 'qty' => $sb['qty']);
    if($smartbatch_first_batch==0) {
      $smartbatch_first_batch = $sb['batch_id'];
      $smartbatch_first_expiry = $sb['exp_date'];
    }
  }
  $smartbatch_count = count($smartbatch_entries);
  $smartbatch_json = htmlspecialchars(json_encode($smartbatch_entries));
}
?>

<?php if($info3000['en_smartbatch']==1) { ?>
<td>
  <button type="button" class="btn btn-default btn-sm smartbatch-open"
    data-item="<?php echo htmlspecialchars($info2['name']); ?>">+</button>
  <span class="smartbatch-view text-muted" <?php if($smartbatch_count==0){ echo "style='display:none;'"; } ?>>
    <?php echo "View (".$smartbatch_count.")"; ?>
  </span>
  <input type="hidden" name="smartbatch_data[]" class="smartbatch-data" value="<?php echo $smartbatch_json; ?>" />
  <input type="hidden" name="products_batch[]" value="<?php echo $smartbatch_first_batch; ?>" />
</td>
<?php $expiry = $smartbatch_first_expiry; ?>
<?php } else { ?>
<td><div class="batchdiv"><select name="products_batch[]"  readonly   class='teacher warehouse inventory3'  >
         <?php
         
           $pid = $info2['pid'];
           $bat = $info2['batch_id'];
         
          $data4 = mysqli_query($conn,"SELECT * from inventory_batch where (active=1 && prd_id='$pid' && type_component=0) || id='$bat' ") or die(mysqli_error($conn)); 

while($info4 = mysqli_fetch_array( $data4 )) 
{ 





if($info2['batch_id']==$info4['id'])
{
     $expiry = $info4['exp_date'];
   echo "<option value='".$info4['id']."' selected >".$info4['batch_code']."</option>";
}


}


?>
</select></div> <input type="hidden" name="batch_old[]" value="1" /></td>
<?php } ?>

<?php } ?>

 <?php  if($info1000['en_expirydisplay']==1) {  ?>
     
     <td><input type="date" name="products_expiry[]" value="<?php echo ($expiry!='' ? date('Y-m-d', strtotime($expiry)) : ''); ?>"  required  class="change8 form-control expiry7" id="<?php echo "expiry".$info2['id'];?>" /> </td>
  
     <?php } ?> 
       
         <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>>
         <input name="products_packing[]"   size="4"  type="text" value="<?php echo $info2['dp'];?>"  class="new_packing searchqty edit-input income_count totalorder"  id="p<?php echo $info2['id'];?>"  <?php if($info2000['en_ricetrade']==1){echo "readonly='readonly'";} ?> />
         
         

         </td>
       
       
       
                <td>
                <input name="unitcos[]"  type="number" step="0.00001" required  id="<?php echo "pp".$info2['id'];?>"   size="4"   value="<?php echo $info2['tp'];?>" class="new_rate edit-input unitcos income_count totalorder"   />
          
         

<input type="hidden" name="discount5[]" value="0" id="<?php echo "pppl".$info2['id'];?>"  tabindex="1"  class="edit-input income_count"   size="4"   /> 

                
             <?php
          if($info4000['separate_mrpcolumnp']==0)
          {
            ?>
       
          <input name="mrp_price[]" size="4"   type="hidden" class="edit-input income_count totalorder" id="<?php echo "mrp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2['pmrp_price'];?>"  />
          <?php
        }
     
        ?>

                  
                <input name="tax_mrp[]" size="4"   type="hidden" class="edit-input income_count totalorder" id="<?php echo "mrptax".$info2['id'];?>"    value="<?php echo $info2['ptax_mrp'];?>"  />     
         
            </td>

    
    <?php if($info4000['separate_mrpcolumnp']==1) { ?><td >
      
      
               <input name="mrp_price[]" size="4"   type="number" step="0.0001" required class="edit-input income_count totalorder" id="<?php echo "mrp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2['pmrp_price'];?>"  readonly="readonly" />
          
      
    
    </td>
    <?php } ?>

               
               
                <?php if($info4000['itemmulti_unit']==1){ ?>
            <td>
            <input name="prd_hidden[]" type="hidden" class="prd_hidden" value="<?php echo $info2['prd_id'];?>"  />
            <input name="packing_hidden[]" type="hidden" class="packing_hidden" value="<?php echo $info2['dp'];?>" />
            <?php 
            
            $single_unit = mysqli_get_var("SELECT unit FROM inventory WHERE id='".$info2['did']."' ");
            $data4 = mysqli_query($conn,"SELECT * FROM product_unit WHERE id IN (SELECT unit FROM multiple_product_unit WHERE pid = '".$info2['did']."' )  ") or die(mysqli_error($conn)); 
            echo "<select name='munit[]'  required class='reportselect munit form-control'   >";
            //echo "<option value='0' >Select Product Unit</option>";
            while($info4 = mysqli_fetch_array( $data4 )){ 
                $selected = '';
                if($info2['dunit'] == $info4['id'])
                    $selected = 'selected';
                echo "<option value='".$info4['id']."' $selected >".$info4['name']."</option>";
            }
            echo "</select>";
            ?></td>
            <td style="display:none;"><input name="con_rate[]" value="<?php echo $info2['unit_rate'];?>" size="4" class="con_rate" id="" /></td>
        <?php } ?>
               
                <td <?php  if($info4000['invoice_cartonratep']==0) { echo ' style=" display:none;"'; } ?>> <select name='rate_in_carton[]' class='teacher income_count case2qty' id="<?php echo "ric".$info2['id'];?>"   >
 <option value='0' >Default</option>
 <option value='1' <?php if($info2['rate_in_carton']==1) { echo ' selected'; } ?> ><?php echo $info1000['packing_label']; ?></option>
 <option value='2'  <?php if($info2['rate_in_carton']==2) { echo ' selected'; } ?> ><?php echo $info1000['multi_unit_label']; ?></option>
 <option value='3'  <?php if($info2['rate_in_carton']==3) { echo ' selected'; } ?> ><?php echo $info2000['customfield1_display'];  ?></option>
 </select>
            </td> 
               
                <td <?php  if($info2000['en_ricetrade']==0) { echo ' style=" display:none;"'; } ?> ><input name="packing2[]" type="number" step="0.01" class='teacher income_count packing2'  value="<?php echo $info2['pac2']; ?>"  id="<?php echo "packk".$info2['id'];?>"   required/> </td>    
                
                
                
               
               <?php if($info1000['vendor_discount1']==1) {     ?>   <td ><input name="products_discount[]" size="4"   type="text" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"    value="<?php echo $info2['dd'];?>"  /></td>
  <?php } else { ?> <input name="products_discount[]"  type="hidden" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"    value="0" size="4" />
    <?php } if($info1000['vendor_discount2']==1) {     ?>                <td ><input name="products_discount2[]" size="4"   type="text" class="edit-input income_count totalorder" id="<?php echo "pppn".$info2['id'];?>"    value="<?php echo $info2['dd2'];?>"  /></td>
 <?php } else { ?> <input name="products_discount2[]" type="hidden" class="edit-input income_count totalorder" id="<?php echo "pppn".$info2['id'];?>"    value="0" size="4" /> 
 
  <?php }
  if($info1000['vendor_discount4']==1) {     ?>                <td ><input name="products_discount4[]" size="4"   type="text" class="edit-input income_count totalorder" id="<?php echo "pppx".$info2['id'];?>"    value="<?php echo $info2['dd4'];?>"  /></td>
 <?php } else { ?> <input name="products_discount4[]" type="hidden" class="edit-input income_count totalorder" id="<?php echo "pppx".$info2['id'];?>"    value="0" size="4" /> 
 
  <?php }
  
   if($info4000['vendor_foc']==1) {
  $purchase_foc_scheme = mysqli_get_var("SELECT discount_percentage FROM amount_discountp WHERE min_amount='".$info2['prd_id']."'");
  $purchase_foc_value = mysqli_get_var("SELECT discount_value FROM amount_discountp WHERE min_amount='".$info2['prd_id']."'");
  if($purchase_foc_scheme=='') { $purchase_foc_scheme = 0; }
  if($purchase_foc_value=='') { $purchase_foc_value = 0; }
  $purchase_foc_threshold = max((float)$purchase_foc_scheme, (float)$purchase_foc_value);
  $purchase_foc_qty = min((float)$purchase_foc_scheme, (float)$purchase_foc_value);
  $purchase_foc_initial = 0;
  if($purchase_foc_threshold > 0 && $purchase_foc_qty > 0) {
    $purchase_foc_initial = floor((float)$info2['pqty'] / $purchase_foc_threshold) * $purchase_foc_qty;
  }
  $totc = $totc + $purchase_foc_initial;
  $totp = $totp + ($purchase_foc_initial*$info2['pac']);
  ?>
  <td><input type="text" name="products_foc[]" value="<?php echo $purchase_foc_initial; ?>" class="foc income_count" id="<?php echo "pfoc".$info2['id'];?>"  required size="4"   />
  <input type="hidden" class="foc_scheme" id="<?php echo "pfoc_scheme".$info2['id'];?>" value="<?php echo $purchase_foc_scheme; ?>" />
  <input type="hidden" class="foc_value" id="<?php echo "pfoc_value".$info2['id'];?>" value="<?php echo $purchase_foc_value; ?>" />
  </td>

<?php } 
else { ?> <input name="products_foc[]" type="hidden" class="edit-input income_count totalorder" id="<?php echo "pfoc".$info2['id'];?>"    value="0" size="4" />
<input type="hidden" class="foc_scheme" id="<?php echo "pfoc_scheme".$info2['id'];?>" value="0" />
<input type="hidden" class="foc_value" id="<?php echo "pfoc_value".$info2['id'];?>" value="0" /> 
 
  <?php } 

   if($info1000['vendor_discount3']==1) {     ?>                <td ><input name="products_discount3[]"  type="text" size="4"  class="edit-input income_count totalorder products_discount3" id="<?php echo "pppm".$info2['id'];?>"    value="<?php echo $info2['dd3'];?>"  /></td>
   <?php } else { ?>
 <input name="products_discount3[]" type="hidden" class="edit-input income_count totalorder products_discount3" id="<?php echo "pppm".$info2['id'];?>"    value="0" size="4" />   
   <?php } if($info1000['vendor_scheme']==1) {     ?>                <td ><input name="products_scheme[]"  type="text" size="4"  class="edit-input pscheme5 totalorder" id="<?php echo "ppps".$info2['id'];?>"    value="<?php echo $info2['scheme'];?>"  /></td>
  <?php } else { ?>   <input name="products_scheme[]"  type="hidden" class="edit-input pscheme5 totalorder" id="<?php echo "ppps".$info2['id'];?>"    value="0" size="4" />       <?php }   ?>        
        
               
                 <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?> >
                 <?php $totp=$totp+$info2['pqty'];?>  
          
        <input name="products_scheme_qty[]" type="hidden" class="edit-input income_count totalorder" id="<?php echo "pppss".$info2['id'];?>"    value="<?php echo $info2['scheme_qty'];?>" size="4" /> 
                          
                 <input  name="products_pcs[]" step="0.0001" size="4" type="text" class="edit-input total_pcs" value="<?php echo $info2['pqty'];?>"  id="<?php echo "t".$info2['id'];?>" readonly /></td>
         <?php if(1==1){   ?>     
     <td  <?php if($info4000['display_taxamount']==0){ echo ' style="display:none;"';    }  ?> >
   <input name="display_totaltax2[]" type="text" class="income_count display_totaltax2" id="<?php echo "ppptttt".$info2['id'];?>"    value="0" size="4" readonly/>
</td>
<?php } ?>      
         
          <?php if($info1000['vendor_tax1']==1) {     ?>               <td ><input type="number" step="0.0001" required name="products_tax[]" class="edit-input income_count" value="<?php echo $info2['ta'];?>"  id="<?php echo "pppp".$info2['id'];?>" size="4"  readonly /></td>
 <?php } else { ?> 
       <input name="products_tax[]" type="hidden" class="edit-input income_count" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1 && $st==1) { echo 0; } else { echo 0;}?>" size="4" readonly />
 
      <?php } ?>
       <td <?php if($info4000['invoice_cartonratep']==0) { echo ' style=" display:none;" '; } ?>  ><input  name="pipe[]" type="text" class="edit-input income_count" tabindex="1" id="<?php echo "pipe".$info2['id'];?>" value="<?php  echo 0; ?>" size="4" readonly /></td>
      
      <?php if($info1000['vendor_tax2']==1) {     ?>             <td ><input type="text" name="products_tax2[]" class="edit-input income_count" value="<?php echo $info2['ta2'];?>" id="<?php echo "ppptt".$info2['id'];?>" size="4"  readonly /></td>
  <?php } else { ?>
  
  <input name="products_tax2[]" type="hidden" class="edit-input income_count totalorder" id="<?php echo "ppptt".$info2['id'];?>"    value="0" size="4" />
      <?php } if($info1000['vendor_tax3']==1) {     ?>             <td ><input type="text" name="products_tax3[]" class="edit-input income_count" value="<?php echo $info2['ta3'];?>" id="<?php echo "pppttt".$info2['id'];?>" size="4"  readonly /></td>
  <?php } else { ?>    
  <input name="products_tax3[]" type="hidden" class="edit-input income_count totalorder" id="<?php echo "pppttt".$info2['id'];?>"    value="0" size="4" />
   <?php }    ?>                      
         
         <?php if(1==1){   ?>     
     <td  <?php if($info4000['display_taxamount']==0){ echo ' style="display:none;"';    }  ?> >
   <input name="display_totaltax[]" type="text" class="income_count display_totaltax" id="<?php echo "ppptt".$info2['id'];?>"    value="0" size="4" readonly/>
</td>
<?php } ?>        
               
               <td >
              <?php $tots=$tots+$info2['prd_amount'];?> 
              
               <input type="hidden" name="products_cogs[]" value="<?php echo $info2['cogs'];?>"  /><input name="products_total[]" type="text" class="tot<?php echo $info2['id'];?> ptotal sub_total income_count " id="newtotal<?php echo $info2['id'];?>"  size="7" value="<?php echo $info2['prd_amount'];?>"  readonly  /> </td>
            <td><?php if(1==1) { ?><input type="button" class="edit" value="Edit" /><input type="button" class="save" value="Save" /><?php } ?><?php if(1==1) { ?><input type="button" class="delete" value="Delete" /> <?php } ?></td>
               
               
            </tr>
          
               
               <?php 
                  
               } 
                 } ?>
            </tbody>
            <tfoot>
                     
           
            </tfoot>
      </table>
      
     </div>
             
    
        
        
        
        <div class="row mt-3">
            <!-- <div class="card card-height-100 h-100">
                <div class="card-body"> -->
                       <!--Own Text -->
                       
  


    <div id="customerdisc" <?php  if($info1000['en_discount']==0) { echo ' style=" display:none;"'; } ?>>

Discount (%) <input name="discount" type="number" step="0.0001" required class="form-control" id="discount"  value="<?php echo $info5['discount'];?>" /><br />
</div>

<div class="invoicetax" <?php  if($info1000['en_tax']==0) { echo ' style=" display:none;"'; } ?>>
<?php  
echo 'Tax Applied <input name="tax" type="number" step="0.0001" required id="tax" value="'.$taxapply.'"  class="form-control"  /><br />';    ?>
</div>

<div class="shipping5" <?php  if($info1000['en_shipping']==0) { echo ' style=" display:none;"'; } ?> >
Freight Charges <input name="shipping" type="number" step="0.0001" required id="shipping"    value="<?php echo $info5['shipping_charges'];?>"  class="form-control"/><br /></div>



<div class="<?php echo $info3000['formlayout_column'];?>">
Notes

<?php
if ($info4000['en_vgm']==1) {
    $sid = $_GET['sid'];
    $ricedata  =mysqli_get_var("SELECT GROUP_CONCAT(a.label,': ',b.value) as rice_data  FROM `rice_field_details` as b ,rice_field as a
    WHERE a.id=b.fid and  b.sid in($sid) and b.stype='6'");
  $notes = $info5['notes'];
 $notes =  str_replace("$ricedata","","$notes");
}else{

    $notes = $info5['notes'];
}
?>
<textarea name="notes" <?php if($info1000['notes_required']==1) { echo 'required';  } ?> class="form-control"><?php echo nextlineinput($notes);?></textarea>
</div>


<div class="<?php echo $info3000['formlayout_column'];?>" <?php if($info2000['hide_oldtransport']==1) echo ' style="display:none"';  ?> >
<?php $data4 = mysqli_query($conn,"SELECT * from pshipping where sid='$id' && po=2") or die(mysqli_error($conn)); 

 $snum = mysqli_num_rows($data4);

?>

Transport Details  <select name="tr" id="tr" class="form-control">
<option value="n">No</option>
<option value="y" <?php if ($snum>0) echo 'selected="selected"';?>>Yes</option>

</select>
</div>
<div class="trdiv <?php echo $info3000['formlayout_column'];?>" >
<table width="100%" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <th scope="col"><?php echo $info2000['transport_details_label']; ?> Number</th>
    <th scope="col"><?php echo $info2000['transport_details_label']; ?> Name</th>
    <th scope="col"><?php echo $info2000['transport_details_label']; ?> Quantity</th>
    <th scope="col"><?php echo $info2000['transport_details_label']; ?> Date</th>
    
  </tr>
<?php 
$i=1;

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
?>  
  <tr>
    <td>
   <input name="shipping_details[]" value="<?php echo $i;?>_" type="hidden" />
    <input name="<?php echo $i;?>_tr_num" type="text" class="form-control" id="tr_num" value="<?php echo $info4['num'];?>"/></td>
    <td><input name="<?php echo $i;?>_tr_name" type="text" class="form-control" id="tr_name" value="<?php echo $info4['name'];?>"/></td>
    <td><input name="<?php echo $i;?>_tr_qty" type="text" class="form-control" id="tr_qty" value="<?php echo $info4['qty'];?>"/> </td>
    <td><input name="<?php echo $i; $i++;?>_tr_date" type="date" class="form-control" id="tr_date" value="<?php $odatetime=date('Y-m-d', strtotime($info4['datetime']));
 echo $odatetime;?>"/></td>
      </tr>
 
<?php } 

for ($i=$i;$i<13;$i++)
{

?>
<tr>
    <td>
   <input name="shipping_details[]" value="<?php echo $i;?>_" type="hidden" />
    <input name="<?php echo $i;?>_tr_num" type="text" class="form-control" id="tr_num"/></td>
    <td><input name="<?php echo $i;?>_tr_name" type="text" class="form-control" id="tr_name"/></td>
    <td><input name="<?php echo $i;?>_tr_qty" type="text" class="form-control" id="tr_qty"/> </td>
    <td><input name="<?php echo $i;?>_tr_date" type="date" class="form-control" id="tr_date"/></td>
      </tr>
<?php }
?>
</table>
</div>
 <!-- </div> -->



                     
                       <!--Own Text End -->
                <!-- </div>
            </div>
        </div> -->
        
        <!-- <div class="col-12 col-lg-3">
            <div class="card card-height-100 h-100">
                <div class="card-body"> -->
                       <!--Own Text -->
  
  

           
  
  
<?php if($info2000['rice_discount']==1) { ?>
<?php
$count = mysqli_get_var("SELECT COUNT(id) FROM rice_discount WHERE purchase_side=1  && inventory=1  $climit_ricediscount AND pi = 1 ");
if($count > 0){ 
?>
<div class="discount-grid">
    <div class="row g-3">
<?php $data4 = mysqli_query($conn,"SELECT * from rice_discount where   1=1  $climit_ricediscount  && inventory=1   && `purchase_side`=1 AND pi = 1 order by  code ") or die(mysqli_error($conn));
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 

if($info4000['en_nooriinternational']==1) {
   $toggleclass = mysqli_get_var("Select toggleclass from rice_purchase_discount where type_id='".$info4['id']."' && sid='$id' && page=3 ");
  }

   ?>
        <div class="col-3">
            <div class="discount-item drice  <?php echo $info4['specialclass']; ?>">
                <div class="mb-2" <?php  if($info4000['en_nooriinternational']==0) {  echo 'style="display:none;"' ; }  ?>>
                    <select name="addclass[]" class="form-control addclass" id="addclass">
    <?php 
           if($toggleclass==1){
              echo '<option value="0">No</option>';
           echo '<option value="1" selected>Yes</option> ';  

           }
           else{
            echo '<option value="0" selected>No</option>';
           echo '<option value="1" >Yes</option> ';  
           }
     ?>
    
   </select>
                </div>
                <label class="form-label"><?php echo $info4['label']; ?></label>
                <input  type="hidden" value="<?php echo $type_id =  $info4['id']; ?>" class="rice_discount" name="rice_discount[]"  /> 
                <input type="hidden" value="<?php echo $info4['less']; ?>" class="rice_type" name="rice_type[]"  />  
                <input type="hidden" value="<?php echo $info4['amount_type']; ?>" name="rice_percent[]"  class="rice_percent" />
        
        <input type="hidden" value="<?php echo $info4['specialclass']; ?>" class="specialclass" name="specialclass[]"  />
       <input type="hidden" value="<?php echo $info4['specialclass2']; ?>" class="specialclass2" name="specialclass2[]"  /> 
        
     <input type="hidden" value="<?php echo $info4['coa_id']; ?>" class="coa_id" name="coa_id[]"  />
     
                <input value="<?php $less = mysqli_get_var("Select amount from rice_purchase_discount where type_id='$type_id' && sid='$id' && page=3  ");  echo $less;  ?>" name="rice_discount_value[]"  type="number" step="0.0001" class="form-control rice_discount_value"   required/>
            </div>
        </div>
  <?php } ?>
    </div>
</div>
  <?php } ?>
<br>

<?php } ?>  
  
<div <?php if(1==1) { echo ' style="display:none;"'; } ?> >  
 Inventory Execution <select name="inventory_execution"  class="form-control">
<option value="1" selected >Yes</option>
<option value="0" <?php if ($info5['inventory_execution']==0) echo 'selected="selected"';?> >No</option>
</select> <br>
  </div>
                  

<input name="paid_amount" type="hidden"  id="paid_amount"  value="0"/> 

<input type="hidden" name="old_paid" value="<?php echo $info5['total_amount']-$info5['pending_amount'];?>" />
<input type="hidden" name="old_a" value="<?php echo $info5['total_amount']?>" />
<input type="hidden" name="old_tax" value="<?php echo $info5['tax_applied']?>" />
<br />

      
               <!--Own Text End -->
                <!-- </div>
            </div>
        </div>
        
   
    <div class="col-12 col-lg-3">
        <div class="card card-height-100 h-100">
            <div class="card-body"> -->
                       <!--Own Text -->
      
<?php if($info3000['en_carton_display']==1){
?>
<div class="<?php echo $info3000['formlayout_column'];?>">
<?php echo $info3000['purchase_total_ctn_label']; ?>  
 <input type="text" name="total_carton" id="packing" value="<?php echo floor($totc); ?>" readonly class="form-control"><br>                               
</div>
<?php } ?>

  
                      
  <div class="<?php echo $info3000['formlayout_column'];?>">
<?php echo $info3000['purchase_total_pcs_label'] ?>  <input name="total_pcs" type="text" id="total_pcs" value="<?php echo floor($totp); ?>" readonly class="form-control">
</div>
  <div class="<?php echo $info3000['formlayout_column'];?>">
Total # of Items <input name="total_items_count" type="text" id="total_items_count" value="0" readonly class="form-control">
</div>

<?php if($info3000['display_cost_purchase'] == '1'){ ?> 
<div class="<?php echo $info3000['formlayout_column'];?>">
Total Landed Cost
<input type="number" step="0.01" name="total_landed_cost" id="total_landed_cost" class="form-control" value="0" readonly  required />
</div>
<div class="<?php echo $info3000['formlayout_column'];?>">
Landed Cost Excluding S.Tax
<input type="number" step="0.01" name="landed_cost_without_stax" id="landed_cost_without_stax" class="form-control" value="0" readonly  required />
</div>
<?php } ?>
<div class="<?php echo $info3000['formlayout_column'];?>">
  <?php echo $info1000['product_label']; ?> Subtotal <input name="sub_total" type="text" class="total-box form-control" id="sub_total" value="<?php echo $tots; ?>" readonly>
</div>
<!-- <br>  -->

<input   class="form-control"   type="hidden" id="grossamount" />  

<div class="<?php echo $info3000['formlayout_column'];?>">
<!--Hamza-->
Cost Per Piece <input type="text" name="total_cost_peice" id="total_cost_peice" class="form-control" value="0" readonly>
</div>
<!--Hamza end-->

<div class="<?php echo $info3000['formlayout_column'];?>" style=" <?php  if($info1000['en_recurringinvoices']==0) { echo "display:none;"; } ?>">
Recurring <table width="100%" border="0" cellspacing="5" cellpadding="5">
  <tr>
    <td width="30%"><input name="recurring_qty" value="<?php echo $info5['recurring_qty']; ?>"   type="text" class="form-control"  placeholder="Value.." /></td>
    <td><?php $data4 = mysqli_query($conn,"SELECT * from recurring_type ") or die(mysqli_error($conn)); 

echo "<select name='recurring_type' id='combobox'  class='teacher form-control'   >";

echo "<option value='0' >None</option>";

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
  if($info5['recurring_type']==$info4['id'])
 {echo "<option value='".$info4['id']."' selected='selected' >".$info4['name']."</option>";
     }
   else {
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}
 }

echo "</select>";

?></td>
  </tr>
</table>

</div>


      
               <!--Own Text End -->
                <!-- </div>
            </div>
        </div>
   
          
          
    <div class="col-12 col-lg-3">
        <div class="card card-height-100 h-100">
            <div class="card-body"> -->
                       <!--Own Text -->
                  





<div class="<?php echo $info3000['formlayout_column'];?>">
Pending Amount <input name="pending_amount" type="text" class="form-control" id="pending_amount" value="<?php echo $pending; ?>" readonly/> 
</div>


<?php 

$vid=$info5['vendor_id'];

?>
<div class="<?php echo $info3000['formlayout_column'];?>">
<div id="oldr">Old Payable <input name="old" type="text" class="form-control"  id="old" readonly value="<?php echo vendoroldpayable($vid); ?>"/> 
</div></div>   


<div class="taxexcludingdisplay <?php echo $info3000['formlayout_column'];?>">
Amount Excluding Tax <input name="invoice_excludingtax" type="text" class="form-control" id="invoice_excludingtax" value="0" readonly/> 
</div>


<div class="<?php echo $info3000['formlayout_column'];?>">              
Invoice Tax <input name="invoice_tax" type="text" class="form-control" id="invoice_tax" value="0" readonly/> 


</div>


      <?php  if($info3000['en_goodluck']==1){?>

<div class="<?php echo $info3000['formlayout_column'];?>">Total SLC Amount <input name="total_slc" type="text" class="form-control"  id="total_slc" readonly/> 
</div>

<div class="<?php echo $info3000['formlayout_column'];?>" >Total SLC Amount Price Difference <input name="total_slc_price" type="text" class="form-control"  id="total_slc_price" readonly/> 
<br /></div>

<div class="<?php echo $info3000['formlayout_column'];?>">Total SLC Amount Difference Amount
 <input name="total_slc_amount" type="text" class="form-control"  id="total_slc_amount" readonly/> 
<br /></div>


  <?php  } ?>
                       
                       <!--Own Text End -->
                <!-- </div> -->
            <!-- </div> -->
        </div>
    <!-- </div>
</div> -->

<div style="clear:both;">
        <input type="hidden" name="shipping_value" value="<?php echo $info5['shipping']; ?>" />
<h3>Total</h3></div> <input name="total" id="total"  type="text" class="form-control" id="total" value="<?php echo $info5['total_amount'];?>" readonly required/> 
<br /><br />

<?php  if(isset($_GET['verify'])) { ?> 
<input name="submit" type="submit" id="submit" accesskey="T"  value="Verify" class="btn btn-success"  /> 
<?php } ?>

<div class="d-flex gap-2 mt-3">
    <!-- Submit Button -->
    <input 
        name="submit" 
        type="submit" 
        id="submit" 
        accesskey="T"
        class="btn btn-info"
        value="Update <?php echo ((isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_invoice_label'] : 'Purchase Invoice'); ?>"
    />

    <!-- Cancel Button -->
    <button 
        type="button" 
        id="Reset" 
        class="btn btn-danger"
        onclick="window.history.back();"
    >
        Cancel
    </button>
</div>


                
  
 
 
       
 <?php } } ?>
  
  </div>
<br />
 <br />
            
 <br />
<br />







                       
                       <!--Own Text End -->
                    </div>
                </section>
            </div>
        </div>
        <!-- page end-->
       </div></div></div>
    <!--main content end-->
    
    </form>
<?php bms_render_hidden_required_guard_script('#slip'); ?>

    
<?php include('../layout/sidebar2.php'); ?>




<script type="text/javascript">
  $(document).ready(function(){


<?php  if($info4000['en_nooriinternational']==1) { ?>

$(".addclass").change(function(){
 
var value=$(this).val();
// console.log(value);
// alert(value);

 var closestRow = $(this).closest("tr");

   // Check if the condition is met (e.g., value is equal to 1)
      // Replace this with your actual condition
       
        if (value == 1) {
         
            closestRow.addClass("trade_no_impact");
            
            closestRow.find('.specialclass').val('trade_no_impact');
       //  $('.income_count').trigger("change");
         $(".rice_discount_value, #sub_total, #paid_amount, #order_cost, #shipping, #discount").trigger("change");
             // Replace "highlight" with your desired class name
        } else {

            closestRow.removeClass("trade_no_impact"); 
            closestRow.find('.specialclass').val('');
        
 $(".rice_discount_value, #sub_total, #paid_amount, #order_cost, #shipping, #discount").trigger("change");
        
        }

});


  $(".addclass").trigger("change");

<?php } ?>






    $(document).on('change', '.ricefield_image', function(){
  var idd = this.id;
  
  var name = document.getElementById(idd).files[0].name;
  var form_data = new FormData();
  var ext = name.split('.').pop().toLowerCase();
/*
  if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1) 
  {
   alert("Invalid Image File");
  }else
  */{
  var oFReader = new FileReader();
  oFReader.readAsDataURL(document.getElementById(idd).files[0]);
  var f = document.getElementById(idd).files[0];
  var fsize = f.size||f.fileSize;
  if(fsize > 2000000)
  {
   alert("Image File Size is very big");
  }
  else
  {
    var company = $( "#company_idd option:selected" ).val();
  
  var a=this.id;
  
  var namee = $("#" + a).attr("name");
 
  
  var setupval= $("#" + a).val();
 
   form_data.append("ddd",a);
  
  form_data.append("file", document.getElementById(idd).files[0]);
   $.ajax({
    url:"../ajax/ricefield_image.php",
    method:"POST",
   
    data:form_data,

         
    contentType: false,
    cache: false,
    processData: false,
    beforeSend:function(){
     $('.' +idd).html("<label class='text-success'>Image Uploading...</label>");
    },   
    success:function(data)
    {
     $('#settext_'+ idd).html(data);
    }
   });


   
  }}
}); });</script>
<script type="text/javascript">
$(function() {
    
    
   
   <?php if ($snum<=0) {?> 
    $('.trdiv').hide(); 
   <?php } ?>
   
    $('#tr').change(function(){
        if($('#tr').val() == 'y') {
            $('.trdiv').show(); 
        } else {
            $('.trdiv').hide(); 
        } 
    });
});
</script>


<script type="text/javascript">
       $(document).ready(function () {
        
            $(document).on('change', '#service_invoice', function () { 
        
        
        var cid = $("#service_invoice").val();


$.ajax
({
type: "POST",
url: "../ajax/serial-query.php",

data: { ptotax : cid },
cache: false,
dataType : 'html',
success: function(html)
{
$(".invoicetax").html(html);
$("#discount").trigger("change");
}
});


$.ajax
({
type: "POST",
url: "../ajax/serial-query.php",

data: { is_onrecord : cid },
cache: false,
dataType : 'html',
success: function(html)
{

        if (html == 1) {
            // Use jQuery to set the 'checked' property to true
            $("#on_record").prop("checked", true);
        }

}
});
 
 
      
    
       }); 
        
        
<?php if($info3000['en_rice_bag_deduction'] == 1){ ?>       
    var weightage = $('.weightage').val();
    var customfield1 = $('.customfield1').val();
    var bag_weight = $('.bag_weight').val();
    var bag_rate = $('.bag_rate').val();
    var average_bag_deduction = (weightage-bag_weight)/customfield1;
    average_bag_deduction = (average_bag_deduction).toFixed(2);
    $('#weight_of_bag').val(average_bag_deduction);
    var rate = $('.unitcos').val();
    var packing2 = $('.packing2').val();

    var total_bag_deduction = ((customfield1*(bag_weight/1000))*(rate/packing2)).toFixed(2);
    $(".bag_deduction").find(".rice_discount_value").val(total_bag_deduction);
    $(".bag_addition").find(".rice_discount_value").val(customfield1*bag_rate);
<?php } ?>
    
    var sauda_filling_id = $('#sauda_filling_id').val();
    if(sauda_filling_id != "" && sauda_filling_id != 0){
        var total_freight_value = $('#total_freight_value').val();
        $('.poonch_freight').find(".rice_discount_value").val(total_freight_value);
    }       
        
$(document).on("change", "#currency", function(e){

        
        
        var empid = $("#currency").val();


$.ajax
({
type: "POST",
url: "../ajax/receipt-query2.php",

data: { currencyrate : empid },
cache: false,
dataType : 'html',
success: function(html)
{
$(".currencyfilter").html(html);

}
});
 
      
    
       });
    
        
        
<?php if(!$po_qtyimpact) { ?>
            $('#product_search').focus();

// Basit
<?php if($info3000['en_hapaperhub'] == 1){ ?>
$(document).on('change', '.mycf', function(e) 
{
    var row = $(this).closest(".carttr");
    var id = this.id.replace('customfield', '');
    var customfield1new = $(this).val() || "";
    
    if (customfield1new) 
    {
        var values = customfield1new.toString().replace(/\s/g, '').split(',');
        var sum = 0;
        
        for (var i = 0; i < values.length; i++) 
        {
            var num = parseFloat(values[i]) || 0;
            sum += num;
        }
        
        row.find("#ctn" + id)
            .val(sum)
            .trigger('change');
        
        // console.log("Sum calculated:", sum);
    }
});
<?php } ?>

        <?php if($info2000['noduplicate_item'] == 1){ ?>
        let serial_values = [];
       $(document).ready(function(){
            $('#acart [name="products[]"]').each(function() {
                const val = $(this).val();
                if (val) {
                    serial_values.push(val);
                }
            });
       });
       <?php } ?>
           $(document).on('change', '#product_search', function () { 
        
        
        var empid = $(this).val();
        var cid = $("#vendor").val(); 

        <?php if($info2000['noduplicate_item'] == 1){ ?>
        let check_val = empid;
        
         if (serial_values.includes(check_val)) {
            $("#product_search").val("").trigger('change.select2');
            alert('Product already exists!');
            return;
        } else 
            serial_values.push(check_val);
        <?php } ?>
$.ajax
({
type: "POST",
url: "../ajax/receipt-query.php",

data: { pid : empid , vendorid : cid, invoice : 1 },
cache: false,
dataType : 'html',
success: function(html)
{
$("#psearch").html(html);
$('#product_search').val('').trigger('change.select2');
$('.searchp:first').focus();

}
});

 
      // Hamza
       $("input[name='currency_rate']").trigger('change');
       //Hamza end
    
       });
<?php } ?>
       
    
$('.cid').change(function () { 
        
        
        var cid = $(".cid").val();


$.ajax
({
type: "POST",
url: "../ajax/receipt-query.php",

data: { ppid : cid },
cache: false,
dataType : 'html',
success: function(html)
{
$("#oldr").html(html);

}
});
 
      
    
       });

       

$('#number').change(function () { 
        
        
        var cid = $("#number").val();


$.ajax
({
type: "POST",
url: "../ajax/serial-query.php",

data: { sp : cid },
cache: false,
dataType : 'html',
success: function(html)
{
$("#serial").html(html);

}
});
 
      
    
       });

       

       
       

 }); 
 
 
 
     
    </script>
<!--Hamza-->
<script>
    $(document).on('change','#currency',function(){
        let select_text  = $(this).find('option:selected').text(); 
        $("input[name='currency_rate']").val(1);
        $("input[name='currency_rate']").trigger('change');
    });
    
    $(document).on('change', "input[name='currency_rate']", function () {
        let currency_rate = $(this).val() || 0;
        $("#acart tbody tr.carttr").each(function () {
            let total_usd = $(this).find("input[name='products_total[]']").val() || 0;
            let total = total_usd * currency_rate;
            $(this).find(".total_currency").val(total);
        });
        $('.income_count').trigger('change');
    });
    $(document).on('change','.rice_discount_value',function(){
         $("input[name='currency_rate']").trigger('change');
    });
    $(document).ready(function () {
      if ($("#result90").length > 0) {
            $("#result90").css("display", "none");
        }
    });
</script>

<!--Hamza end-->
<script type="text/javascript">
 
 
  $(document).ready(function () {
      
      
      <?php if($info4000['itemmulti_unit']==1){ ?>
 
$(document).on("change", ".munit", function(e){

    var unit = $(this).val();
    var that = $(this);
    var prd_id = that.closest('tr').find('.prd_hidden').val();
    var packing = that.closest('tr').find('.packing_hidden').val();
    var new_rate = that.closest('tr').find('.new_rate').val();

    $.ajax
    ({
    type: "POST",
    url: "../ajax/receipt-query.php",

    data: { get_conversion_rate : unit, prd_id : prd_id },
    cache: false,
    dataType : 'JSON',
    success: function(response){
        var final_value = packing * response.a;
        var final_rate =  response.a;
        that.closest('tr').find('.con_rate').val(final_rate);
        that.closest('tr').find('.new_packing').val(final_rate);
        
        $(".income_count").trigger("change");
    }
    });
    
});
    


$(".munit").trigger("change");


<?php } ?> 
$(document).on('change  ', ".case2qty", function() {

// Test if the div element is empty


  var dd =  $(this).find(":selected").val();


var a=this.id;
a = a.replace(/\D/g, '');


<?php   if($info4000['en_engineering']==1){

?>


if(dd=='2'){
//perkg
//perkg

//kg
$('#customfield'+ a).attr('readonly', true);
$('#customfield'+ a).val(0);



}
else if(dd=='3'){
//perkg
//perkg
//kgcon
console.log('saqib');
console.log(a);
$('#customfield'+ a).attr('readonly', false);
//list rate


}


<?php }?>


});


     $('.save').hide();
 $('.edit-input').attr("readonly", true);
 
 $(document).on('click', ".edit", function(){
    $('.edit').hide();
    $('.save').show();
    
    $(this).closest('tr').find('.edit-input').attr("readonly", false);
});

$(document).on('click', ".save", function(){
    $('.save').hide();
    $('.edit').show();
    
    $(this).closest('tr').find('.edit-input').attr("readonly", true);   
    // Hamza
       $("input[name='currency_rate']").trigger('change');
      //Hamza end
});
  
      
      
           $('.delete').on('click',function() {
    
    
  $(this).closest( 'tr').remove();
 


//Total Quantity Sum  (Pcs)
    var sum = 0;
    $(".total_pcs").each(function(){
        sum += +$(this).val();
    });
    $("#total_pcs").val(sum);


//Total Quantity Sum  (Carton)
    var sum3 = 0;
    $(".packing").each(function(){
        sum3 += +$(this).val();
    });
    $("#packing").val(sum3);



//Total Amount Sum  (Sub Total)
    var sum2 = 0;
    $(".sub_total").each(function(){
        sum2 += +$(this).val();
    });
    //sum2 = Math.round(sum2);
    var decimal_point = "<?php echo $info2000['total_decimal']; ?>";
    sum2 = sum2.toFixed(decimal_point);
    $("#sub_total").val(sum2);


  var n4 = $("#sub_total").val();
      
   var n5 = $("#paid_amount").val();
    var n6 = $("#pending_amount").val();
    
  var n7 = $("#shipping").val();
      var n8 = $("#discount").val();
    
     
     var result = +n4;
    
    <?php if ( $info1000['en_discount']==1) { ?>
 
    n8=(+n8*1)/100;
n8=(n8*1)*result;
    result=+result - n8;
<?php } ?>
  
  
   <?php if($info2000['rice_discount']==1) { 
    if($info3000['en_micado']==1){ ?>

        var currencyRate = parseFloat($("input[name='currency_rate']").val()) || 1;
  var subTotal = parseFloat($("#sub_total").val()) || 0;

  var bankDocsVal = subTotal * currencyRate;

  $(".rice_discount_value").each(function () {
    var special2 = $(this).closest("tr").find(".specialclass2").val();
    if (special2 === "bank_documents") {
      $(this).val(bankDocsVal.toFixed(2));
    }
  });

  var expenseClasses = [
    "opening_exp",
    "others",
    "shipping_charges",
    "warehouse_charges",
    "duty",
    "income_tax",
    "eto",
    "wharfage",
    "freight_forward",
    "clearing_exp",
    "stax"
  ];

  var expenseSum = 0;
  $(".rice_discount_value").each(function () {
    var special2 = $(this).closest("tr").find(".specialclass2").val();
    if (expenseClasses.includes(special2)) {
      var val = parseFloat($(this).val()) || 0;
      expenseSum += val;
    }
  });

  var totalLandedCost = bankDocsVal + expenseSum;
  $("#total_landed_cost").val(totalLandedCost.toFixed(2));

  var lessStaxVal = 0;
  $(".rice_discount_value").each(function () {
    var special2 = $(this).closest("tr").find(".specialclass2").val();
    if (special2 === "less_stax") {
      lessStaxVal = parseFloat($(this).val()) || 0;
    }
  });

  var landedCostWithoutStax = totalLandedCost - lessStaxVal;
  $("#landed_cost_without_stax").val(landedCostWithoutStax.toFixed(2));
    console.log("Hello");

    <?php } else { ?>

      $(".drice").each(function(){
          
          
      var damount = $(this).find('.rice_discount_value').val();
      var dless = $(this).find('.rice_type').val();
      var dpercent = $(this).find('.rice_percent').val();
      var specialclass = $(this).find('.specialclass').val();
      var specialclass2 = $(this).find('.specialclass2').val();    var pack22 = $('#packing').val(); 
    
      var broker_id = $('#broker_id').val(); 
        
     var customfield1 = $('.customfield1').val(); 
     var sub_total = $('.sub_total').val(); 
     
    
    
    if(broker_id!='0' ) {  
      
     
    
 if(specialclass=='noimpact' || specialclass=='trade_no_impact' || specialclass=='freight_class'  ) {
         
     }
    else if(specialclass!='brokery_rs' && specialclass!='brokery_percentage' ) { 
      
            if(dless==1) {
                if(dpercent==1) {
                    damount = (+100- +damount)/100;
                    result=+result*damount;
                } else if(dpercent==0) {
                    result=+result- +damount;   
                } else if(dpercent==3) {
                    var unitcos  = 0;
                    $(".unitcos").each(function(){
                        unitcos += +$(this).val();
                    });
                    var packing2 = 0;
                    $(".packing2").each(function(){
                        packing2 += +$(this).val();
                    });
                    var damount2 = (damount*unitcos)/packing2;
                    result=+result- +damount2;
                    // result=+result- +damount;    
                } 
                else if(dpercent==2) {
                    var total_bags = 0;
                    $(".customfield1").each(function(){
                        total_bags += +$(this).val();
                    });
                    var damount2 = total_bags*damount;
                    result=+result- +damount2;
                }  
                else if(dpercent==4){
                    var no_of_trucks = $('#no_of_trucks').val();
                    var damount2 = no_of_trucks*damount;
                    result=+result- +damount2;
                }
            } 
            else if(dless==0) {
                if(dpercent==1) {
                    damount = (+100+ +damount)/100;
                    result=+result*damount;
                } else if(dpercent==0) {
                    result=+result+ +damount;   
                } else if(dpercent==3) {
                    var unitcos  = 0;
                    $(".unitcos").each(function(){
                        unitcos += +$(this).val();
                    });
                    var packing2 = 0;
                    $(".packing2").each(function(){
                        packing2 += +$(this).val();
                    });
                    var damount2 = (damount*unitcos)/packing2;
                    result=+result+ +damount2;
                    // result=+result- +damount;    
                } else if(dpercent==2) {
                    var total_bags = 0;
                    $(".customfield1").each(function(){
                        total_bags += +$(this).val();
                    });
                    var damount2 = total_bags*damount;
                    result=+result+ +damount2;
                }
                else if(dpercent==4){
                    var no_of_trucks = $('#no_of_trucks').val();
                    var damount2 = no_of_trucks*damount;
                    result=+result+ +damount2;
                }   
            }
        }
    } else if( broker_id=='0' ) { 
    
 if(specialclass=='noimpact' || specialclass=='trade_no_impact' || specialclass=='freight_class'  ) {
         
     }
    else if(specialclass=='brokery_rs') {
            damount = damount*customfield1;
            if(dless==1) {
                result=+result- +damount;   
            } else if(dless==0) {
                result=+result+ +damount;
            }
        }
        else if(specialclass=='brokery_percentage') {
            damount = (damount/100)*sub_total;
            if(dless==1) {
                result=+result- +damount;   
            } else if(dless==0) {
                result=+result+ +damount;   
            }
        } else {
            if(dless==1) {
                if(dpercent==1) {
                    damount = (+100- +damount)/100;
                    result=+result*damount;
                } else if(dpercent==0) {
                    result=+result- +damount;   
                }  else if(dpercent==3) {
                    var unitcos  = 0;
                    $(".unitcos").each(function(){
                        unitcos += +$(this).val();
                    });
                    var packing2 = 0;
                    $(".packing2").each(function(){
                        packing2 += +$(this).val();
                    });
                    var damount2 = (damount*unitcos)/packing2;
                    result=+result- +damount2;  
                } else if(dpercent==2) {
                    var total_bags = 0;
                    $(".customfield1").each(function(){
                        total_bags += +$(this).val();
                    });
                    var damount2 = total_bags*damount;
                    result=+result- +damount2;
                }
                else if(dpercent==4){
                    var no_of_trucks = $('#no_of_trucks').val();
                    var damount2 = no_of_trucks*damount;
                    result=+result- +damount2;
                } 
            } else if(dless==0) {
                if(dpercent==1) {
                    damount = (+100+ +damount)/100;
                    result=+result*damount;
                } else if(dpercent==0) {
                    result=+result+ +damount;   
                } else if(dpercent==3) {
                    var unitcos  = 0;
                    $(".unitcos").each(function(){
                        unitcos += +$(this).val();
                    });
                    var packing2 = 0;
                    $(".packing2").each(function(){
                        packing2 += +$(this).val();
                    });
                    var damount2 = (damount*unitcos)/packing2;
                    result=+result+ +damount2;
                    // result=+result- +damount;    
                } else if(dpercent==2) {
                    var total_bags = 0;
                    $(".customfield1").each(function(){
                        total_bags += +$(this).val();
                    });
                    var damount2 = total_bags*damount;
                    result=+result+ +damount2;
                }
                else if(dpercent==4){
                    var no_of_trucks = $('#no_of_trucks').val();
                    var damount2 = no_of_trucks*damount;
                    result=+result+ +damount2;
                }
            }
        }
    }
        
        
 
          
          
          });
    
<?php } } ?>
 
  
        var n10 = $("#tax").val();
   <?php if ($info1000['en_tax']==1) { ?>
     var percent=result/100;
     percent = percent * n10;
     result = +result+ +percent;
     <?php } ?>

    
    <?php if ($info1000['en_shipping']==1) { ?>
 var result = +result+ +n7; 
    <?php } ?>
    
    var decimal_point = "<?php echo $info2000['total_decimal']; ?>";
    result = result.toFixed(decimal_point);
    //result = Math.round(result);
     
   var pending = +result - n5;
   pending = pending.toFixed(decimal_point);
      $("#total").val(result);
      $(".total-display").val(result);
    $("#pending_amount").val(pending);

  
     });

 });  
   
    </script>    
    
    
    
     
<script type="text/javascript">
 
 <?php  if($info4000['en_engineering']==1){         ?>
$(document).on('change  ', ".case2qty", function() {
       var a=this.id;
a = a.replace(/\D/g, '');

            var dd= $(this).closest(".carttr").find("#ric" +a).find(":selected").val();
        if(dd=='2'){
            
               var listrate = $('#pp'+ a).val(); 
            $('#pipe'+ a).val(listrate); 

        }else if(dd=='3'){
            
             var kgqty=$(this).closest(".carttr").find("#customfield" + a).val();  
           var list_rate=$(this).closest(".carttr").find("#pp" + a).val();  
         
          var tottal = list_rate*kgqty;
      $(this).closest(".carttr").find(".ptotal").val(tottal); 
           var total = $('.ptotal'+ a).val(); 
            var pcss = $('#ctn'+ a).val(); 
            var piperate = pcss/total;
            console.log('---case----');
            $('#pipe'+ a).val(piperate); 
            console.log(piperate);
            
            
        }
        
    
    
    });
  <?php  } ?>
  
$(document).ready(function(){

$('.income_count').trigger('change');

  function updatePurchaseItemFoc($row) {
    var prdId = $row.find("input[name='products[]']").val();
    var $focInput = $row.find(".foc");
    var rowId = ($focInput.attr("id") || "").replace("pfoc", "");
    var qty = parseFloat($row.find("input[name='products_pcs[]']").val()) || 0;
    var focScheme = parseFloat($("#pfoc_scheme" + rowId).val()) || 0;
    var focValue = parseFloat($("#pfoc_value" + rowId).val()) || 0;
    var currentFoc = parseFloat($focInput.val()) || 0;
    var lastFocQty = parseFloat($row.data("purchaseFocQty"));

    if (!prdId || !rowId || !$focInput.length) {
      return;
    }

    if ($row.data("skipPurchaseFocTrigger") === 1) {
      $row.removeData("skipPurchaseFocTrigger");
      return;
    }

    if (qty <= 0 || focScheme <= 0 || focValue <= 0) {
      if ((!isNaN(lastFocQty) && lastFocQty !== qty) || (isNaN(lastFocQty) && currentFoc !== 0)) {
        $focInput.val(0);
        $row.data("skipPurchaseFocTrigger", 1);
        $row.find(".income_count:first").trigger("change");
      }
      $row.data("purchaseFocQty", qty);
      return;
    }

    if ($row.data("focLoading") === 1 && $row.data("focQty") === qty) {
      return;
    }

    if (!isNaN(lastFocQty) && lastFocQty === qty) {
      return;
    }

    $row.data("focLoading", 1);
    $row.data("focQty", qty);

    $.ajax({
      type: "POST",
      url: "../ajax/ajax-as.php",
      data: { direct_itemfoc: prdId, area_val: qty },
      cache: false,
      dataType: "html",
      success: function(response) {
        var nextFoc = parseFloat($.trim(response) === "" ? 0 : $.trim(response)) || 0;
        if ((isNaN(lastFocQty) && currentFoc === 0 && nextFoc !== 0) || (!isNaN(lastFocQty) && currentFoc !== nextFoc)) {
          $focInput.val(nextFoc);
          $row.data("skipPurchaseFocTrigger", 1);
          $row.find(".income_count:first").trigger("change");
        }
        $row.data("purchaseFocQty", qty);
      },
      complete: function() {
        $row.data("focLoading", 0);
      }
    });
  }

  $("#acart tbody tr.carttr").each(function() {
    updatePurchaseItemFoc($(this));
  });

  $(window).on("load", function() {
    $("#acart tbody tr.carttr").each(function() {
      updatePurchaseItemFoc($(this));
    });
  });

  $(document).on("change focusout", ".searchp, .change, input[name='products_pcs[]']", function() {
    updatePurchaseItemFoc($(this).closest("tr.carttr"));
  });

  $(document).on("change input focusout", ".foc", function() {
    var $row = $(this).closest("tr.carttr");
    var qty = parseFloat($row.find("input[name='products_pcs[]']").val()) || 0;
    $row.data("purchaseFocQty", qty);
  });

  });
 
    </script>    

<?php  include('../functions/incomecount_function.php'); ?>

<script type="text/javascript">




$('#number').change(function () { 
        
        
        var cid = $("#number").val();


$.ajax
({
type: "POST",
url: "../ajax/serial-query.php",

data: { sp : cid },
cache: false,
dataType : 'html',
success: function(html)
{
$("#serial").html(html);

}
});
 
      
    
       });




 
 </script>            

<style >
body {
    overflow-x:hidden;}
</style>

<?php if($info3000['en_smartbatch']==1) { ?>
<div class="modal fade" id="smartBatchModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Batch Details</h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-8">
            <label>Item</label>
            <input type="text" id="smartbatch-item" class="form-control" readonly="readonly" />
          </div>
          <div class="col-md-4">
            <label>Total Qty</label>
            <input type="text" id="smartbatch-totalqty" class="form-control" readonly="readonly" />
          </div>
        </div>
        <div style="margin-top:15px;">
          <table class="table table-bordered" id="smartbatch-table">
            <thead>
              <tr>
                <th style="width:60px;">S#</th>
                <th>Batch</th>
                <th style="width:140px;">Qty</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
$(function() {
  function getRowItemText($row) {
    var text = $row.find('td').eq(0).text();
    return $.trim(text.replace(/\s+/g, ' '));
  }

  function parseSmartBatchData(raw) {
    if (!raw) {
      return [];
    }
    try {
      var data = JSON.parse(raw);
      if ($.isArray(data)) {
        return data;
      }
    } catch (e) {}
    return [];
  }

  function renderSmartBatchRows(entries) {
    var $tbody = $('#smartbatch-table tbody');
    $tbody.empty();
    if (!entries.length) {
      $tbody.append('<tr><td colspan="3" class="text-center">No batches found.</td></tr>');
      return;
    }
    $.each(entries, function(index, entry) {
      var batch = entry.batch || '';
      var qty = entry.qty || '';
      var rowHtml = '<tr>' +
        '<td>' + (index + 1) + '</td>' +
        '<td>' + batch + '</td>' +
        '<td>' + qty + '</td>' +
        '</tr>';
      $tbody.append(rowHtml);
    });
  }

  $(document).on('click', '.smartbatch-open', function() {
    var $row = $(this).closest('tr');
    var itemText = $(this).data('item') || getRowItemText($row);
    var totalQty = $row.find("input[name='products_pcs[]']").val() || '';
    var entries = parseSmartBatchData($row.find('.smartbatch-data').val());

    $('#smartbatch-item').val(itemText);
    $('#smartbatch-totalqty').val(totalQty);
    renderSmartBatchRows(entries);
    $('#smartBatchModal').modal('show');
  });
});
</script>
<?php } ?>



<?php include('../layout/footer.php'); ?>


<?php if($info2000['meditech_singleinvoice']==1) { ?>

 <script>   

           $('.grn_list').change(function () { 
        
        
    
var vid = ''; 
$('.grn_list:checkbox:checked').each(function(i, selected){ 
  vid = vid + $(selected).val() + ', '; 
});

vid = vid.replace(/,\s*$/, "");


$.ajax
({
type: "POST",
url: "../ajax/receipt-query2.php",

data: { grn_list : vid  },
cache: false,
dataType : 'html',
success: function(html)
{
$(".cartcustom-overlay").html(html);

$('.income_count:last').trigger('change');
}
});
 
          
    
       });
       
    //    $('.grn_list').trigger('change'); 
       
</script>

<?php } ?>



<script type="text/javascript" >


    $(document).ready(function(){
    var useAjaxProductSearchEditPi = <?php echo ($use_ajax_search==1 ? 'true' : 'false'); ?>;
    var editPiSearchMinChars = <?php echo (isset($info3000['search_cher']) && (int)$info3000['search_cher'] >= 0 && (int)$info3000['search_cher'] <= 5) ? (int)$info3000['search_cher'] : 0; ?>;

    function getEditPiProductSearchFilters() {
        return {
            cat: "a",
            subcat: "a",
            subsub: "a",
            brand: ($("#inv_brand").val() || "a")
        };
    }

    function initEditPiProductSearch() {
        if(!$.fn.select2){
            return;
        }
        var $select = $('#product_search');
        if(!$select.length){
            return;
        }
        var placeholderText = $select.find("option:first").text() || "Select a <?php echo $info1000['product_label']; ?>";
        if($select.hasClass("select2-hidden-accessible")){
            $select.select2("destroy");
        }
        if(useAjaxProductSearchEditPi){
            $select.empty().append(new Option(placeholderText, ""));
            $select.select2({
                width: "100%",
                minimumInputLength: editPiSearchMinChars,
                placeholder: placeholderText,
                allowClear: true,
                ajax: {
                    url: "../ajax/serial-query.php",
                    type: "POST",
                    dataType: "json",
                    delay: 250,
                    data: function(params){
                        var filters = getEditPiProductSearchFilters();
                        return {
                            purchase_product_search: 1,
                            term: params.term || "",
                            cat: filters.cat,
                            subcat: filters.subcat,
                            subsub: filters.subsub,
                            brand: filters.brand
                        };
                    },
                    processResults: function(data){
                        if (data && data.results) {
                            return data;
                        }
                        if ($.isArray(data)) {
                            return { results: data };
                        }
                        return { results: [] };
                    },
                    cache: true
                }
            });
        } else {
            $select.select2();
        }
    }

    initEditPiProductSearch();

    $(document).on('change', '#inv_brand', function(){
        var selectedBrand = $(this).val() || 'a';
        $('#brandfilter').val(selectedBrand);

        if($('#product_search').length){
            if(useAjaxProductSearchEditPi){
                initEditPiProductSearch();
                return;
            }
            $.ajax({
                type: "POST",
                url: "../ajax/serial-query.php",
                data: { inv_items_filter: 1, cat: "a", subcat: "a", subsub: "a", brand: selectedBrand },
                cache: false,
                dataType : 'html',
                success: function(html){
                    var $newSelect = $(html);
                    $('#product_search').replaceWith($newSelect);
                    initEditPiProductSearch();
                }
            });
        }
    });
    $('#brandfilter').val($('#inv_brand').val() || 'a');
        

<?php  if($info2000['en_mastqalandar']==1)
{ ?>

    $('#penalty_amount, #moisture2').change(function () { 
        var penalty_amount = $('#penalty_amount').val();
        var customfield1 = 0;
        $('.customfield1').each(function(){
            customfield1 += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        var moisture2 = $('#moisture2').val();

        var weightage = 0
        $('.weightage').each(function(){
            weightage += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        }); 

        var claim_weight = 0;
        $('.pscheme5').each(function(){
            claim_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });

        var penalty_amount_total = penalty_amount * customfield1;
        /*var bag_packing_weight = $('#bag_packing_weight').val();
        if(moisture2 != ""){
            penalty_amount_total = (((weightage-claim_weight) - (customfield1 * moisture2))/bag_packing_weight)*penalty_amount;
            penalty_amount_total = Math.round(penalty_amount_total);
        }*/
        $('.bag_penalty_amount_deduction').find(".rice_discount_value").val(penalty_amount_total);
        $('.income_count').trigger('change');
    });
    $('#penalty_amount').trigger('change');
    
    $('#moisture, #moisture2').change(function () { 
    
        var cid = $("#moisture").val();
        var sub_total = $("#sub_total").val();
        var sauda_moisture_id = $('#sauda_moisture_id').val();

        var customfield1 = 0;
        $('.customfield1').each(function(){
            customfield1 += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });

        var weightage = 0
        $('.weightage').each(function(){
            weightage += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        var claim_weight = 0;
        $('.pscheme5').each(function(){
            claim_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });

        var bag_weight = 0;
        $('.bag_weight').each(function(){
            bag_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        weightage = weightage - claim_weight - bag_weight;
        <?php if($info3000['en_mft'] == 1 && ($sauda_filling_id == '' || $sauda_filling_id == 0)){ ?>
            weightage = $('#thadda_weight').val();
        <?php } ?> 

        var unitcos = 0;
        $('.unitcos').each(function(){
            unitcos += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });

        var packing2 = $('.packing2').val();
        if($('.moisture_deduction_bags').prop("checked") == true){
            var moisture_deduction_bags = 1;
        }else{
            var moisture_deduction_bags = 0;
        }
        var moisture2 = $('#moisture2').val();

        $.ajax({
            type: "POST",
            url: "../ajax/serial-query.php",
            data: { cmoisture : cid, sub_total : sub_total, total_weight : weightage, rate : unitcos, packing2 : packing2, sauda_moisture_id : sauda_moisture_id, moisture_deduction_bags : moisture_deduction_bags, total_bags :  customfield1, moisture2 : moisture2 },
            k8cache: false,
            dataType : 'JSON',
            success: function(response){
                $("."+response.class).find(".rice_discount_value").val(response.amount);
                // $(".cmoisture").find(".rice_discount_value").val(html);
                $('.income_count').trigger('change');
            }
        });
    });
    $('#moisture').trigger('change');

    <?php if($info3000['en_mft'] == 1){ ?>
        $(document).on('change', '#r_other_deduction', function(){
            var r_other_deduction = $('#r_other_deduction').val();
            var weightage = 0
            $('.weightage').each(function(){
                weightage += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
            });
            var claim_weight = 0;
            $('.pscheme5').each(function(){
                claim_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
            });
            weightage = weightage - claim_weight;
            var amt_total = (r_other_deduction*weightage);
            $('.other_deductions').find(".rice_discount_value").val(amt_total);
            $('.income_count').trigger('change');
        });
    <?php } else{ ?>
        $(document).on('change', '#r_other_deduction', function(){
            var r_other_deduction = $('#r_other_deduction').val();
            var bags = $('.customfield1').val();
            var rate = $('.unitcos').val();
            var packing2 = $('.packing2').val();
            var amt_total = (r_other_deduction*bags)*(rate/packing2);
            $('.other_deductions').find(".rice_discount_value").val(amt_total);
            $('.income_count').trigger('change');
        });
    <?php } ?>

    $('#r_other_deduction').trigger('change');

    <?php if($info3000['en_mft'] == 1){ ?>
        $(document).on('change', '#feild_worker_filling', function(){
            var filling = $('#feild_worker_filling').val();
            var sauda_filling_id = $('#sauda_filling_id').val();
            if(sauda_filling_id != 0 && sauda_filling_id != "")
                var amt_total = filling*10;
            else
                var amt_total = filling*10;
            
            $('.filling_deductions').find(".rice_discount_value").val(amt_total);
            $('.income_count').trigger('change');
        });
    <?php } else { ?>
        $(document).on('change', '#feild_worker_filling', function(){
            var filling = $('#feild_worker_filling').val();
            var amt_total = filling*10;
            $('.filling_deductions').find(".rice_discount_value").val(amt_total);
            $('.income_count').trigger('change');
        });
    <?php } ?>
    $('#feild_worker_filling').trigger('change');
    
    
    $('#broken, #broken2').change(function () {  
        var cid = $("#broken").val();
        var sauda_broken_id = $('#sauda_broken_id').val();

        var sum = 0;
        $('.total_pcs').each(function(){
            sum += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });

        var sum2 = 0;
        $('.pscheme5').each(function(){
            sum2 += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });

        var bag_weight = 0;
        $(".bag_weight").each(function(){
            bag_weight += +$(this).val();
        });

        var broken2 = $('#broken2').val();

        sum = sum - sum2 - bag_weight;
        <?php if($info3000['en_mft'] == 1 && ($sauda_filling_id == '' || $sauda_filling_id == 0)){ ?>
            sum = $('#thadda_weight').val();
        <?php } ?>

        $.ajax({
            type: "POST",
            url: "../ajax/serial-query.php",
            data: { cbroken : cid, sum2 : sum, sauda_broken_id : sauda_broken_id, broken2 : broken2 },
            k8cache: false,
            dataType : 'JSON',
            success: function(response){
                $("."+response.class).find(".rice_discount_value").val(response.amount);
                // $(".cbroken").find(".rice_discount_value").val(html);
                $('.income_count').trigger('change');
            }
        });
    });
    $('#broken').trigger('change');

    //work for chappal
    $('#chappal_brokery_rs, #chappal_brokery_weight').change(function () {
        var brokery_weight = $('#chappal_brokery_weight').val();
        var brokery_rs = $('#chappal_brokery_rs').val();
        if(brokery_rs != '' && brokery_weight != ''){
            var weightage = 0
            $('.weightage').each(function(){
                weightage += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
            });
            var claim_weight = 0;
            $('.pscheme5').each(function(){
                claim_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
            });
            var brokery_amount = ((weightage-claim_weight)/brokery_weight)*brokery_rs;
        }else{
            var brokery_amount = '';
        }
        $(".chappal_brokery_amount").find(".rice_discount_value").val(brokery_amount);
    });
    $('#chappal_brokery_rs').trigger('change');

    $('#chappal_weight_deduction').change(function () {
        var weight_deduction = $('#chappal_weight_deduction').val();
        if(weight_deduction != ""){
            var weightage = 0
            $('.weightage').each(function(){
                weightage += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
            });
            var claim_weight = (weight_deduction*weightage)/100;
            $('.pscheme5').val(claim_weight);
        }
    });
    $('#chappal_weight_deduction').trigger('change');
    //work for chappal end


    // pk work start
    $(document).on('change', '#chalky', function () { 
        var sauda_chalky_id = $('#sauda_chalky_id').val();
        var chalky = $('#chalky').val();
        var weightage = 0
        $('.weightage').each(function(){
            weightage += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        var claim_weight = 0;
        $('.pscheme5').each(function(){
            claim_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        var bag_weight = 0;
        $('.bag_weight').each(function(){
            bag_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        weightage = weightage - claim_weight - bag_weight;
        <?php if($info3000['en_mft'] == 1 && ($sauda_filling_id == '' || $sauda_filling_id == 0)){ ?>
            weightage = $('#thadda_weight').val();
        <?php } ?>
        // alert(sauda_chalky_id+" "+chalky)
        $.ajax({
            type: "POST",
            url: "../ajax/serial-query.php",
            data: { cchalky : chalky, sauda_chalky_id : sauda_chalky_id, weightage : weightage},
            cache: false,
            dataType : 'JSON',
            success: function(response){
                // console.log(response);
                $("."+response.class).find(".rice_discount_value").val(response.amount);
                $('.income_count').trigger('change');
            }
        });
    });

    $('#chalky').trigger('change');

    $(document).on('change', '#damage', function () { 
        var sauda_damage_id = $('#sauda_damage_id').val();
        var damage = $('#damage').val();
        var weightage = 0
        $('.weightage').each(function(){
            weightage += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        var claim_weight = 0;
        $('.pscheme5').each(function(){
            claim_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        var bag_weight = 0;
        $('.bag_weight').each(function(){
            bag_weight += parseFloat($(this).val());  // Or this.innerHTML, this.innerText
        });
        weightage = weightage - claim_weight - bag_weight;
        <?php if($info3000['en_mft'] == 1 && ($sauda_filling_id == '' || $sauda_filling_id == 0)){ ?>
            weightage = $('#thadda_weight').val();
        <?php } ?>
        $.ajax({
            type: "POST",
            url: "../ajax/serial-query.php",
            data: { cdamage : damage, sauda_damage_id : sauda_damage_id, weightage : weightage},
            cache: false,
            dataType : 'JSON',
            success: function(response){
                // console.log(response);
                $("."+response.class).find(".rice_discount_value").val(response.amount);
                $('.income_count').trigger('change');
            }
        });
    });
    $('#damage').trigger('change');

    $(document).on('change', '.pscheme5', function(){   
        $('#broken').trigger('change');
        $('#moisture').trigger('change');
    });
    // pk end
    
    
        
    
    
<?php   } ?>
        

<?php if($info3000['en_snd_purchase']==1){ ?>

$(document).on('focusout', '.searchp, .searchqty', function(){
    var that = $(this);
    var prd_id = that.closest('tr').find('.singleitem').val(); 
    var qty = that.closest('tr').find("#t"+prd_id).val();
    var dist_id = $("#dist_to_id").val(); 
	var brand_id = $("#inv_brand").val() || "a"; 
    // alert(qty+'   '+$("#product_search").val());
    console.log(qty);
    //  exit();
     // $(".reportselect").filter('.select2-hidden-accessible').select2("destroy"); 
     if(qty>0)
     {
          $.ajax({
            type: "POST",
            url: "../ajax/ajax-as.php",
            data: { qty_disc_litmus:1, qty:qty , dist_id,dist_id,brand_id:brand_id,prd_id:prd_id},
            cache: false,
            dataType : 'html',
            success: function(response){
                    that.closest('tr').find('[name="products_discount[]"]').val(response);
                    that.closest('tr').find('.income_count').trigger('change');
            }

       });


        $.ajax({
            type: "POST",
            url: "../ajax/ajax-as.php",
            data: { qty_scheme_litmus:1, qty:qty , dist_id,dist_id,brand_id:brand_id,prd_id:prd_id},
            cache: false,
            dataType : 'html',
            success: function(response){
                        that.closest('tr').find('[name="products_scheme[]"]').val(response);
                        that.closest('tr').find('.income_count').trigger('change');
            }

       });

        $.ajax({
            type: "POST",
            url: "../ajax/ajax-as.php",
            data: { qty_tax_litmus:1, qty:qty , dist_id,dist_id,brand_id:brand_id,prd_id:prd_id},
            cache: false,
            dataType : 'html',
            success: function(response){
                        that.closest('tr').find('[name="products_tax[]"]').val(response);
                        that.closest('tr').find('.income_count').trigger('change');
            }

       });


        $.ajax({
            type: "POST",
            url: "../ajax/ajax-as.php",
            data: { qty_rate_litmus:1, qty:qty , dist_id,dist_id,brand_id:brand_id,prd_id:prd_id},
            cache: false,
            dataType : 'html',
            success: function(response){
                that.closest('tr').find('[name="unitcos[]"]').val(response);
                that.closest('tr').find('.income_count').trigger('change');
            }
       });

     }

                

});



 

<?php } ?> 
        


    });


    <?php if($info2000['en_ricetrade']==1) { ?>

$(document).on("change", ".weight_type", function(e){

    
        var empid1 = $(this).val();
        
        if(empid1=='Truck Weight') {    
        var empid2 = $(".weight11").val();
        } else {
        var empid2 = $(".weight22").val();
}

$('.searchp').val(empid2);
 $('.income_count:first').trigger("change");

       });

<?php } ?>


$(document).ready(function() {
    $("#main-content").toggleClass("merge-left");
     $("#sidebar").toggleClass("hide-left-bar");
});

// pk work start
$(document).on('change', '.rrice_percentage', function(){
    var rrice_percentage = $(this).val();
    var total = $('.packing').val();
    var sales_brokery = total*(rrice_percentage/100);
    // $('.sales_brokery').val(sales_brokery);
    $(".purchase_brokery").find(".rice_discount_value").val(sales_brokery);
    $('.income_count').trigger('change');
})
//pk work end


<?php if($info3000['en_goodluck'] == 1){ ?>

$(document).on('change focusout ', '.income_count', function() {
var a=this.id;

    a = a.replace(/\D/g, '');
    var price= $(this).closest(".carttr").find("#pp" + a).val();
    var qty= $(this).closest(".carttr").find("#t" + a).val();
    //  var custom_field1= $(this).closest(".carttr").find(".custom_field1").val();
    var slc_price = $(this).closest(".carttr").find(".price_slc").val();

    if(slc_price=='') slc_price=0;
    
  var slc_amt2 = qty * price;
  
   var slc_amt = qty * slc_price;
  
  var slc_cal = 0;
  
  if(slc_amt2<slc_amt) slc_cal = slc_amt - slc_amt2;
  
     //  $(this).closest(".carttr").find(".price_slc").val(slc_price.toFixed(2));
        $(this).closest(".carttr").find(".slc_amt").val(slc_cal.toFixed(2));
    // console.log(custom_field1);


             var sum4 = 0;
     var ab = 0;
     var xyz = 0;
     var nn = 0;

  $(".price_slc").each(function(){
    
     ab = $(this).val();
     xyz = $(this).closest(".carttr").find(".packing").val();
     nn = parseFloat(ab) * parseFloat(xyz);
    
    sum4 = parseFloat(sum4) +parseFloat(nn);
    
  });

    $("#total_slc").val(sum4);


    var sum5 = 0;
    $(".price_slc").each(function(){
      sum5 += +$(this).val();
    });
    $("#total_slc_price").val(sum5);

        var sum6 = 0;
    $(".slc_amt").each(function(){
      sum6 += +$(this).val();
    });
    $("#total_slc_amount").val(sum6);


 // console.log(sum4 +" == "+sum5+"  == "+sum6);


});

$('.income_count').trigger('change');

<?php } ?>

</script><?php }  
}


else  header("location:../index.php");  ?>












