<?php include '../global-connect/global-connect.php';
include '../functions/inc.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']))
{
	
	

	
$vendor_id = test_input($_POST['vendor']);
$customer_id = test_input($_POST['vendor']);
$po_id = test_input($_POST['order_id']);
$allowed_pi_products = array();
if($po_qtyimpact && $po_id > 0) {
    $allowed_pi_products_result = mysqli_query($conn,"SELECT DISTINCT prd_id FROM po_details WHERE order_id='$po_id'") or die(mysqli_error($conn));
    while($allowed_pi_product = mysqli_fetch_array($allowed_pi_products_result)) {
        $allowed_pi_products[(string)$allowed_pi_product['prd_id']] = true;
    }
}
$bank = test_input($_POST['bank']);	
$notes = test_input($_POST['notes']);	
$inventory_execution = test_input($_POST['inventory_execution']);

$memo= $notes;


$on_record5 = $_POST['on_record5'];

if($on_record5!='') { 
$on_record= $on_record5; 


}

else {

 if(isset($_POST['on_record']))
 { $on_record = mysqli_get_var("Select max(on_record) from purchasing ");  $on_record = $on_record+1; }
 else { $on_record=0; }

}

$serial = test_input($_POST['number']);		
if($serial==NULL || $serial=='')
$serial="0";
else $serial = test_input($_POST['number']);

$dcdate = test_input($_POST['dcdate']);	


 if(isset($_POST['discount']))
$discount = test_input($_POST['discount']);	
 else $discount=0;
 if($discount == '')
 	$discount = 0;
 
 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;
 }
 
 
 $broken = test_input($_POST['broken']);	
$moisture = test_input($_POST['moisture']);	


$filesystem = test_input($_POST['filesystem']);
$filesystem2 = test_input($_POST['filesystem']);


	 
	 
if($filesystem2=='') { $filesystem2=0; }	 




if(isset($_POST['completepo']))
$completepo = test_input($_POST['completepo']);	
else $completepo=0;
if($info3000['en_importexpense_currency'] == 0){
	$pending_amount = $pending_amount * 1;
}else{
    $pending_amount = $pending_amount * $currency_rate;
}

// $pending_amount = test_input($_POST['currency_rate']*$_POST['pending_amount']);

$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']);
$total_amount = test_input($_POST['total_amount']);	


$month_id = mysqli_get_var("Select count(id) from purchasing WHERE MONTH(datetime)
 = MONTH('$date')");
 $month_id = $month_id+1;


$create_time=date("Y-m-d H:i:s");

$data3 = mysqli_query($conn,"SELECT *  FROM po where id='$po_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_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;
$dop = test_input($_POST['dop']);
$transporter_id = test_input($_POST['transporter_id']);
$party_id = $_POST['party_id'];
if($party_id == ''){
  $party_id = 0;
}

$kanta_weight = 0;
$factory_weight = 0;
$no_of_trucks = 0;
$distributor_to_id = 0;
$distributor_from_id = 0;


$currency = test_input($_POST['currency']);	
$currency_rate = test_input($_POST['currency_rate']);	
$currency_total = test_input($total_amount);

//Date 11/5/2025
if($info3000['en_importexpense_currency'] == 0){
	$total_amount = $total_amount * 1;
}else{
    $total_amount = $total_amount * $currency_rate;
}

$total = test_input($_POST['currency_rate']*$total_amount);


// $total_amount = $total;
// Date end

$daily_id = get_max_daily_id("purchasing" , $date, 0, $service_invoice, $current_company, $cost_center, $distributor_id);


$sales_id = $_POST['sales_id'];
if($sales_id == '')
    $sales_id = 19;


$vendor_id2 = $_POST['vendor_id2'];
if($vendor_id2=='') $vendor_id2=0;


$vendor_id3 = $_POST['vendor_id3'];
if($vendor_id3=='') $vendor_id3=0;



 $credit_account  = $_POST['credit_account'];
  $tax_account  = $_POST['tax_account'];  



$sql2 = "Insert into purchasing

(po_id, emp_id, datetime, pending_amount,vendor_id, vendor_id2, vendor_id3,total_amount,notes,on_record,serial, serial_date, discount, shipping_charges, tax_applied,  month_id, cost_center, inventory_execution, service_invoice,  currency, currency_rate, currency_total,  broken, moisture,  create_time, create_by, filesystem_id, broker_id, sauda_id, dod, delivery_condition, truck_type, payment_terms, delivery_terms, dop, recurring_type, recurring_date, recurring_qty, transporter_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)
VALUES ('$po_id','$loginuser','$date','$pending_amount','$vendor_id','$vendor_id2','$vendor_id3','$total_amount','$notes','$on_record', '$serial', '$dcdate' , '$discount' , '$shipping', '$atax',  '$month_id', '$cost_center', '$inventory_execution','$service_invoice','$currency', '$currency_rate', '$currency_total', '$broken', '$moisture', '$create_time','$loginuser','$filesystem2', '$broker_id', '$sauda_id', '$dod', '$delivery_condition', '$truck_type', '$payment_terms', '$delivery_terms', '$dop', '$recurring_type', '$recurring_date', '$recurring_qty','$transporter_id', '$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')" ;

$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));

 
	
$data2 = mysqli_query($conn,"SELECT MAX(id) AS id FROM purchasing") or die(mysqli_error($conn));
$info2 = mysqli_fetch_array( $data2 );
$id= $info2['id'];
$sid= $info2['id'];
 
	
$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)
VALUES ('$sid','$tr_num','$tr_name','$tr_qty','$tr_date')" ;

$retval25 = mysqli_query($conn, $sql25 );
}
	}
}

}	


$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['rice_discount'])) {
  for($i=0 ;$i < count($_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 = (int)$rice_charges + (int)$rice_charges_qty;
  }

  }
}

if (isset($_POST['products'])) {

if($info3000['costing_weight'] == 1){
	$total_pcs_amount = 0;
	$total_weight_ = 0;
}

$default_product_warehouse = (int)$current_warehouse;
if($default_product_warehouse <= 0) {
  $default_product_warehouse = (int)mysqli_get_var("SELECT id FROM inventory_warehouse WHERE 1=1 $wlimit_warehouse $climit_warehouse ORDER BY id ASC LIMIT 1");
}
if($default_product_warehouse < 0) {
  $default_product_warehouse = 0;
}

for($i=0 ;$i < count($_POST['products']); $i++) { 	 
		$p_ido = $_POST['products'][$i];
		if($po_qtyimpact && !isset($allowed_pi_products[(string)$p_ido])) {
			continue;
		}
		$prdgross = $prdgross + $_POST['products_total'][$i];	   
		if($info3000['costing_weight'] == 1){
  		$total_pcs_amount = $_POST['products_pcs'][$i];
			$result = mysqli_query($conn, "SELECT weight FROM inventory WHERE id = '$p_ido' LIMIT 1");
			$wei = 1;
			if ($result && mysqli_num_rows($result) > 0) {
			$row = mysqli_fetch_assoc($result);
				$wei = $row['weight'];
					if ($wei == 0) {
						$wei = 1;
					}
				}
				$total_weight_ = $total_weight_ +  ( $total_pcs_amount * $wei) ;
		
		}
  
  }

  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];
$custom_field1=$_POST['custom_field1'][$i];
$description=$_POST['products_description'][$i];
$total=$_POST['products_total'][$i];
$packing=$_POST['products_packing'][$i];
$discount=$_POST['products_discount'][$i];

$unitcos=$_POST['unitcos'][$i];

$pfoc = $_POST['products_foc'][$i];
if($pfoc == ''){ $pfoc = 0; }

$munit=$_POST['munit'][$i];
$con_rate=$_POST['con_rate'][$i];
$munit = ($munit) ? $munit : 0;
$con_rate = ($con_rate) ? $con_rate : 0;	



$packing2=$_POST['packing2'][$i];

$unitcos2=$total/$qty;

$pwarehouse = 0;
if(isset($_POST['products_warehouse'][$i])) {
  $pwarehouse = (int)$_POST['products_warehouse'][$i];
}
if($pwarehouse <= 0) {
  $pwarehouse = $default_product_warehouse;
}
	
	
for ($multi = 0; $multi < $qty; $multi++) { 


$is_batch = mysqli_get_var("Select is_batch from inventory where id='$c' ");

if($is_batch==1) {
  $sql = "Insert into multi_ibatch
(batch_code, item_id, qty, secondry_qty, purchase_id)
VALUES ('0','$c','1','0','$id')";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}

}	

	
	
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];


$mrp_price=$_POST['mrp_price'][$i]; 
  $tax_mrp=$_POST['tax_mrp'][$i];

if($mrp_price==""){
  $mrp_price=0;
}

if($tax_mrp==""){
  $tax_mrp=0;
}
  

$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];

$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($discount == '')
 	$discount = 0;
if($discount2 == '')
 	$discount2 = 0;
if($discount3 == '')
 	$discount3 = 0;
if($discount4 == '')
 	$discount4 = 0;


if($qty>0)
{

$price=$total/$qty;


if($smartbatch_enabled) {
  foreach($smart_batches as $sb_item) {
    if(!is_array($sb_item)) { continue; }
    $sb_batch_id = isset($sb_item['batch_id']) ? (int)$sb_item['batch_id'] : 0;
    $sb_qty = isset($sb_item['qty']) ? (float)$sb_item['qty'] : 0;
    if($sb_qty <= 0) { continue; }
    if($sb_batch_id > 0) {
      $sql = "UPDATE po_details SET qty_purchase = GREATEST(qty_purchase-'$sb_qty',0) WHERE order_id='$po_id' AND prd_id='$c' AND batch_id='$sb_batch_id'";
    } else {
      $sql = "UPDATE po_details SET qty_purchase = GREATEST(qty_purchase-'$sb_qty',0) WHERE order_id='$po_id' AND prd_id='$c' AND qty_purchase!=0";
    }
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  }
} else {
  $data2 = mysqli_query($conn,"SELECT qty_purchase FROM po_details where order_id='$po_id' AND prd_id='$c' AND qty_purchase!=0") or die(mysqli_error($conn));
  $info2 = mysqli_fetch_array( $data2 );
  $qtyp= $info2['qty_purchase'];
  $qtyl=$qtyp-$qty;

  if($qtyl<=0)
  $qtyl=0;

  $sql = "update po_details
  set qty_purchase='$qtyl' where order_id='$po_id' AND prd_id='$c' AND qty_purchase!=0";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}


if($info1000['en_grn']==0) {
if(!$po_qtyimpact && $inventory_execution==1) {

$c2 = mysqli_get_var("Select stock_effect from inventory WHERE id = '$c'");	
if($c2==0) { $c2=$c; }

$w_unit_cost = $total/$qty;
if($info4000['ricecost_cogs']==1) {

if($prdgross!=0) {    

$arice_charges = $rice_charges * ($total/$prdgross);

if($info3000['costing_weight'] == 1){
  $s_weight = mysqli_get_var("SELECT weight FROM inventory WHERE id = '$c' LIMIT 1");
  if($s_weight == 0){
    $s_weight = 1;
  }
  
  $weight_val = $w_unit_cost + ($rice_charges * (($qty * $s_weight) / $total_weight_));
  $w_unit_cost = $weight_val;
}else{  
  $arice_charges_to = $arice_charges + $total;
  $w_unit_cost = $arice_charges_to/$qty;
}

$brice_charges = $brice_charges + $arice_charges;

}

}

if($info1000['rate_incarton']==1) { $w_unit_cost = $w_unit_cost/$packing; } else { $w_unit_cost = $w_unit_cost; }


if($info3000['en_importexpense_currency'] == 0){
	$w_unit_cost = $w_unit_cost * 1;
}else{
    $w_unit_cost = $w_unit_cost * $_POST['currency_rate'];
}


if($smartbatch_enabled) {
  foreach($smart_batches as $sb_item) {
    if(!is_array($sb_item)) { continue; }
    $sb_batch_id = isset($sb_item['batch_id']) ? (int)$sb_item['batch_id'] : 0;
    $sb_qty = isset($sb_item['qty']) ? (float)$sb_item['qty'] : 0;
    if($sb_qty <= 0) { continue; }
    $actual_qty = $sb_qty;
    $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, packing, foc )
    VALUES ('$c2','$actual_qty','$w_unit_cost','$pwarehouse','$current_company2','5','$date','$wref_id','$sid','1','$customer_id','$sb_batch_id','$packing', '0')" ;

    $retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));
  }
} else {
  $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, packing, foc )
  VALUES ('$c2','$actual_qty','$w_unit_cost','$pwarehouse','$current_company2','5','$date','$wref_id','$sid','1','$customer_id','$pbatch','$packing', '$pfoc')" ;

  $retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));
}

}

}

$data65 = mysqli_query($conn,"SELECT sum(qty_purchase) as qp FROM po_details where order_id='$po_id'") or die(mysqli_error($conn));
$info65 = mysqli_fetch_array( $data65 );

if($info65['qp']==0 || $completepo==1) {
	$sql = "update po
set completed='1' where id='$po_id'";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
	}

if($ptax!=0 || $ptax!=0 || $ptax!=0 ) { 


$taxpercent = ($ptax + $ptax2 + $ptax3)/100;
$singlep = ($_POST['unitcos'][$i]) * $qty;
// $pptax = $taxpercent * $singlep;

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;  }

}

$pptax = $atax;

$total_tax=$total_tax+$pptax;

}

if(is_decimal($total_tax)){  $total_tax = number_format($total_tax,$info2000['total_decimal'], '.', ''); }


if($smartbatch_enabled) {
  $unit_price = ($qty != 0) ? ($total / $qty) : 0;
  foreach($smart_batches as $sb_item) {
    if(!is_array($sb_item)) { continue; }
    $sb_batch_id = isset($sb_item['batch_id']) ? (int)$sb_item['batch_id'] : 0;
    $sb_qty = isset($sb_item['qty']) ? (float)$sb_item['qty'] : 0;
    if($sb_qty <= 0) { continue; }
    $sb_total = $unit_price * $sb_qty;
    $sql = "Insert into purchasing_details
    (order_id,prd_id,packing,packing2,prd_amount,`tp`,discount,discount2,discount3,discount4,scheme,scheme_qty,qty, tax_applied,tax_applied2,tax_applied3, tax_type, mrp_price, tax_mrp,  warehouse_id, batch_id, details2, unit, unit_rate, custom_field1, foc)
    VALUES ('$id','$c','$packing','$packing2','$sb_total','$unitcos','$discount','$discount2','$discount3','$discount4','$pscheme','$pscheme_qty','$sb_qty','$aptax','$ptax2','$ptax3', '$taxtype','$mrp_price', '$tax_mrp','$pwarehouse', '$sb_batch_id', '$description', '$munit','$con_rate', '$custom_field1', '0')";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  }
} else {
  $sql = "Insert into purchasing_details
  (order_id,prd_id,packing,packing2,prd_amount,`tp`,discount,discount2,discount3,discount4,scheme,scheme_qty,qty, tax_applied,tax_applied2,tax_applied3, tax_type, mrp_price, tax_mrp,  warehouse_id, batch_id, details2, unit, unit_rate, custom_field1, foc)
  VALUES ('$id','$c','$packing','$packing2','$total','$unitcos','$discount','$discount2','$discount3','$discount4','$pscheme','$pscheme_qty','$qty','$aptax','$ptax2','$ptax3', '$taxtype','$mrp_price', '$tax_mrp','$pwarehouse', '$pbatch', '$description', '$munit','$con_rate', '$custom_field1', '$pfoc')";

  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}







if(!$po_qtyimpact && $info1000['en_grn']==0) { 

$pqty = mysqli_get_var("Select qty from inventory WHERE id = '$c2'") ;
$puc = mysqli_get_var("Select unit_cost from inventory WHERE id = '$c2'") ;
$pucpqty= $puc * $pqty;
$pucqty= $price * $qty;

$tpuc =  $pucpqty + $pucqty;

$tqty = $pqty + $qty;

$actualpuc = $tpuc / $tqty;
$sql = "UPDATE inventory SET qty = '$tqty' WHERE id = '$c2'" ;


$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


if($info1000['en_inventorybatch']==1) {
  if($smartbatch_enabled) {
    foreach($smart_batches as $sb_item) {
      if(!is_array($sb_item)) { continue; }
      $sb_batch_id = isset($sb_item['batch_id']) ? (int)$sb_item['batch_id'] : 0;
      $sb_qty = isset($sb_item['qty']) ? (float)$sb_item['qty'] : 0;
      if($sb_batch_id > 0 && $sb_qty > 0) {
        $sql="UPDATE inventory_batch SET qty=qty+'".$sb_qty."' WHERE id='".$sb_batch_id."'";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
      }
    }
  } else {
    $sql="UPDATE inventory_batch SET qty=qty+'".$qty."' WHERE id='".$pbatch."'";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  }
}

}


$sid = $id;

// work rice field
// for($kk=0; $kk<COUNT($_POST['fid']); $kk++){
//   $fid = $_POST['fid'][$kk];
//   $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));
// 	}
// }


if(isset($_FILES['riceimage'])){
// $rice_len = count($_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'  and a.stype='6' 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
// work rice field
	 if($info4000['en_shopify']==1) {

updatestocked(0,$c2);

}


 }
 
 // work rice field
if(isset($_POST['fid']) && is_array($_POST['fid'])){

    for($kk = 0; $kk < count($_POST['fid']); $kk++){

        $fid = $_POST['fid'][$kk];
        $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));
        }

    }

} 
  }

$paid=$total_amount-$pending_amount;

$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; 	

//  Hamza
if($info3000['en_importexpense_currency'] == 0){
	$total_amount = $total_amount * 1;
	$paid = $paid * 1;
	$total_tax = $total_tax * 1;
	$pending_amount = $pending_amount * 1;
}else{
    $total_amount = $total_amount * $currency_rate;
    $paid = $paid * $currency_rate;
    $total_tax = $total_tax * $currency_rate;
    $pending_amount = $pending_amount * $currency_rate;
}
//Hamza end

if(1==2)
{


$sql = "Insert into cash_transaction
(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, cost_center )
VALUES ('$date','8','$total_amount','$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+'$total_amount' where id='8'  && costcenter_id='$cost_center'  $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

	
	}
else {

$total_tax = $_POST['invoice_tax'];

$totinventory = $total_amount-$total_tax;

$sql = "Insert into cash_transaction
(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, cost_center )
VALUES ('$date','$sales_id','$totinventory','$ref_id','$memo', 2, '$sid', '$loginuser','$current_company2','$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+'$totinventory' where id='$sales_id'  && costcenter_id='$cost_center'  $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}

if($paid!=0)
{

$sql = "Insert into cash_transaction
(datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, cost_center )
VALUES ('$date','$bank','$paid','$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-'$paid' where id='$bank'  && costcenter_id='$cost_center'  $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


}

if($total_tax!=0)
{
$sql = "Insert into cash_transaction
(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, cost_center  )
VALUES ('$date','$tax_account','$total_tax','$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+'$total_tax' where id='$tax_account'  && costcenter_id='$cost_center'  $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}



if($pending_amount!=0)
{
$sql = "Insert into cash_transaction
(datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, cost_center )
VALUES ('$date','$credit_account','$pending_amount','$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-'$pending_amount' 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($vendor_id);	
	
}




if($info2000['customervendor_same']==1) {

$pa = $total_amount;
$customer= $vendor;


if($info2000['enable_unadjustpayment']==0) {
	
	customerpaymentfifoclear($customer);	
	
}



}



$phonenum = mysqli_get_var("Select cell from user WHERE id = '$vendor_id'");
$smsname = mysqli_get_var("Select company_name from user WHERE id = '$vendor_id'");
$smsname2 = mysqli_get_var("Select lname from user WHERE id = '$vendor_id'");

if($info2000['vendor_sms']==1)
{


$message = "Dear ".$smsname." ,  Purchase Invoice (".$sid.")  of amount Rs.".$total_amount." has been generated.
Thank You";


 $length11= strlen($phonenum);
 
 if($length11==11)
 {
	
send_sms($phonenum,$message,$debug);
 }
 
}


if($info1000['admin_sms']==1)
{



$message = "Dear ".$smsname." ,
   Purchase Invoice (".$sid.")  of amount Rs.".$total_amount." has been generated.
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) {
	

$aarice = $tota;	

if (isset($_POST['rice_discount'])) {
 
 $max_id = mysqli_get_var("SELECT MAX(id) AS id FROM purchasing");

for($i=0 ;$i < count($_POST['rice_discount_value']); $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($specialclass=='single_impact'  ) {
    
    
    
    
    if($less==0) {
	
if($amount_type==0) { $ramount = $qty; } else { $ramount = $aarice * ($qty/100); $aarice = $aarice - $ramount;   }	
	

	
//  Hamza
if($info3000['en_importexpense_currency'] == 0){
    $ramount = $ramount * 1;
}else{
    $ramount = $ramount * $_POST['currency_rate'];
}
			 
 //Hamza end
if($dept_id != 37){
	
	
	$sql = "Insert into cash_transaction
	(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id, cost_center )
	VALUES ('$date','$coa_id','$ramount','$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+'$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, cost_center )
	VALUES ('$date','$coa_id','$ramount','$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-'$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, cost_center )
	VALUES ('$date','$coa_id','$ramount','$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-'$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, cost_center )
		VALUES ('$date','4','$ramount','$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+'$ramount' where id='4' && 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, cost_center )
		VALUES ('$date','$coa_id','$ramount','$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+'$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, cost_center )
	VALUES ('$date','$coa_id','$ramount','$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+'$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, cost_center )
		VALUES ('$date','4','$ramount','$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-'$ramount' where id='4' && 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, cost_center )
		VALUES ('$date','$coa_id','$ramount','$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-'$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 );



$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' ") ;

$specialclass2 = mysqli_get_var("Select specialclass from rice_discount where id='$c'") ;

// Date 11/5/2025
if (strpos($specialclass2, 'PKR_EXPENCE_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass2, 'AGENT_CHARGES_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass2, 'TRANSPORTATION_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass2, 'SHPPING_CHARGES_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass2, 'PORT_CHARGES_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass2, 'EXAMINATION_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass2, 'DUTY') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass2, 'ASSESMENT_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass2, 'MISCELLANCOUS_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}

//Date End

if (strpos($specialclass2, 'Convertion_Rate_Difference_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass2, 'Fright_charges_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass2, 'Insurance_Charges_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass2, 'Commission_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass2, 'Packing_Material_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}


if (strpos($specialclass2, 'investoraccount') !== false) {
if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}


 if($service_id!= 0 && $pvendor_id != 0  && $qty>0)
			 {
				 
				
			if($info4000['en_nooriinternational']==1) { 
	
	

	
	if($specialclass2=='brokery_bags') { 
	
	
	$qty = $qty * $_POST['total_carton'];
	
	
	
	 }
	
	
	 }
				
				 // Date 11/5/2025
          if($info3000['en_importexpense_currency'] == 0){
			        $calculate_rate = $qty * 1;
			    }else{
			        $calculate_rate = $qty * $currency_rate;
			    } 

			 	$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)
			 	VALUES ('0', '0', '0', '$date', '$calculate_rate', '$pvendor_id','$calculate_rate', '$qty', '".$coa_id."', '3', '$daily_id', '$current_time', '$cost_center', '$current_company', '$serial','3','2','1','$service_label','$sid',2)" ;
			
			 	$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));
				
				
			 	$max_id = mysqli_get_var("SELECT MAX(id) AS id FROM purchasing");
				
         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));
          }
        }
	$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', '$qty', '$qty', '1', '1', '$tax_type')";
      $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn)); 
	  
	  
	  if($info2000['enable_unadjustpaymentp']==0) {
	
	supplierpaymentfifoclear($pvendor_id);	
	
}
				
			 }
				
// if($coa_id!=0 && $coa_id2!=0) {
				
	 $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;
			 $daily_id = get_max_daily_id("cash_transaction", $date, 0, $service_invoice, $current_company, $cost_center, $distributor_id); 
			 $serial_code = mysqli_get_var("SELECT MAX(serial_code) FROM cash_transaction WHERE 1=1 AND cost_center = '$cost_center' AND sales_type='1' $serialby_month1  $serialby_year1  ");
			 $serial_code++; 
			
			 //  Hamza
			    if($info3000['en_importexpense_currency'] == 0){
			        $calculate_rate = $qty * 1;
			    }else{
			        $calculate_rate = $qty * $currency_rate;
			    }
			 
			 //Hamza end
			 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(! $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> New Purchase Invoice 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> New Purchase Invoice created successfully.  <a target="_blank" class="btn btn-warning btn-xs" href="'.$info1000['printview_slug'].'print-pi.php?sid='.$sid.'">Print Receipt</a>  &nbsp;&nbsp; <a target="_blank" class="btn btn-warning btn-xs" href="'.$info1000['printview_slug'].'print-pi.php?sid='.$sid.'">Print Duplicate Receipt</a> </div>';
}


}
  
 
 
 ?>
 

<?php include('../layout/header.php'); ?>

<?php include('../layout/sidebar.php'); ?>



<form name="sendmail" method="post" enctype="multipart/form-data" action="create-pi.php" 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">New Purchase Invoice &nbsp;&nbsp;&nbsp; (Invoice #: <?php $numb = mysqli_get_var("Select max(id) from purchasing") ; echo $numb+1; ?>)</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'>New Purchase Invoice &nbsp;&nbsp;&nbsp; (Invoice #: <?php $numb = mysqli_get_var("Select max(id) from purchasing") ; echo $numb+1; ?>)</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 position-relative" style="z-index:2;">
                     New Purchase Invoice &nbsp;&nbsp;&nbsp; (Invoice #: <b><?php $numb = mysqli_get_var("Select max(id) from purchasing") ;
echo $numb+1; ?></b>)
                        <span class="tools pull-right">
                 <input name="on_record" type="checkbox" id="on_record"  <?php $id=$_GET['sid']; $on_record = mysqli_get_var("Select on_record from po 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 row position-relative" style="z-index:1;">
                       <!--Own Text -->
    
     <?php echo $mess; 
    
if(isset($_GET['sid']))
{
	
	
$id=test_input($_GET['sid']);




$data5 = mysqli_query($conn,"SELECT * from po where id='$id'") or die(mysqli_error($conn));

while($info5 = mysqli_fetch_array( $data5 )) 
 { 

$taxapply=$info5['tax_applied'];
$pending =$info5['pending_amount'];
if ($pending!=0)
echo "<div class='alert alert-warning alert-border-left alert-dismissible fade show'><button type='button' class='btn btn-warning btn-xs'>Warning</button> This order's payment is pending</div>";

?>


<div class="col-lg-3">
        <!-- <div class="row">
            <div class="col-md-12">
                <section class="card">
                    
                    <div class="card-body"> -->
                       <!--Own Text -->
                       
  
  <div  <?php if($info2000['en_filesystem']==0) { echo 'style="display:none;"'; } ?> >   
<?php echo $info2000['filesystem_label']; $data4 = mysqli_query($conn,"SELECT id, name  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']." </option>";
	}

	echo "</select><br>"; ?>
</div>

 <input name="amount_received" type="hidden"  value="0" id="amount_received"/> 

<?php echo $info1000['vendor_label']; ?> 
<input name="order_id"  type="hidden" id="order_id"  value="<?php  echo $id; ?>"  />
<input name="broker_id"  type="hidden" id="broker_id"  value="<?php echo $info5['broker_id']; ?>"  />
<input name="vendor"  type="hidden" id="vendor"   value="<?php $vid=$info5['vendor_id'];  echo $info5['vendor_id']; ?>" readonly />
<input name="vendorname" class="form-control"  type="text" 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 ); 
$vendorname = $info7['company_name'];
echo $info7['company_name']." ( ".$info7['fname']." ".$info7['lname']."  ) "; ?>" readonly />
<br>

 <div <?php if($info2000['en_ricetrade']==0) { echo ' style="display:none"'; } ?> > 
<?php





$broker_id = $info5['broker_id']; if($broker_id=='') $broker_id = 0;


 if($broker_id!=0)
{
	
?>
<br>

<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 />	
	
<?php	} else { ?>
<br>

<label>Broker</label>
<input type="text" class="form-control" value="<?php echo $info1000['company_name']; ?>" readonly />

  
<?php }  ?>
</div>

<div style="display: none;">
Search <?php echo $info1000['product_label']; ?><br>
 <?php
    if($en_brand==0) { $bb= " && brand_id IN (Select aid from salesman_reportbrand where eid='$loginuser') ";}
 
  $data = mysqli_query($conn,"SELECT id,name, sku, details, barcode  from inventory where inactive=0 $bb $climit_product  order by name") or die(mysqli_error($conn)); 
 

echo "<select name='teacher_id' id='product_search'  accesskey='s'  class='combobox form-control'   >";
echo "<option value=''>Select a ".$info1000['product_label']."...</option>";
 while($info = mysqli_fetch_array( $data )) 
 { 
   echo "<option value='".$info['id']."' >".$info['barcode'].' '.$info['sku'].' '.$info['name']."</option>";
}


echo "</select>";

?>
</div>




                       
                       <!--Own Text End -->
                    <!-- </div>
                </div>
            </div> -->
        </div>
        <!-- </div> -->
        
        
        <div class="col-lg-2">
        <div class="row">
            <div class="col-md-12">
                <!-- <div class="card card-height-100">
                   
                    <div class="card-body"> -->
                       <!--Own Text -->
                       
  

Date <input name="date" type="date"  id="date" <?php if($info1000['en_backdatedposting']==0) { echo 'max="'.$max_date.'" min="'.$min_date.'"'; } ?>  value="" class="form-control"  />

<br>
<?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>";
?>
<?php } ?>

<br>

 <?php if ($info5['on_record']==0) { ?>
  <input name="on_record2"  type="hidden"  class="form-control" id="onrecord" tabindex='10' value="0" required="required" /> 
   <?php 
  }else {  ?>
    
 
 
  <input name="on_record2"  type="hidden"  class="form-control" id="onrecord" tabindex='10' value="<?php echo $info5['on_record']; ?>" required="required" /> 
<span id="ord" ></span>
 
 <?php } ?>
<span id="serial" ></span>
<br>


<div style=" <?php  if($info2000['custom_onrecord']==0) { echo "display:none;"; } ?>"><br>

Invoice #<br>
  <input name="on_record5"  class="form-control" tabindex='1'  type="number" id="on_record5"  value="<?php echo $info5['on_record'];?>"     required/> 
<br>             </div> 



<div <?php if($info2000['en_ricetrade']==0 && $info4000['salepurchase_accountdynamic']==0) { echo ' style=" display:none;" ';  } ?> >           
                       
             <label>Purchase Account</label>          
                    
                    <?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>
		<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 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>




<div 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>";
 ?>
             </div> 
                       
                       <!--Own Text End -->
                    <!-- </div>
                </div> -->
            </div>
        </div>
        </div>
        
        <!-- <div class="col-lg-2">
        <div class="row">
            <div class="col-md-12"> -->
                <!-- <div class="card card-height-100">
                    
                    <div class="card-body"> -->
                       <!--Own Text -->
                       

   <div <?php if($info2000['en_mastqalandar']==0) echo ' style="display:none"';  ?> >
<b>Broken (%)</b><br>
  <input name="broken" value="0"  class="form-control" required  type="number" id="broken" />  
<br>  



<b>Moisture (%)</b><br>
  <input name="moisture" value="0"  class="form-control"  required  type="number" id="moisture" />  
<br>  <br>

</div>   
  
  
<div <?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>
<br>  

DC Date<br>
  <input name="dcdate"  type="date"  class="form-control" id="dcdate" tabindex='10' <?php if ($info5['serial_date'] > 0){  $odatetime=date('Y-m-d', strtotime($info5['serial_date']));
 echo "value='".$odatetime."'"; }?> /> 

<br>

</div>
<div class="<?php echo $info3000['formlayout_column']; ?>">
Total Amount

 <input name="total" id="total"  type="text" tabindex="-1"     class="total-display form-control" value="<?php echo $info5['total_amount'];?>" readonly="readonly"/>                         
  </div>
  <!--Hamza-->
 
 <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));    
        }
    $ssid = $_GET['sid'];
    $vendor_id2 = mysqli_get_var("SELECT vendor_id2 from purchasing where id = $ssid");
    $vendor_id3 = mysqli_get_var("SELECT vendor_id3 from purchasing where id = $ssid");
        
		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']==$vendorid) { 
		     echo "<option value='".$info4['cid']."' selected='selected' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; 
		     
		 }
		 else { 
		     if($vendor_id2 == $info4['cid']){
		        echo "<option value='".$info4['cid']."' 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>";

	
?>
<!-- <br><br> -->
<!-- </div> -->
</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']==$vendorid) { 
		     echo "<option value='".$info4['cid']."' selected='selected' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; } 
		     else { 
		         if($vendor_id3 == $info4['cid']){
    		        echo "<option value='".$info4['cid']."' 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>
 
 <!--hamza end-->
<div style=" <?php  if($info2000['invoice_cartonrate']==0) { echo "display:none;"; } ?>" class="<?php echo $info3000['formlayout_column']; ?>">

   
   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']; if($info5['factory_weight']=='') echo 0; ?>"  class="form-control"  required  type="number" id="factory_weight" />  
<br> <br>
</div>                       
                        
     
      <div   <?php if($info2000['en_mastqalandarshipment']==0) { echo ' style=" display:none;"'; } ?> >
 <br>

 
 <label>Total <?php $sauda_id =  mysqli_get_var("Select sauda_id from po where id IN (Select po_id from purchasing_grn where id='$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" tabindex="-1"  required   class="form-control" />                         
 
 </div>                       
     
     
     
    <div  <?php if($info2000['en_paymentterms']=="0" ) { echo ' style=" display:none;"'; } ?> >
 

<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;"'; } ?> >
 
 <br>
<br>

<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;"'; } ?> >
 <br>

 
 <label>Mode of Payment</label>
  <input name="dop" value="<?php echo $info5['dop'];?>" type="number" tabindex="-1"  required   class="form-control" />                         
 </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" value="<?php echo $info5['currency_rate']; ?>" />
</div>

</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'   >";

 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>";

?>      
</div>
                   
                       <!--Own Text End -->
                    <!-- </div>
                </div> -->
            <!-- </div>
        </div>
        </div> -->


        <!-- <div class="col-lg-12">
    <div class="row">
        <div class="col-md-12">
            <div class="card card-height-100">
              <div class="card-body"> -->
              

                        
            
              
              
              
              
                        <!-- <div class="row g-3 align-items-end"> -->
<?php
      $stype='4';           
			$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 = $stype 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 = $stype 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" >
<table width="100%" cellpadding="5"  class="table table-striped table-hover align-middle" id="acart">
 <thead>
   <tr>
   
   <th width="25%" ><div><?php echo $info1000['product_label']; ?></div></th> 
    	         <th <?php if($info1000['hide_qavailable']==1) echo ' style="display:none;"';  ?> ><div><?php echo $info3000['qta_avl_label']; ?></div></th>
                 <th ><div><?php echo $info1000['multi_unit_labelp']; ?></div></th>
                   <th <?php if($info1000['no_purchasepacking']==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>
               
                  <?php if($info1000['en_warehouse']==1) {  echo  '  <th ><div>WH </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> '; } ?>        
         
               <?php if($info2000['multiple_batch']==1) {   echo  '  <th ><div>'.$info1000['batch_label'].' </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_mrpcolumn']==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>'; 
				} ?>
            
                
    	<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  ><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, SUM(COALESCE(d.custom_field1,0)) as custom_field1, MAX(d.details2) as details2, MAX(d.tax_mrp) as ptax_mrp, MAX(d.unit) as dunit, SUM(d.prd_amount) as prd_amount, MAX(d.tp) as tp, MAX(d.mrp_price) as pmrp_price, MAX(d.tax_type) as tax_type, MAX(d.uom) as unit, MAX(d.batch_id) as batch_id, MAX(i.name) as name, MAX(d.prd_id) as pid, MAX(d.prd_id) as prd_id, SUM(d.qty_purchase) AS pqty, SUM(d.qty) AS aqty, 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.packing) as pac, MAX(d.packing2) as pac2, MAX(d.qty) AS ppqty, MAX(d.warehouse_id) AS warehouse_id2 from po_details d, inventory i where d.prd_id=i.id AND d.order_id='$id' group by d.prd_id ") or die(mysqli_error($conn));
   } else {
     $data2 = mysqli_query($conn,"SELECT *, d.prd_id  as pid, d.tax_mrp as ptax_mrp, d.mrp_price as pmrp_price , d.qty_purchase AS pqty, d.packing2 as pac2, d.qty AS aqty, 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.packing as pac, d.qty AS ppqty, d.warehouse_id AS warehouse_id2 from po_details d, inventory i where d.prd_id=i.id  AND d.order_id='$id' order by d.id ") or die(mysqli_error($conn));
   }
		
		$totp=0;
	$totc=0;
		$totamounttot=0;
		
while($info2 = mysqli_fetch_array( $data2 )) 
 {
	$custom_field1 = $info2['custom_field1'];
    $gross_weight2 = $info2['pqty'];

	 if($info2000['scheme_directfoc']==0) { 
$sscheme = $info2['scheme_qty'];
 } else {
	
$sscheme = 0; 	 
	 } 
	
$discount=$info2['dd']/100; 
$discount2=$info2['dd2']/100; 
$discount4=$info2['dd4']/100;
 
// $discount3=$info2['dd3']/100; 
$toffer = $info2['dd3']*($info2['ppqty']-$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['ppqty']-$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['ppqty'] * ($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_incarton']==1) {  
$price=$price*$info2['pac'];
 } 

$quant_tot=$info2['pqty']+$quant_tot;




$price=round($price,  $info1000['pproductdecimal'] );

	 
	  ?>
  <tr class="carttr">
    <td><input type="hidden" name="products[]" class="products singleitem" value="<?php echo $info2['pid'];?>"  />
	 <input type="hidden" id="<?php echo "pptax".$info2['id'];?>" name="taxtype[]" value="<?php echo $info2['tax_type'];?>"  />
	<?php echo $info2['name'];?>
                   <div  <?php if($info1000['item_description']==0) echo ' style="display:none;"';   ?>  >
          <textarea name="products_description[]" class="form-control" placeholder="Details.."><?php echo $info2['details2']; ?></textarea> 
        </div> 
    </td>
     <td <?php if($info1000['hide_qavailable']==1) echo ' style="display:none;"';  ?>><?php echo $info2['pqty'];?></td>
    <td>
    <input  type="text" size="4"  class="searchp income_count packing"  id="ctn<?php echo $info2['id'];?>" value="<?php if(is_decimal($info2['pqty'])) { echo (($info2['pqty']-$sscheme)/$info2['pac']); } else { echo floor(($info2['pqty']-$sscheme)/$info2['pac']); } ?>" tabindex="1"/></td>
    
     <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>>   <input type="text" size="4"  value="<?php if(is_decimal($info2['pqty'])) { echo 0; } else {  echo ceil(($info2['pqty']-$sscheme)%$info2['pac']); } ?>"  class="change income_count totalorder" tabindex="1" id="pcs<?php echo $info2['id'];?>"/> 
           

                        </td>
   

       <td <?php if($info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?> ><input  id="customfield<?php echo $info2['id'];?>" name="custom_field1[]"  <?php if($info1000['en_recurringinvoices']==1){ echo "type='number' step='0.001'";}else {echo "type='text'";}?> value="<?php echo $info2['custom_field1']; ?>"  tabindex="1" class="form-control customfield1 income_count teacher" /> </td> 
   
    <?php if($info1000['en_warehouse']==1) { ?>
             <?php
             $selected_warehouse_id = (int)$info2['warehouse_id2'];
             if($selected_warehouse_id <= 0) {
               $selected_warehouse_id = (int)$current_warehouse;
             }
             ?>
             <td><select name="products_warehouse[]"  required   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($selected_warehouse_id==$info4['id'])
 {
   echo "<option value='".$info4['id']."' selected >".$info4['name']."</option>";
}
else {
	   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
	}

 }


?>
</select></td>

<?php } ?>
 
 
 <?php if($info1000['en_inventorybatch']==1) { ?>
  <?php
  $smartbatch_entries = array();
  $smartbatch_count = 0;
  $smartbatch_json = '[]';
  $smartbatch_first_batch = 0;
  if($info3000['en_smartbatch']==1) {
    $pid = $info2['pid'];
    $data_sb = mysqli_query($conn,"SELECT d.batch_id, d.qty_purchase, b.batch_code FROM po_details d LEFT JOIN inventory_batch b ON d.batch_id=b.id WHERE d.order_id='$id' AND d.prd_id='$pid' AND d.qty_purchase > 0 ORDER BY d.id") or die(mysqli_error($conn));
    while($sb = mysqli_fetch_array($data_sb)) {
      $smartbatch_entries[] = array(
        'batch_id' => (int)$sb['batch_id'],
        'batch' => $sb['batch_code'],
        'qty' => (float)$sb['qty_purchase']
      );
      if($smartbatch_first_batch==0) {
        $smartbatch_first_batch = (int)$sb['batch_id'];
      }
    }
    $smartbatch_count = count($smartbatch_entries);
    $smartbatch_json = htmlspecialchars(json_encode($smartbatch_entries), ENT_QUOTES);
  }
  ?>
  <?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; ?>" />
    <input type="hidden" name="batch_old[]" value="1" />
  </td>
  <?php } else { ?>
  <td><div class="batchdiv"><input type="text" name="products_batch[]" <?php  if($info2['is_batch']==0) { echo 'readonly';  }?>  value="<?php if($info2['batch_id']!='' && $info2['batch_id']!=0){ echo mysqli_get_var("select batch_code from inventory_batch where id = ".$info2['batch_id']); }  if($info2['is_batch']==0) { echo 'No Batch';  }?>" tabindex="1" class="change7 income_count batch7 form-control" maxlength="<?php echo $info2000['max_batch_length']; ?>" required id="<?php echo "batch".$info2['id'];?>"  /></div> <input type="hidden" name="batch_old[]" value="0" /></td>
  <?php } ?>
<?php } ?>

 <?php  if($info1000['en_expirydisplay']==1) {  ?>
     
     <td><input type="date" name="products_expiry[]" value="<?php $odatetime=date('Y-m-d', strtotime($current_date));
 echo $odatetime;?>" tabindex="1" required  class="change8 form-control" id="<?php echo "expiry".$info2['id'];?>" /> </td>
  
     <?php } ?>
   
   <?php if($info2000['multiple_batch']==1) { ?>
  <td><input type="text" name="multi_batch[]" value="-" readonly="readonly" /> </td>

<?php } ?>
   
    <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>><input name="products_packing[]" size="4" type="text" class="new_packing searchqty income_count edit-input" id="p<?php echo $info2['id'];?>" tabindex="1"  value="<?php echo $info2['pac'];?>"  readonly="readonly"  /></td>
     <td>
 <input name="unitcos[]" id="pp<?php echo $info2['id'];?>" size="4" tabindex="1" value="<?php echo $info2['tp'];?>" class="new_rate income_count edit-input"  />  


    
<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_mrpcolumn']==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_mrpcolumn']==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['prd_id']."' ");
			$data4 = mysqli_query($conn,"SELECT * FROM product_unit WHERE id IN (SELECT unit FROM multiple_product_unit WHERE pid = '".$info2['prd_id']."' )  ") 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($info2000['en_ricetrade']==0) { echo ' style=" display:none;"'; } ?> ><input name="packing2[]" type="number" tabindex="1" step="0.01" class='teacher income_count'  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'];?>"  tabindex="1"  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'];?>"  tabindex="1"  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'];?>"  tabindex="1"  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'];?>"  tabindex="1"  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'];?>"  tabindex="1"  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'];?>"  tabindex="1"  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;
    }
  ?>
  <td><input type="text" required step="0.0001" name="products_foc[]" value="<?php echo $purchase_foc_initial; ?>" class="foc" id="<?php echo "pfoc".$info2['id'];?>" 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 type="hidden" required step="0.0001" name="products_foc[]" value="0" class="foc" id="<?php echo "pfoc".$info2['id'];?>" 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'];?>"  tabindex="1"  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'];?>"  tabindex="1"  value="0" size="4" />   
   <?php } if($info1000['vendor_scheme']==1) {     ?>                <td ><input name="products_scheme[]"  type="text" size="4"  class="edit-input pscheme5 income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2['scheme'];?>"  /></td>
  <?php } else { ?>   <input name="products_scheme[]"  type="hidden" class="edit-input pscheme5 income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="0" size="4" />       <?php }   ?>        
        
   
  <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>>
     <input name="products_scheme_qty[]" type="hidden" class="edit-input income_count totalorder" id="<?php echo "pppss".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2['scheme_qty'];?>" size="4" /> 
              
  <input  name="products_pcs[]"  step="0.01"  size="4" type="text" class="total_pcs edit-input" id="<?php echo "t".$info2['id'];?>" readonly="readonly" value="<?php echo $info2['pqty'];?>" /></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="text" 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="readonly" />
 
      <?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'];?>"  tabindex="1"  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'];?>"  tabindex="1"  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><input name="products_total[]" size="4" type="text" class="tot<?php echo $info2['id'];?> ptotal  sub_total" id="newtotal<?php echo $info2['id'];?>" tabindex = "-1" value="<?php $aa= $info2['prd_amount']; echo $aa; $totamounttot=$totamounttot+ $aa;?>" readonly  /></td>
               <td><?php if($info87['receipt_edit']==1) { ?><input type="button" class="edit" value="Edit" /><input type="button" class="save" value="Save" /><?php } ?><?php if($info87['receipt_delete']==1) { ?><input type="button" class="delete" value="Delete" /><?php } ?></td> 
   
  </tr>
  <?php } ?>
  </tbody>
</table>
</div>

<br />
<div class="row">
<div class="col-lg-3">
        <!-- <div class="row">
            <div class="col-md-12">
                <div class="card card-height-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="text" class="form-control" id="discount" tabindex="2" 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="text" id="tax" value="'.$taxapply.'" tabindex="4" class="form-control" readonly /><br />';    ?>
</div>

<div class="shipping5" <?php  if($info1000['en_shipping']==0) { echo ' style=" display:none;"'; } ?> >
Freight Charges <input name="shipping" type="text" id="shipping"  tabindex="3"  value="<?php echo $info5['shipping_charges'];?>"  class="form-control"/><br /></div>

    
Notes
<?php
if($info2000['en_chappal'] == 1){
    $truck_no = mysqli_get_var("SELECT num FROM pshipping WHERE sid='$id' AND po=1 ");
    $bilty_no = mysqli_get_var("SELECT value FROM rice_field_details WHERE sid = '$id' AND fid = '3' AND stype = 5 " );
    $info5['notes'] = $vendorname." | T# ".$truck_no." | B# ".$bilty_no." | S# ".$id." | Bags ".$custom_field1." | GW ".$gross_weight2;
}
?>
<textarea name="notes" <?php if($info1000['notes_required']==1) { echo 'required';  } ?> class="form-control" ><?php echo $info5['notes'];?></textarea>
<br>
   
        
<?php if($info2000['en_ricetrade']==1) { $ab = " && 1=2"; } $data4 = mysqli_query($conn,"SELECT * from pshipping where sid='$id' && po=1 $ab ") 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>
<br>
<div class="trdiv" >
<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>
      
<br>
        


                       
                       <!--Own Text End -->
                    <!-- </div>
                </div>
            </div>
        </div> -->
        </div>
        
   
     <div class="col-lg-3">
        <!-- <div class="row">
            <div class="col-md-12">
                <div class="card card-height-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 )) 
 {  ?>
         <div class="col-3">
            <div class="discount-item drice  <?php echo $info4['specialclass']; ?>">
    
                <label class="form-label"><?php echo $info4['label'];  $type_id =  $info4['id']; ?></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['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=2  ");  echo $less;  ?>" name="rice_discount_value[]"   type="number" step="0.001"  class="form-control rice_discount_value"   required/>
              </div>
        </div>
  <?php } ?>
    </div>
</div><br>
  <?php } ?>
<br>

<?php } ?>  


<div class="transporter" <?php if($info1000['en_transporter']==0) { echo 'style="display:none;"'; } ?>>
<br> Transporter  <?php $data4 = mysqli_query($conn,"SELECT * from transporter_data ") or die(mysqli_error($conn)); 

echo "<select name='transporter_id' id='combobox'  class='teacher form-control'   >";

echo "<option value='0' >None</option>";

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
    if($info5['transporter_id']==$info4['id'])
 {echo "<option value='".$info4['id']."' selected='selected' >".$info4['name']."</option>";
	 }
   else {echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}
}

echo "</select>";

?> 
</div>


 <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 name="mode" type="hidden"  value="0"/>
 <input name="bank" type="hidden"  value="0"/>

<br />
    


Complete Purchase Order
 <input name="completepo" type="checkbox" value="1" checked   />  

 

        
            <!--Own Text End -->
                    <!-- </div>
                </div>
            </div>
        </div> -->
        </div>
        
   
        
      <div class="col-lg-3">
        <div class="row">
            <div class="col-md-12">
                <div class="card card-height-100">
                   
                    <div class="card-body">
                       <!--Own Text -->
        

      
<?php if($info3000['en_carton_display']==1){
?>

<?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>                       
  
<?php } ?>

  
<?php echo $info3000['purchase_total_pcs_label'] ?>  <input name="total_pcs" type="text" id="total_pcs" value="<?php echo ceil($totp); ?>" readonly class="form-control"><br>  


<br> 

<div style=" <?php  if($info1000['en_recurringinvoices']==0) { echo "display:none;"; } ?>">
<br> 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>
        </div>
        
</div>
        
        
      <div class="col-lg-3">
        <!-- <div class="row">
            <div class="col-md-12">
                <div class="card card-height-100">
                   
                    <div class="card-body"> -->
                       <!--Own Text -->
                       
   Products Subtotal <input name="sub_total" type="text"  class="form-control" id="sub_total" tabindex="2" value="<?php echo $totamounttot; ?>" readonly/><br />

   <input   class="form-control"   type="hidden" id="grossamount" />  


Pending Amount 
<input name="pending_amount" type="text" class="form-control" id="pending_amount" value="<?php echo $info5['total_amount'];?>" readonly/><br />



<div id="oldr">Old Payable <input name="old" type="text" class="form-control"  id="old" readonly="readonly" value="<?php echo vendoroldpayable($vid); ?>"/> 
<br /></div>


<div class="taxexcludingdisplay">
Amount Excluding Tax <input name="invoice_excludingtax" type="text" class="form-control" id="invoice_excludingtax" value="0" readonly/> 
       <br>


                       
Invoice Tax <input name="invoice_tax" type="text" class="form-control" id="invoice_tax" value="0" readonly/> 
       <br>

</div>

                       
                       <!--Own Text End -->
                    <!-- </div>
                </div>
            </div>
        </div> -->
        </div>

<div style="clear:both" >          
<h3>Total</h3> <input name="total_amount" type="text" class="form-control" id="total_amount" tabindex="4" value="<?php echo $info5['total_amount'];?>" readonly="readonly" required/>

<br />
<br />
<input name="submit" type="submit" id="submit" class="btn btn-success" tabindex="5" value="Create Purchase Invoice"  /> <input type="submit" class="btn btn-success" tabindex="6" value="Reset"  /> 
 <input type="reset" tabindex="7" class="btn btn-info" value="Cancel"  />

</div>

 
 
<br />


<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");
}
});
 
	  
	
	   }); 
		
	
		   
		   
<?php if(!$po_qtyimpact) { ?>
		   $('#product_search').focus();
     
           $('#product_search').change(function () { 
		
		
		var empid = $("#product_search").val();
var cid = $("#vendor").val();

$.ajax
({
type: "POST",
url: "../ajax/receipt-query.php",

data: { pid : empid , vendorid : cid },
cache: false,
dataType : 'html',
success: function(html)
{
$("#psearch").html(html);
$('#product_search').val('');
$('.searchp:first').focus();

}
});
 
	  
	
	   });
<?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>
<script type="text/javascript">
  $(document).ready(function(){

    $(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' required>Image Uploading...</label>");
    },   
    success:function(data)
    {
     $('#settext_'+ idd).html(data);
    }
   });


   
  }}
}); });</script>
<script type="text/javascript">
 
 
  $(document).ready(function () {
	  
	   $('.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);	
});

          
          $('.delete').on('click',function() {
            $(this).closest('tr').remove();

            if ($(".income_count").length) {
              $(".income_count").first().trigger("change");
            } else {
              var decimal_point = "<?php echo $info2000['total_decimal']; ?>";
              var zeroValue = (0).toFixed(decimal_point);
              $("#total_pcs, #packing, #sub_total, #total_amount, #total, #pending_amount").val(zeroValue);
              $(".total-display").val(zeroValue);
            }

            $("#shipping, #discount, .rice_discount_value").trigger("change");
          });

 });  
   
    </script>    

 
  
<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 } ?> 	
		

<?php  if($info2000['en_mastqalandar']==1)
{ ?>

  $('#moisture').change(function () { 
    
    
    var cid = $("#moisture").val();
	var sub_total = $("#sub_total").val();



$.ajax
({
type: "POST",
url: "../ajax/serial-query.php",

data: { cmoisture : cid, sub_total : sub_total },
k8cache: false,
dataType : 'html',
success: function(html)
{
$(".cmoisture").find(".rice_discount_value").val(html);

$('.income_count').trigger('change');

}
});
 
    
  
     });


	$('#moisture').trigger('change');
	
	
	  $('#broken').change(function () { 
    
    
    var cid = $("#broken").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
});

sum = sum - sum2;

$.ajax
({
type: "POST",
url: "../ajax/serial-query.php",

data: { cbroken : cid, sum2 : sum },
k8cache: false,
dataType : 'html',
success: function(html)
{
$(".cbroken").find(".rice_discount_value").val(html);
$('.income_count').trigger('change');

}
});
 
    
  
     });


	$('#broken').trigger('change');
	
	
		$(document).on('change focusout ', '.customfield1', function() {


var packing= $(this).val();
var pval = <?php echo $on_record = mysqli_get_var("Select value from rice_discount where specialclass='cplus' "); ?>

var calc = packing * pval;

   $(".cplus").find(".rice_discount_value").val(calc);


     });
	
	
<?php	} ?>
		

$('.income_count').trigger('change');

  function syncPurchaseFocTotals() {
    var totalPcs = 0;
    $(".total_pcs").each(function() {
      totalPcs += parseFloat($(this).val()) || 0;
    });
    $(".foc").each(function() {
      totalPcs += parseFloat($(this).val()) || 0;
    });
    $("#total_pcs").val(totalPcs);

    var totalCarton = 0;
    $(".packing").each(function() {
      totalCarton += parseFloat($(this).val()) || 0;
    });
    $(".foc").each(function() {
      totalCarton += parseFloat($(this).val()) || 0;
    });
    $("#packing").val(totalCarton);
  }

  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);
        syncPurchaseFocTotals();
      }
      $row.data("purchaseFocQty", qty);
      return;
    }

    var focThreshold = Math.max(focScheme, focValue);
    var focQty = Math.min(focScheme, focValue);
    var nextFoc = 0;

    if (focThreshold > 0 && focQty > 0 && qty > 0) {
      nextFoc = Math.floor(qty / focThreshold) * focQty;
    }

    if (isNaN(lastFocQty)) {
      if (currentFoc === 0 && nextFoc !== 0) {
        $focInput.val(nextFoc);
        syncPurchaseFocTotals();
      }
    } else if (lastFocQty !== qty && currentFoc !== nextFoc) {
      $focInput.val(nextFoc);
      syncPurchaseFocTotals();
    }

    $row.data("purchaseFocQty", qty);
  }

  function refreshAllPurchaseItemFoc() {
    $("#acart tbody tr.carttr").each(function() {
      updatePurchaseItemFoc($(this));
    });
    syncPurchaseFocTotals();
  }

  refreshAllPurchaseItemFoc();

  $(window).on("load", function() {
    setTimeout(refreshAllPurchaseItemFoc, 0);
    setTimeout(refreshAllPurchaseItemFoc, 200);
    setTimeout(refreshAllPurchaseItemFoc, 800);
  });

  $(document).on("change focusout", ".searchp, .change, input[name='products_pcs[]']", function() {
    var $row = $(this).closest("tr.carttr");
    setTimeout(function() {
      updatePurchaseItemFoc($row);
    }, 0);
    setTimeout(function() {
      updatePurchaseItemFoc($row);
    }, 100);
  });

  $(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);
    syncPurchaseFocTotals();
  });

	});

  
 
    </script>    

<?php  include('../functions/incomecount_function.php'); ?>

<script type="text/javascript">
$(document).ready(function () {
  if ($(".income_count").length) {
    $(".income_count").first().trigger("change");
  } else {
    $("#shipping, #discount, .rice_discount_value").trigger("change");
  }
});

$(document).on("input", "#shipping, #discount", function () {
  $(this).trigger("change");
});
</script>

<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>           

  <?php
  }
}
  
  ?>
                    
  
<script type="text/javascript">

 $('input').keyup(function(e){
  if(e.which==39)
   $(this).closest('td').next().find('input').focus();
  else if(e.which==37)
   $(this).closest('td').prev().find('input').focus();
  else if(e.which==40)
   $(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input').focus();
  else if(e.which==38)
   $(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input').focus();
 });

</script>

                       
                       <!--Own Text End -->
                    </div>
                </section>
            </div>
        </div>
        <!-- page end-->
       </div></div></div>
    <!--main content end-->  </form>
<?php include('../layout/sidebar2.php'); ?>


<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>
<?php } ?>



<?php include('../layout/footer.php'); ?>
<script type="text/javascript" >

$(document).ready(function() {
    $("#main-content").toggleClass("merge-left");
	 $("#sidebar").toggleClass("hide-left-bar");
});

<?php if($info3000['en_smartbatch']==1) { ?>
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) {
    $tbody.append('<tr><td>' + (index + 1) + '</td><td>' + (entry.batch || '') + '</td><td>' + (entry.qty || '') + '</td></tr>');
  });
}

$(document).on('click', '.smartbatch-open', function() {
  var $row = $(this).closest('tr');
  var itemText = $(this).data('item') || $.trim($row.find('td').eq(0).text().replace(/\s+/g, ' '));
  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');
});

$(document).on('click', '#smartBatchModal .close, #smartBatchModal [data-dismiss=\"modal\"]', function() {
  $('#smartBatchModal').modal('hide');
});
<?php } ?>

$('.warehouse').attr('tabindex', '1');

</script><?php }      

}


else  header("location:../index.php");  ?>
