<?php include '../global-connect/global-connect.php';
include '../functions/inc.php';
if (!function_exists('bms_inventory_trade_offer_value')) {
function bms_inventory_trade_offer_value($itemId)
{
    $itemId = (int)$itemId;
    if ($itemId <= 0) {
        return 0;
    }
    $tradeOffer = mysqli_get_var("SELECT tradeoffer FROM inventory WHERE id='$itemId' LIMIT 1");
    if ($tradeOffer === null || $tradeOffer === '' || !is_numeric($tradeOffer)) {
        return 0;
    }
    return (float)$tradeOffer;
}
}
$inline_form_direct_enabled = (function_exists('bms_inline_form_direct_enabled') ? bms_inline_form_direct_enabled() : (!empty($info4000['all_in_one']) && (int)$info4000['all_in_one'] === 1)) || (!empty($info4000['custom_development']) && (int)$info4000['custom_development'] === 1);
include_once '../functions/issue-trace-helper.php';

$searchpage=1;
 
$mess="";
session_start();
if(isset($_COOKIE[$info1000['software_version'].'user'])) {
$user=$_COOKIE[$info1000['software_version'].'user'];
$role=$_COOKIE[$info1000['software_version'].'role'];
$loginuser=$_COOKIE[$info1000['software_version'].'uid'];
$onrecord_id=$_COOKIE[$info1000['software_version'].'onrecord_id'];
$on_record = 1;
$current_company=$_COOKIE[$info1000['software_version'].'multi_company'];
$current_company2=$_COOKIE[$info1000['software_version'].'multi_company2'];



$current_zone=$_COOKIE[$info1000['software_version'].'current_zone'];
$current_warehouse=$_COOKIE[$info1000['software_version'].'current_warehouse'];

 
$current_costcenter=$_COOKIE[$info1000['software_version'].'cost_center']; 
$current_costcenter2=$_COOKIE[$info1000['software_version'].'cost_center2']; 

 $po_withoutvalue = !empty($info3000['po_withoutvalue']) && (int)$info3000['po_withoutvalue'] === 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 )) 
 { 
 $issue_trace = function_exists('bms_issue_trace_from_pr')
   ? bms_issue_trace_from_pr(isset($_GET['prid']) ? (int)$_GET['prid'] : 0)
   : array();
 
  // $info_emp = $info;
  $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($_GET['shipping']) && $_GET['shipping']==1){
  $is_shipping = 1;
}else{
  $is_shipping = 0;
}

     
     
if(isset($_SESSION['ncart'])) {  } else { 
$_SESSION['ncart']=array();
}
    
     
$cats = explode(", ", $_GET['nid']);

     
    foreach($cats as $cat) {
     $prod_id = trim($cat);
    
     
  //  $categories .= $cat . "</category>\n";

     
 // $_SESSION['ncart']=array_diff($_SESSION['ncart'], $prod_id);

    //  unset($_SESSION['ncart'][array_search($prod_id, $_SESSION['ncart'])]);

    if(in_array( $prod_id , $_SESSION['ncart'] ) || $prod_id=='') {


    // echo "this is my".$prod_id;
   } else { 

   

        array_push($_SESSION['ncart'],$prod_id);
    }
     
}
    
     $max=sizeof($_SESSION['ncart']);
     
    


     
     
for($i=0; $i<$max; $i++) { 
  $ncart2 ='';
 $_SESSION['ncart'][$i];
    
    
$ncart2 =  $ncart2.$_SESSION['ncart'][$i].", "; 
    
}





if($ncart2!='') { $ncart2 = $ncart2.' 0 '; }     
     
if(isset($_POST['create10']))
{    




$error=0;



$date=date("Y-m-d H:i:s");



if(file_exists($_FILES['customerfile']['tmp_name']) || is_uploaded_file($_FILES['customerfile']['tmp_name'])) {
   
    

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['customerfile']['type'],$mimes)){
    
    
  
 $csvFile = fopen($_FILES['customerfile']['tmp_name'], 'r');
            
            //skip first line
            fgetcsv($csvFile);
 
 
 while(($line = fgetcsv($csvFile)) !== FALSE){
     
      $countv = count($line);


if($countv !=9 && $countv !=1)
{


$error=1;

}

 }


}

}

}
 
  if(isset($_POST['submit']))
{
    
$vendor_id = test_input($_POST['vendor_id']);
$customer_id = test_input($_POST['vendor_id']); 
$brand_input = isset($_POST['brandfilter']) ? $_POST['brandfilter'] : (isset($_POST['inv_brand']) ? $_POST['inv_brand'] : 0);
$brand_id = brandwise_normalize_id($brand_input);
$date = test_input($_POST['date']);
$bank = test_input($_POST['bank']); 

$notes = test_input($_POST['notes']);

$filesystem_id = test_input($_POST['filesystem']);

$mode = test_input($_POST['mode']); 
$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; }

}

if($on_record5=='') { 
$on_record5=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; 
 
 
$dop = test_input($_POST['dop']); 
 
 
  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;
 }


$create_time=date("Y-m-d H:i:s");

$pending_amount = test_input($_POST['pending_amount']); 





    
$total_amount = test_input($_POST['total_amount']); 


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;
    }



$filesystem = test_input($_POST['filesystem']);
$filesystem2 = test_input($_POST['filesystem']);

$file_no = $_POST['file_no'];
if($file_no == '' || $file_no == 0)
    $file_no = 0;

if ($_FILES["file"]["name"]){
    $file_name=$_FILES["file"]["name"];
    $temp_name=$_FILES["file"]["tmp_name"];
    $error = $_FILES["file"]["error"];
    $file_type = $_FILES["file"]["type"];
    $dir = "Purch_order";
    if(!is_dir($dir))
      mkdir($dir);
    
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);
    

    $f_name="purch_order"."".$sid."".$i.".".$ext;
    $target_path = $dir."/".$f_name;
    move_uploaded_file($temp_name, $target_path);

  }



 if(0) {    
 
$filesystem2 = mysqli_get_var("Select id from file_system where  name='$filesystem'  ") ;
 
if($filesystem2=='') {
    
$sql2 = "Insert into file_system (name,dealer_id,last_update)  VALUES ('$filesystem','$customer_id','$current_date')" ;
$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));


$data10 = mysqli_query($conn,"SELECT MAX(id) AS id FROM file_system") or die(mysqli_error($conn));
$info10 = mysqli_fetch_array( $data10 );
$filesystem2= $info10['id'];
     }  }

if($filesystem2=='') { $filesystem2=0; }



$cost_center = test_input($_POST['cost_center']);
$service_invoice = test_input($_POST['service_invoice']);

$dcdate = test_input($_POST['dcdate']); 

$month_id = mysqli_get_var("Select max(month_id) from purchasing WHERE MONTH(datetime)
 = MONTH('$date') && YEAR(datetime)
 = YEAR('$date')");
 $month_id = $month_id+1;
 
 
 $currency = test_input($_POST['currency']);    
$currency_rate = test_input($_POST['currency_rate']);   
$currency_total = test_input($total_amount);

if($info3000['en_importexpense_currency'] == 0){
    $total_amount = $total_amount * 1;
}else{
    $total_amount = $total_amount * $currency_rate;
}

// $total_amount = test_input($_POST['currency_rate']*$total_amount);

$party_id = $_POST['party_id'];
if($party_id == ''){
  $party_id = 0;
}
$purchase_account = $_POST['purchase_account'];
    $purchase_account = 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'];    



if($dcdate==NULL || $dcdate==''){
    $sql2 = "Insert into purchasing
(shipping, datetime, emp_id, vendor_id, vendor_id2, vendor_id3, total_amount,pending_amount,notes,on_record,serial, discount, shipping_charges, tax_applied, inventory_execution, month_id, cost_center, service_invoice, recurring_type, recurring_date, recurring_qty,  currency, currency_rate, currency_total,  create_time, create_by, dop, filesystem_id, party_id, sales_account, credit_account,  tax_account, company_id, brand_id)
VALUES ('$is_shipping','$date','$loginuser','$vendor_id','$vendor_id2','$vendor_id3','$total_amount','$total_amount','$notes','$on_record', '$serial', '$discount' , '$shipping', '$atax', '$inventory_execution', '$month_id', '$cost_center', '$service_invoice', '$recurring_type', '$recurring_date', '$recurring_qty','$currency', '$currency_rate', '$currency_total','$create_time','$loginuser', '$dop','$filesystem2', '$party_id', '$purchase_account', '$credit_account', '$tax_account', '$current_company', '$brand_id')" ;}
else {
    $sql2 = "Insert into purchasing
(shipping, datetime, emp_id, vendor_id, vendor_id2, total_amount,pending_amount,notes,on_record,serial, serial_date, discount, shipping_charges, tax_applied, inventory_execution, month_id, cost_center, service_invoice, recurring_type, recurring_date, recurring_qty,  currency, currency_rate, currency_total,  create_time, create_by , dop , filesystem_id, party_id, sales_account, credit_account,  tax_account, company_id, brand_id )
VALUES ('$is_shipping','$date','$loginuser','$vendor_id','$vendor_id2','$total_amount','$total_amount','$notes','$on_record', '$serial', '$dcdate' , '$discount' , '$shipping', $atax, '$inventory_execution', '$month_id', '$cost_center', '$service_invoice', '$recurring_type', '$recurring_date', '$recurring_qty','$currency', '$currency_rate', '$currency_total','$create_time','$loginuser', '$dop','$filesystem2', '$party_id', '$purchase_account', '$credit_account', '$tax_account', '$current_company', '$brand_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 = $id;

if (isset($_POST['fid'])){
// 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));
    }
}
}

$rice_len = count(isset($_FILES['riceimage'])?$_FILES['riceimage']:[]);
$sql = "SELECT fid,(a.id) as idd,a.stype FROM `rice_field_details` as a ,rice_field as b  where a.fid = b.id and sid ='$sid' and b.itype='5'  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

if($info3000['costing_weight'] == 1){
    $total_weight_ = 0;
  $total_pcs_amount = 0;
}
if (isset($_POST['products'])) {
    
    
  for($i=0 ;$i < count($_POST['products']); $i++) {
    $prdgross = $prdgross + $_POST['products_total'][$i];    
        if($info3000['costing_weight'] == 1){
      $total_pcs_amount = $_POST['products_pcs'][$i];
      $wei = isset($_POST['custom_field1'][$i]) ? (float)$_POST['custom_field1'][$i] : 0;
      if($wei <= 0){
        $wei = 1;
      }
            $total_weight_ = $total_weight_ +  ( $total_pcs_amount * $wei) ;
      
        }
  }
  
}


// work rice field

if($info2000['rice_discount']==1) {

if (isset($_POST['rice_discount']) ) {
 
 
    $max_id = mysqli_get_var("SELECT MAX(id) AS id FROM purchasing");
  $expense_invoice_ids = array();
  $expense_invoice_refs = array();
  $expense_invoice_serials = array();
  $expense_invoice_fifo_synced = array();
 
for($i=0 ;$i < count($_POST['rice_discount_value']); $i++) {

$c= $_POST['rice_discount'][$i];    
$qty=$_POST['rice_discount_value'][$i];
$toggleclass=$_POST['addclass'][$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($qty!="")
{
    
 $sql25 = "Insert into rice_purchase_discount

(sid,type_id, amount, page,toggleclass)
VALUES ('$sid','$c','$qty', 3,'$toggleclass')" ;

$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' ") ;


$specialclass = mysqli_get_var("Select specialclass from rice_discount where id='$c' ") ;
$specialclass2 = mysqli_get_var("Select specialclass2 from rice_discount where id='$c' ") ;
$specialclass_search = strtolower(trim($specialclass.' '.$specialclass2));

if (strpos($specialclass_search, 'usdcost') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'localcost') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'pkr_expence_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'agent_charges_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'transportation_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'shpping_charges_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'port_charges_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'examination_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'duty') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'assesment_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}else if (strpos($specialclass_search, 'miscellancous_noimpact') !== false) {
    if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}



if (strpos($specialclass_search, 'convertion_rate_difference_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'fright_charges_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'insurance_charges_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'commission_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}else if (strpos($specialclass_search, 'packing_material_noimpact') !== false) {
    if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}


if (strpos($specialclass_search, 'dealeraccount') !== false) {
if($vendor_id2!=0) $pvendor_id = $vendor_id2;
}

if (strpos($specialclass_search, 'investoraccount') !== false) {
if($vendor_id3!=0) $pvendor_id = $vendor_id3;
}


 if($service_id!=0 && $pvendor_id != 0  && $qty>0)
             {
          $expense_amount = (float)$qty;

          if($info4000['en_nooriinternational']==1 && strpos($specialclass_search, 'brokery_bags') !== false) {
            $expense_amount = $expense_amount * (float)$_POST['total_carton'];
          }

          $currency_amount = $expense_amount;
          if (strpos($specialclass_search, 'usdcost') !== false) {
            $calculate_rate = $currency_amount * (float)$currency_rate;
          } else if (strpos($specialclass_search, 'localcost') !== false) {
            $calculate_rate = $currency_amount;
          } else if($info3000['en_importexpense_currency'] == 0){
            $calculate_rate = $currency_amount;
          } else {
            $calculate_rate = $currency_amount * (float)$currency_rate;
          }

          $invoice_key = (string)$pvendor_id;
          if(!isset($expense_invoice_ids[$invoice_key])) {
            $daily_id = get_max_daily_id("purchasing", $date, 0, $service_invoice, $current_company, $cost_center, $distributor_id);
            $sql2 = "INSERT INTO purchasing (po_id,  broker_id, sauda_id, datetime, pending_amount, vendor_id, total_amount, currency_total, sales_account, type_component, daily_id, create_time, cost_center, company_id, serial,pr_id,currency,currency_rate, notes, pay_id, truck_type, brand_id)
            VALUES ('0', '0', '0', '$date', '$calculate_rate', '$pvendor_id','$calculate_rate', '$currency_amount', '$coa_id', '3', '$daily_id', '$current_time', '$cost_center', '$current_company', '$serial','3','2','1','$service_label','$sid',2, '$brand_id')" ;

            $retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));
            $max_id = mysqli_get_var("SELECT MAX(id) AS id FROM purchasing");
            $expense_invoice_ids[$invoice_key] = $max_id;

            $data20 = mysqli_query($conn,"SELECT max(ref_id) as max from cash_transaction") or die(mysqli_error($conn));
            $info20 = mysqli_fetch_array( $data20 );
            $expense_invoice_refs[$invoice_key] = $info20['max']+1;
            $expense_invoice_serials[$invoice_key] = mysqli_get_var("SELECT COALESCE(MAX(serial_code),0)+1 FROM cash_transaction WHERE 1=1 AND cost_center = '$cost_center' AND sales_type='1' $serialby_month1  $serialby_year1  ");

            if($info4000['en_vgm']==1){
              $ricedata  =mysqli_get_var("SELECT GROUP_CONCAT(a.label,': ',b.value) as rice_data  FROM `rice_field_details` as b ,rice_field as a
            WHERE a.id=b.fid and  b.sid in($sid) and b.stype='6'");
              if ($ricedata!='') {
                  $note = mysqli_get_var("select notes from purchasing where id ='$max_id'");
                  $note = $note.' '.$ricedata;
                  $sql = "UPDATE purchasing SET notes = '$note' WHERE id = '$max_id'" ;
                  $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
              }
            }
          } else {
            $max_id = $expense_invoice_ids[$invoice_key];
            mysqli_query($conn, "UPDATE purchasing SET pending_amount = pending_amount + '$calculate_rate', total_amount = total_amount + '$calculate_rate', currency_total = currency_total + '$currency_amount' WHERE id = '$max_id'") or die(mysqli_error($conn));
          }

          $tax_type = mysqli_get_var("SELECT is_taxable FROM services WHERE id = '$service_id' ");
          $sql = "INSERT INTO purchasing_details (order_id, prd_id, packing, packing2, prd_amount, `tp`, qty, warehouse_id, tax_type) VALUES ('$max_id', '$service_id', '1', '1', '$currency_amount', '$currency_amount', '1', '1', '$tax_type')";
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

          if($info2000['enable_unadjustpaymentp']==0 && !isset($expense_invoice_fifo_synced[$invoice_key])) {
            supplierpaymentfifoclear($pvendor_id, $brand_id);
            $expense_invoice_fifo_synced[$invoice_key] = 1;
          }

          $ref_id = $expense_invoice_refs[$invoice_key];
          $serial_code = $expense_invoice_serials[$invoice_key];
          $daily_id = get_max_daily_id("cash_transaction", $date, 0, $service_invoice, $current_company, $cost_center, $distributor_id);

          if($coa_id2!=0) {
            $sql = "INSERT INTO cash_transaction (datetime, account_id, debit, credit, ref_id, description, transaction_type, arefer, cost_center, on_record, sales_type,  user_type, user_id , create_time, create_by, company_id, serial_code, filesystem_id, daily_id, verified_by, verified_time )
            VALUES ('$date', '$coa_id2', '0', '$calculate_rate', '$ref_id', '$service_label',  2, '$max_id', '$cost_center', '0', '1', '0', '0', '$current_time', '$loginuser' , '$current_company2', '$serial_code', '$filesystem_id', '$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', '$filesystem_id', '$daily_id', '$loginuser', '$current_time')" ;
            $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

            $sql = "Update accounts_type Set balance=balance+'$calculate_rate' where id='$coa_id' && costcenter_id='$cost_center'  $caccounts_company";
            $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
          }

          if($info4000['ricecost_cogs']==1 && $info3000['en_ajk'] == 0) {
            $check_inventory = mysqli_get_var("select count(id) as count from cash_transaction where account_id = '$purchase_account' and ref_id = '$ref_id' and transaction_type = 2 And arefer = '$max_id' ");
            if($check_inventory==0){
              $sql = "INSERT INTO cash_transaction (datetime, account_id, debit, credit, ref_id, description, transaction_type, arefer, cost_center, on_record, sales_type,  user_type, user_id , create_time, create_by, company_id, serial_code, filesystem_id, daily_id, verified_by, verified_time )
              VALUES ('$date', '$purchase_account', '$currency_amount', '0', '$ref_id', 'Inventory Effect',  2, '$max_id', '$cost_center', '0', '1', '0', '0', '$current_time', '$loginuser' , '$current_company2', '$serial_code', '$filesystem_id', '$daily_id', '$loginuser', '$current_time')" ;
              $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

              $sql = "Update accounts_type Set balance=balance+'$currency_amount' where id='$purchase_account' && costcenter_id='$cost_center'  $caccounts_company";
              $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
            }else{
              $sql = "Update cash_transaction Set debit = debit+'$currency_amount' where account_id = '$purchase_account' and ref_id = '$ref_id' and transaction_type = 2 And arefer = '$max_id' " ;
              $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

              $sql = "Update accounts_type Set balance=balance+'$currency_amount' where id='$purchase_account' && costcenter_id='$cost_center'  $caccounts_company";
              $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
            }
          }

} } } }
}



$tr = test_input($_POST['tr']);

if($tr=='y')
{
    
    
if (isset($_POST['shipping_details'])) {
 
 
  foreach ($_POST['shipping_details'] as $n) {  

$tr_num = $_POST[$n.'tr_num'];
$tr_name = $_POST[$n.'tr_name'];
$tr_qty = $_POST[$n.'tr_qty'];
$tr_date = $_POST[$n.'tr_date'];

if($tr_date==NULL || $tr_date=='')
$tr_date=date("Y-m-d H:i:s");
else $tr_date = test_input($_POST[$n.'tr_date']);

if($tr_num!='' || $tr_name!='')
{
$sql25 = "Insert into pshipping

(sid,num,name,qty,datetime,po)
VALUES ('$id','$tr_num','$tr_name','$tr_qty','$tr_date','2')" ;

$retval25 = mysqli_query($conn, $sql25 ) or die(mysqli_error($conn));
}
    }
}

}
 

$data20 = mysqli_query($conn,"SELECT max(wref_id) as max from warehouse_transaction") or die(mysqli_error($conn));
  
$info20 = mysqli_fetch_array( $data20 );
 $wref_id=$info20['max']+1;         
    
if (isset($_POST['products'])) {
    
    

for($i=0 ;$i < count($_POST['products']); $i++) {
$c= $_POST['products'][$i];   
$qty=$_POST['products_pcs'][$i];

$description=test_input($_POST['products_description'][$i]);
$smartbatch_enabled = ($info3000['en_smartbatch']==1 && ($info4000['grn_single_batch_qty']==1 || $info3000['open_batchgrn']==1));
$smart_batch_items = array();
$smart_batch_refs = array();
$smart_total_qty = 0;

if($smartbatch_enabled && isset($_POST['smartbatch_data'][$i])) {
  $smart_raw = trim($_POST['smartbatch_data'][$i]);
  if($smart_raw!='') {
    $smart_batches = json_decode($smart_raw, true);
    if(is_array($smart_batches)) {
      $smart_total_weight = 0;
      foreach($smart_batches as $entry) {
        if(!is_array($entry)) { continue; }
        $batch_code = isset($entry['batch']) ? trim($entry['batch']) : '';
        if($batch_code=='') {
          $batch_code = isset($entry['batch_code']) ? trim($entry['batch_code']) : '';
        }
        $batch_qty = isset($entry['qty']) ? floatval($entry['qty']) : 0;
        $batch_weight = isset($entry['weight']) ? floatval($entry['weight']) : 0;
        if($batch_code=='' || $batch_qty<=0) { continue; }
        $smart_total_qty += $batch_qty;
        $smart_total_weight += $batch_weight;
        $smart_batch_items[] = array('batch_code' => $batch_code, 'qty' => $batch_qty, 'weight' => $batch_weight);
      }
      if(!empty($smart_batch_items)) {
        $_POST['custom_field1'][$i] = $smart_total_weight;
      }
    }
  }
}

$custom_field1=$_POST['custom_field1'][$i];
$custom_field2=$_POST['custom_field2'][$i];
$custom_field3=$_POST['custom_field3'][$i];
$custom_field4=$_POST['custom_field4'][$i];
$custom_field5=$_POST['custom_field5'][$i];
$custom_field6=$_POST['custom_field6'][$i];


$packing=$_POST['products_packing'][$i];
$discount=$_POST['products_discount'][$i];
$total=$_POST['products_total'][$i];
$unitcos=$_POST['unitcos'][$i];

if(isset($_POST['price_slc'][$i]) && $_POST['price_slc'][$i]!='') { $custom_field1=$_POST['price_slc'][$i]; }
if($smartbatch_enabled && count($smart_batch_items)>0) { $custom_field1 = $smart_total_weight; }

if($smart_total_qty>0) {
    $qty = $smart_total_qty;
}


if(isset($_POST['products_foc'][$i])) 
{
    $pfoc=$_POST['products_foc'][$i];
}
else 
{
    $pfoc=0;
}
    


$munit=$_POST['munit'][$i];
$con_rate=$_POST['con_rate'][$i];
$munit = ($munit) ? $munit : 0;
$con_rate = ($con_rate) ? $con_rate : 0;



$rate_in_carton = $_POST['rate_in_carton'][$i]; 
if($rate_in_carton == '')
    $rate_in_carton = 0;

$packing2=$_POST['packing2'][$i];

if($packing2 == '')
    $packing2 = 1;


if(isset($_POST['products_warehouse'][$i])) {
$pwarehouse=$_POST['products_warehouse'][$i];
}
else {
    $pwarehouse=0;
    }
    
    
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($info1000['en_inventorybatch'] == 1 && $info2000['batch_grnonly'] == 0 && $info1000['direct_invoicep']==1 && $info3000['en_hapaperhub']==0) { 

  if($info1000['batch_with_brand']==1){

    // BRAND WORK
    if(isset($_POST['batch_brand'][$i]) && $_POST['batch_brand'][$i]!='') {
        
      $batch_brand = $_POST['batch_brand'][$i];
      $brand_count = mysqli_get_var("SELECT COUNT(id) FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
    
      if ($brand_count != 0) {
          $batch_brand = mysqli_get_var("SELECT id FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
      } else {
          $sql = "INSERT INTO product_brands (name) VALUES ('$batch_brand')";
          $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    
          $batch_brand = mysqli_get_var("SELECT id FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
      }
    
    } else {
      // IT WILL CHECK IF THERE IS ANY BRAND ON EMPTY '' will get its id else 0
        $batch_brand = $_POST['batch_brand'][$i];
        $brand_count = mysqli_get_var("SELECT COUNT(id) FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
        if ($brand_count != 0) {
          $batch_brand = mysqli_get_var("SELECT id FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
        } else {
          $batch_brand=0;
        }
    }
        
    // BATCH WITH BRAND
    if($smartbatch_enabled && count($smart_batch_items)>0) {
      foreach($smart_batch_items as $sb_index => $sb_item) {
        $pbatch=$sb_item['batch_code'];
        $batch1 = mysqli_get_var("Select count(id) from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0 && brand_id = '$batch_brand' "); 
        if($batch1!=0) {
          $pbatch_id = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0 && brand_id = '$batch_brand' "); 
        } else {
          $pexpiry=$_POST['products_expiry'][$i];
          $sql = "Insert into inventory_batch
          (batch_code, prd_id, exp_date, brand_id,packing)
          VALUES ('$pbatch','$c','$pexpiry','$batch_brand','$packing')";
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
          $pbatch_id = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0 && brand_id = '$batch_brand' "); 
        }
        $smart_batch_refs[] = array('id' => $pbatch_id, 'code' => $pbatch, 'qty' => $sb_item['qty'], 'weight' => (isset($sb_item['weight']) ? $sb_item['weight'] : 0));
      }
      $pbatch=0;
    } else if(isset($_POST['products_batch'][$i])) {
        
      $pbatch=$_POST['products_batch'][$i];
      
      $batch1 = mysqli_get_var("Select count(id) from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0 && brand_id = '$batch_brand' "); 
      if($batch1!=0) {
        $pbatch = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0 && brand_id = '$batch_brand' "); 
      } else {
      
      $pexpiry=$_POST['products_expiry'][$i];
      
      $sql = "Insert into inventory_batch
      (batch_code, prd_id, exp_date, brand_id,packing)
      VALUES ('$pbatch','$c','$pexpiry','$batch_brand','$packing')";
      
      $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 && brand_id = '$batch_brand' "); 
        
      }
      
    
    } else {
      $pbatch=0;
    }
    
}else{
      
if($smartbatch_enabled && count($smart_batch_items)>0) {

foreach($smart_batch_items as $sb_index => $sb_item) {

$pbatch=$sb_item['batch_code'];

$batch1 = mysqli_get_var("Select count(id) from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0"); 
if($batch1!=0) {
$pbatch_id = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0"); 
} else {

$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_id = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0"); 
  
}

$smart_batch_refs[] = array('id' => $pbatch_id, 'code' => $pbatch, 'qty' => $sb_item['qty']);

}

$pbatch=0;

}
else if(isset($_POST['products_batch'][$i])) {
  
$pbatch=$_POST['products_batch'][$i];

$batch1 = mysqli_get_var("Select count(id) from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0"); 
if($batch1!=0) {
$pbatch = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0"); 
} else {

$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;
  } 
}
}
else {
 if(isset($_POST['products_batch'][$i])) {

$pbatch=$_POST['products_batch'][$i];
}
else {
  $pbatch=0;
  }      
}  

    
// 
// 
// if(isset($_POST['products_batch'][$i])) {


// $pbatch=$_POST['products_batch'][$i];
// $pexpiry=$_POST['products_expiry'][$i];


// if($info4000['en_allbatchdisplay']==1) { 



//   $bval = mysqli_get_var("SELECT id FROM inventory_batch WHERE batch_code IN (Select batch_code from inventory_batch where id = '$pbatch' && type_component=0  ) &&  prd_id='$c' && type_component=0   "); 
     
//   if($bval!='') { $pbatch = $bval; }
// else {   
//  $bval = mysqli_get_var("Select batch_code from inventory_batch where id = '$pbatch'    ");  
//   $sql = "INSERT into inventory_batch (batch_code, prd_id, qty,type_component) VALUES ('$bval','$c',1, 0)  " ;
// $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

//  $pbatch = mysqli_get_var("SELECT id FROM inventory_batch WHERE batch_code IN (Select batch_code from inventory_batch where id = '$pbatch' && type_component=0  ) &&  prd_id='$c' && type_component=0   "); 

// } }
// else {
// $sql = "Insert into inventory_batch
// (batch_code, prd_id, exp_date, type_component)
// VALUES ('$pbatch','$c','$pexpiry',0)";

// $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

// $pbatch = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch' && type_component=0"); 


// }
// }
// else {
//  $pbatch=0;
//  }   
  
$taxtype=$_POST['taxtype'][$i];
$ptax=$_POST['products_tax'][$i];
$ptax2=$_POST['products_tax2'][$i];
$ptax3=$_POST['products_tax3'][$i];
$aptax=$_POST['products_tax'][$i];


$discount=$_POST['products_discount'][$i];
$discount2=$_POST['products_discount2'][$i];
$discount4=$_POST['products_discount4'][$i];
$discount3=bms_inventory_trade_offer_value($c);
$pscheme=$_POST['products_scheme'][$i];
$pscheme_qty=$_POST['products_scheme_qty'][$i];
$uom=$_POST['uom'][$i];
if($uom == '')
    $uom = 0;
if($discount == '')
    $discount = 0;
if($discount2 == '')
    $discount2 = 0;
if($discount4 == '')
    $discount4 = 0;
if($discount3 == '')
    $discount3 = 0;

if($pscheme_qty == '')
    $pscheme_qty = 0;


if($qty > 0)
{

$price=$total/$qty;

$taxpercent = ($ptax + $ptax2 + $ptax3);
$singlep = ($_POST['unitcos'][$i]) * $qty;
// $pptax = $taxpercent * $singlep;

$mrp_price=$_POST['mrp_price'][$i];
$tax_mrp=$_POST['tax_mrp'][$i];

$atax=0;

if($taxpercent!=0) {
    
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 = $total-($gross-$discount1-$discount2-$discount3);  $tatax = $tatax + $atax;  }
}

$pptax = $atax;

$total_tax = $_POST['invoice_tax'];




$w_unit_cost = $total/$qty;

if($info4000['ricecost_cogs']==1) {

// if($prdgross!=0) {       
    
// $arice_charges = $rice_charges * ($total/$prdgross);
// $arice_charges_to = $arice_charges + $total;
// // $w_unit_cost = $w_unit_cost + ($arice_charges/$qty);
// $w_unit_cost = $arice_charges_to/$qty;
// $brice_charges = $brice_charges + $arice_charges;

// }
if($prdgross!=0) {      
    
$arice_charges = $rice_charges * ($total/$prdgross);

if($info3000['costing_weight'] == 1){
  $weight_per_unit = isset($_POST['custom_field1'][$i]) ? (float)$_POST['custom_field1'][$i] : 0;
  if($weight_per_unit <= 0){
    $weight_per_unit = 1;
  }
  if($total_weight_ <= 0){
    $total_weight_ = 1;
  }
  $weighted_charge_share = $rice_charges * (($qty * $weight_per_unit) / $total_weight_);
  $w_unit_cost = $w_unit_cost + ($weighted_charge_share / $qty);
}else{  
  $arice_charges_to = $arice_charges + $total;
  $w_unit_cost = $arice_charges_to/$qty;
}

$brice_charges = $brice_charges + $arice_charges;

}

}

if($info3000['en_importexpense_currency'] == 0){
    $w_unit_cost = $w_unit_cost * 1;
}else{
    $w_unit_cost = $w_unit_cost * $_POST['currency_rate'];
}
// $w_unit_cost = $w_unit_cost * $_POST['currency_rate'];


// echo "Final Cost: "+$w_unit_cost;
// die('');

if($info4000['en_razik']==0)  {
$totinventory = $totinventory+($w_unit_cost*$qty);  
} else {

$totinventory = $totinventory+$total;   
}

if(0==1) {

/*---------------start update price unitcost customfield1 and customfield2--------------*/
$customfields1_mrpprice = mysqli_get_var("SELECT mrp_price FROM inventory where id = '$c' order by id desc limit 1"); 
$customfields2_unitcost = mysqli_get_var("SELECT unit_cost FROM inventory where id = '$c' order by id desc limit 1"); 

$customfields1_mrpprice=($customfields1_mrpprice>0)?$customfields1_mrpprice:$mrp_price;

$sale_price=$_POST['sale_price'][$i];
    
$sql = "UPDATE inventory SET `mrp_price`='$sale_price', `sale_price`='$sale_price' WHERE id = '$c'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    

$mrp_price = $sale_price;   
    
}


$mrp_price=$_POST['mrp_price'][$i];
$tax_mrp=$_POST['tax_mrp'][$i];

if($mrp_price=='') $mrp_price=0;
if($tax_mrp=='') $tax_mrp=0;


$sql = "Insert into purchasing_details
(order_id,prd_id, packing, packing2,prd_amount,tp,  mrp_price, tax_mrp, custom_field1, custom_field2, custom_field3,custom_field4, custom_field5, custom_field6, discount,discount2,discount3,discount4,scheme,scheme_qty,qty, tax_applied,tax_applied2,tax_applied3, tax_type,  warehouse_id, batch_id, details2,  unit, unit_rate, foc, rate_in_carton, uom)
VALUES ('$id','$c','$packing','$packing2','$total','$unitcos','$mrp_price', '$tax_mrp','$custom_field1', '$custom_field2','$custom_field3','$custom_field4','$custom_field5','$custom_field6','$discount','$discount2','$discount3','$discount4','$pscheme','$pscheme_qty','$qty','$aptax','$ptax2','$ptax3', '$taxtype','$pwarehouse', '$pbatch', '$description', '$munit','$con_rate','$pfoc', '$rate_in_carton', '$uom')";
if($smartbatch_enabled && count($smart_batch_refs)>0) {
  $unit_price = 0;
  if ($qty > 0) {
    $unit_price = $total / $qty;
  }
  foreach($smart_batch_refs as $sb_item) {
    $sb_qty = $sb_item['qty'];
    $sb_total = $unit_price * $sb_qty;
    $sb_weight = isset($sb_item['weight']) ? (float)$sb_item['weight'] : 0;
    $sql = "Insert into purchasing_details
    (order_id,prd_id, packing, packing2,prd_amount,tp,  mrp_price, tax_mrp, custom_field1, custom_field2, custom_field3,custom_field4, custom_field5, custom_field6, discount,discount2,discount3,discount4,scheme,scheme_qty,qty, tax_applied,tax_applied2,tax_applied3, tax_type,  warehouse_id, batch_id, details2,  unit, unit_rate, foc, rate_in_carton, uom)
    VALUES ('$id','$c','$packing','$packing2','$sb_total','$unitcos','$mrp_price', '$tax_mrp','$sb_weight', '$custom_field2','$custom_field3','$custom_field4','$custom_field5','$custom_field6','$discount','$discount2','$discount3','$discount4','$pscheme','$pscheme_qty','$sb_qty','$aptax','$ptax2','$ptax3', '$taxtype','$pwarehouse', '".$sb_item['id']."', '$description', '$munit','$con_rate','$pfoc', '$rate_in_carton', '$uom')";
    $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
  }
} else {
  $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
}



// Basit
if($info3000['en_hapaperhub'] == 1) 
{
    $current_date = date('d/m/Y');
    $batch_values = explode(',', $custom_field1);
    $batch_total_qty = array_sum(array_map('trim', $batch_values)); 

    foreach($batch_values as $batch_value_raw) 
    {
        $batch_single_value = trim($batch_value_raw);
        if(empty($batch_single_value)) continue;

        $new_batch_code = $current_date . '-' . $batch_single_value;

        $check_batch_sql = "SELECT id, qty FROM inventory_batch 
                      WHERE prd_id = '$c' 
                      AND batch_code = '$new_batch_code' 
                      AND type_component = 0";
        $check_batch_result = mysqli_query($conn, $check_batch_sql);

        if(mysqli_num_rows($check_batch_result) > 0) 
        {
            $batch_row = mysqli_fetch_assoc($check_batch_result);
            $current_batch_id = $batch_row['id'];
            
            $check_tran_sql = "SELECT id, qty FROM warehouse_transaction 
                           WHERE item_id = '$c' 
                           AND batch_no = '$current_batch_id' 
                           AND warehouse_id = '$pwarehouse'";
            $tran_result = mysqli_query($conn, $check_tran_sql);

            if(mysqli_num_rows($tran_result) > 0) 
            {
                $tran_row = mysqli_fetch_assoc($tran_result);
                $existing_tran_qty = (float)$tran_row['qty'];
                $new_tran_qty = $existing_tran_qty + $batch_total_qty;

                $update_tran_sql = "UPDATE warehouse_transaction 
                               SET qty = '$new_tran_qty' 
                               WHERE id = '".$tran_row['id']."'";
                mysqli_query($conn, $update_tran_sql) or die(mysqli_error($conn));
            } 
            else 
            {
                $insert_tran_sql = "INSERT INTO warehouse_transaction
                         (item_id, qty, item_cost, warehouse_id, company_id, tran_type, 
                          `datetime`, `wref_id`, arefer, atran_type, cvuser, batch_no, packing)
                         VALUES 
                         ('$c', '$batch_total_qty', '$w_unit_cost', '$pwarehouse', '$current_company2',
                          '5', '$date', '$wref_id', '$sid', '1', '$customer_id', '$current_batch_id', '$packing')";
                mysqli_query($conn, $insert_tran_sql) or die(mysqli_error($conn));
            }
        } 
        else 
        {
            $insert_batch_sql = "INSERT INTO inventory_batch
                           (batch_code, prd_id, qty, exp_date, type_component)
                           VALUES 
                           ('$new_batch_code', '$c', '$batch_total_qty', NULL, 0)";
            mysqli_query($conn, $insert_batch_sql) or die(mysqli_error($conn));

            $new_batch_id = mysqli_insert_id($conn);

            $insert_new_tran_sql = "INSERT INTO warehouse_transaction
                     (item_id, qty, item_cost, warehouse_id, company_id, tran_type, 
                      `datetime`, `wref_id`, arefer, atran_type, cvuser, batch_no, packing)
                     VALUES 
                     ('$c', '$batch_total_qty', '$w_unit_cost', '$pwarehouse', '$current_company2',
                      '5', '$date', '$wref_id', '$sid', '1', '$customer_id', '$new_batch_id', '$packing')";
            mysqli_query($conn, $insert_new_tran_sql) or die(mysqli_error($conn));
        }
    }
}


if($info3000['en_hapaperhub'] == 0) {
    
$c2 = mysqli_get_var("Select stock_effect from inventory WHERE id = '$c'"); 
if($c2==0) { $c2=$c; }  


if($info4000['en_umarsons']==1) { $qty = $qty - $pfoc; }

$actual_qty = $qty + $pfoc;
if($smartbatch_enabled && count($smart_batch_refs)>0) {
 foreach($smart_batch_refs as $sb_item) {
  $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','".$sb_item['qty']."','$w_unit_cost','$pwarehouse','$current_company2','5','$date','$wref_id','$sid','1','$customer_id','".$sb_item['id']."','$packing', '0')" ;

  $retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));
 }
} else {
 $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));
}


if($info4000['ricecost_cogs']==1) {

$sql = "update warehouse_transaction  set item_cost='$w_unit_cost' where arefer='$grn_id' AND item_id='$c' AND tran_type=26 && deleted=0 ";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "update warehouse_transaction  set item_cost='$w_unit_cost' where arefer='$sid' AND item_id='$c' AND tran_type=5 && deleted=0 ";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}

$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 = $pucqty + $pucpqty;

$tqty = $pqty + $qty;

if($pqty<=0 || $puc<=0 )
$actualpuc= $price;
else  $actualpuc = $tpuc / $tqty;

$sql = "UPDATE inventory SET qty = '$tqty', `unit_cost`='$unitcos' WHERE id = '$c2'" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));



if($smartbatch_enabled && count($smart_batch_refs)>0) {
  foreach($smart_batch_refs as $sb_item) {
    $sql = "UPDATE inventory_batch SET qty = qty + '".$sb_item['qty']."' WHERE prd_id='$c2' &&  id = '".$sb_item['id']."'" ;
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  }
} else {
  $sql = "UPDATE inventory_batch SET qty = qty + '$qty' WHERE prd_id='$c2' &&  id = '$pbatch'" ;
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}

}

}
 }


 //Update Costing WRT Rice amounts
 if($info4000['ricecost_cogs']==1 && 1==2) {

  if($info2000['rice_discount']==1) {
    if (isset($_POST['rice_discount']) ) {
      
      $total_rice = 0;
      for($i=0 ;$i < count($_POST['rice_discount']); $i++) {
        $total_rice+=$_POST['rice_discount_value'][$i];
      }   

      if($info3000['weight_cost']==1){
        $total_prd_qty = mysqli_get_var("select sum(qty) as total_qty from purchasing_details where order_id = '$id' ");
        $r_final_cost = $total_rice/$total_prd_qty;
      }else{
        $total_prd_amount = mysqli_get_var("select sum(prd_amount) as total_amount from purchasing_details where order_id = '$id' ");
        $r_final_cost = $total_rice/$total_prd_amount;
      }         

      for($i=0 ;$i < count($_POST['products']); $i++) {

        $c= $_POST['products'][$i];   

        if($info3000['weight_cost']==1){
          $qty=$_POST['products_pcs'][$i];
          $rice_added_cost = $r_final_cost * $qty;
        }else{
          $amount=$_POST['products_total'][$i];
          $rice_added_cost = $r_final_cost * $amount;
        }

        if($info1000['en_grn']==1){
          $sql = "update warehouse_transaction  set item_cost=item_cost+'$rice_added_cost' where arefer='$grn_id' AND item_id='$c' AND tran_type=26 && deleted=0 ";
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));  
        }
        
        $sql = "update warehouse_transaction  set item_cost=item_cost+'$rice_added_cost' where arefer='$sid' AND item_id='$c' AND tran_type=5 && deleted=0 ";
        $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));  

      }
    }
  }    


}


}


$paid_amount=test_input($_POST['paid_amount']);;
$all_in_one_payment_date = isset($_POST['all_in_one_payment_date']) ? test_input($_POST['all_in_one_payment_date']) : '';
if($inline_form_direct_enabled && $paid_amount>0){
    if((int)$bank <= 0 || (int)$mode <= 0 || $all_in_one_payment_date==''){
        die('All-in-one payment date, bank/cash account, and payment mode are required when paid amount is entered.');
    }
    $payment_entry_date = date('Y-m-d H:i:s', strtotime($all_in_one_payment_date.' '.date('H:i:s', strtotime($date))));
}else{
    $payment_entry_date = $date;
}

$vendor = $vendor_id;




if($paid_amount!=0) {

$sql2 = "Insert into payment_sent

(datetime,vid,bank,mode,amount,details,type)
VALUES ('$payment_entry_date','$vendor_id','$bank','$mode','$paid_amount','$notes','1')" ;

$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));

}


$data20 = mysqli_query($conn,"SELECT max(ref_id) as max from cash_transaction") or die(mysqli_error($conn));
  
$info20 = mysqli_fetch_array( $data20 );
 $ref_id=$info20['max']+1;  


 
 if(1==2)
  {
  

$sql = "Insert into cash_transaction
(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, filesystem_id, company_id, cost_center)
VALUES ('$date','8','$total_amount','$ref_id','$memo', 2, '$sid', '$loginuser','$filesystem_id','$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'];



    

$sql = "Insert into cash_transaction
(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, filesystem_id, company_id, cost_center)
VALUES ('$date','$purchase_account','$total_amount','$ref_id','$memo', 2, '$sid', '$loginuser','$filesystem_id','$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='$purchase_account'  && costcenter_id='$cost_center'  $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


}

if($bank != 0){
$sql = "Insert into cash_transaction
(datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, filesystem_id, company_id, cost_center)
VALUES ('$date','$bank','$paid_amount','$ref_id','$memo', 2, '$sid', '$loginuser','$filesystem_id','$current_company2','$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Update accounts_type Set balance=balance-'$paid_amount' where id='$bank'  && costcenter_id='$cost_center'  $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}


if($info4000['ricecost_cogs']==1 && $arice_charges!=0  && $info4000['en_razik']==0 && $info3000['en_ajk']==0)  {

$ricediscountexpense_account = $info4000['ricediscountexpense_account'];
    
$sql = "Insert into cash_transaction
(datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, filesystem_id, company_id, cost_center )
VALUES ('$date','$ricediscountexpense_account','$rice_charges','$ref_id','$memo', 2, '$sid', '$loginuser','$filesystem_id','$current_company2','$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Update accounts_type Set balance=balance-'$rice_charges' where id='$ricediscountexpense_account'  && costcenter_id='$cost_center'  $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}


if($total_tax!=0 && $info4000['en_razik']==0)
{
$sql = "Insert into cash_transaction
(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, filesystem_id, company_id, cost_center )
VALUES ('$date','$tax_account','$total_tax','$ref_id','$memo', 2, '$sid', '$loginuser','$filesystem_id','$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));

}




    
$sql = "Insert into cash_transaction
(datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, filesystem_id, company_id, cost_center)
VALUES ('$date','$credit_account','$total_amount','$ref_id','$memo', 2, '$sid', '$loginuser','$filesystem_id','$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='$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, $brand_id);    
    
}



$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($info4000['en_vgm']==1){

   
    $ricedata  =mysqli_get_var("SELECT GROUP_CONCAT(a.label,': ',b.value) as rice_data  FROM `rice_field_details` as b ,rice_field as a
  WHERE a.id=b.fid and  b.sid in($sid) and b.stype='6'");
    if ($ricedata!='') {
        $note = mysqli_get_var("select notes from purchasing where id ='$sid'");
        $note = $note.' '.$ricedata;
        $sql = "UPDATE purchasing SET notes = '$note' WHERE id = '$sid'" ;
        $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    }
  }
  


if(! $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 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 Voucher</a>  </div>';
}




 

 
 
 
 
}

 if(isset($_POST['submit2']))
{
    
$pp_id = $_POST['pp_id'];
if($pp_id == "")
{
    $pp_id = 0;
}

$pr_id = $_POST['prid'];
$transporter_id=test_input($_POST['portofdischarge']);
$vendor_id = test_input($_POST['vendor_id']);   
$date = test_input($_POST['date']); 
$pending_amount = test_input($_POST['pending_amount']);

$notes = test_input($_POST['notes']);


$inventory_execution = test_input($_POST['inventory_execution']);   

$salesperson_id = test_input($_POST['salesperson_id']); 


$total_truck = test_input($_POST['total_truck']);   
$company_po_num=test_input($_POST['company_po_num']);



 if(isset($_POST['on_record']))
 { $on_record = mysqli_get_var("Select max(on_record) from po ");  $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;
 }





$total_amount = test_input($_POST['total_amount']); 
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;
    }


$create_time=date("Y-m-d H:i:s");



$filesystem = test_input($_POST['filesystem']);
$filesystem2 = test_input($_POST['filesystem']);



if($filesystem2=='') { $filesystem2=0; }


$cost_center = test_input($_POST['cost_center']);
$service_invoice = test_input($_POST['service_invoice']);


$month_id = mysqli_get_var("Select max(month_id) from po WHERE MONTH(datetime)
 = MONTH('$date') && YEAR(datetime)
 = YEAR('$date')");
 $month_id = $month_id+1;


$dop = test_input($_POST['dop']);   

$payment_terms = $_POST['payment_terms'];
$delivery_terms = $_POST['delivery_terms'];

if($payment_terms=='') $payment_terms = 0;
if($delivery_terms=='') $delivery_terms = 0;

$currency = test_input($_POST['currency']); 
$currency_rate = test_input($_POST['currency_rate']);
$slc_currency_rate = test_input($_POST['slc_currency_rate']);

if($slc_currency_rate=='') $slc_currency_rate = 0;  
    
$currency_total = test_input($total_amount);

$total_amount = test_input($_POST['currency_rate']*$total_amount);
if($po_withoutvalue) {
  $pending_amount = 0;
  $total_amount = 0;
  $currency_total = 0;
  $discount = 0;
  $shipping = 0;
  $tax = 0;
  $atax = 0;
}
$party_id = $_POST['party_id'];
if($party_id == ''){
  $party_id = 0;
}
$purchase_account = $_POST['purchase_account'];
if($purchase_account == '')
    $purchase_account = 19;



 $credit_account  = $_POST['credit_account'];
  $tax_account  = $_POST['tax_account'];    




$file_no = $_POST['file_no'];
if($file_no == '')
    $file_no = 0;

if ($_FILES["file"]["name"]){
    $file_name=$_FILES["file"]["name"];
    $temp_name=$_FILES["file"]["tmp_name"];
    $error = $_FILES["file"]["error"];
    $file_type = $_FILES["file"]["type"];
    $dir = "Purch_order";
    if(!is_dir($dir))
      mkdir($dir);
    
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);
    

    $f_name="purch_order"."".$sid."".$i.".".$ext;
    $target_path = $dir."/".$f_name;
    move_uploaded_file($temp_name, $target_path);

  }



if($info2000['inward_qc'] == 1){
    $inward_qc = 0;
}else{
    $inward_qc = 1;
}



$distributor_to_id = ($_POST['distributor_to_id']) ? $_POST['distributor_to_id'] : 0;
$distributor_from_id = ($_POST['distributor_from_id']) ? $_POST['distributor_from_id']: 0;


if($info3000['en_litmus'] == 1){
   $auto_acknowledge = mysqli_get_var("Select auto_acknowledge from distributor where id='$distributor_to_id' ");
}else
 $auto_acknowledge=0;

// $daily_id = get_max_daily_id("po", $date, 0, $service_invoice, $current_company, $cost_center, $distributor_id);
    $daily_id = get_max_daily_id("po", $hassan_ali_datetime, 0, $service_invoice, $current_company, $cost_center, $distributor_to_id);

$on_record5 = $_POST['on_record5'];

$custom_duties = 1;
if($info3000['en_import_duties'] == 1){
  $custom_duties = 0;
}

if($info4000['en_crimsonfzc']==1){
            
            
          
  $vendor_type = mysqli_get_var("Select type from vendor where id='$vendor_id' ");

$word = "international";


// Test if string contains the word 
if(strpos($vendor_type, $word) !== false){
 $custom_duties = 0;



}else{

$custom_duties = 1;



}


}

if($on_record5=='') { 
$on_record5=0; 

}


if($info4000['en_secondpoapproval']==0) 
{ $approval2 = 1; } 
else { $approval2=0; }


 if($info4000['autopo_approval']==1)    
{ $approval = 1; }  
else { $approval=0; }

$lpo = test_input($_POST['lpo']);

$salesperson_id = test_input($_POST['salesperson_id']);     



$vendor_id2 = $_POST['vendor_id2'];
if($vendor_id2=='') $vendor_id2=0;


$vendor_id3 = $_POST['vendor_id3'];
if($vendor_id3=='') $vendor_id3=0;


//============] MANAGER MUTI LEVEL WORK FOR APPROVALS
$manager_1 = test_input($_POST['manager_1']);
$manager_2 = test_input($_POST['manager_2']);
$manager_3 = test_input($_POST['manager_3']);

if($manager_1=='') $manager_1=0;
if($manager_2=='') $manager_2=0;
if($manager_3=='') $manager_3=0;

if($info3000['multiplemanager_approvals']==1) {
  $approval1 = mysqli_get_var("select level from approval_level where stype = 4 and approval = 1 ");
  if(empty($approval1)){$manager_1=0;}else{
    if($total_amount>=$approval1){}else{$manager_1=0;}
  }
  $approval2 = mysqli_get_var("select level from approval_level where stype = 4 and approval = 2 ");
  if(empty($approval2)){$manager_2=0;}else{
    if($total_amount>=$approval2){}else{$manager_2=0;}
  }
  $approval3 = mysqli_get_var("select level from approval_level where stype = 4 and approval = 3 ");
  if(empty($approval3)){$manager_3=0;}else{
    if($total_amount>=$approval3){}else{$manager_3=0;}
  }
}

// echo "Manager 1: ".$manager_1." - Manager 2: ".$manager_2." Manager 3: ".$manager_3."<br>";
// echo "Total Amount: ".$total_amount."<br>";
// echo "Approval 1: ".$approval1." - Approval 2: ".$approval2." Approval 3: ".$approval3;
// die('');
//============] MANAGER MUTI LEVEL WORK FOR APPROVALS

$slab1_percent = test_input($_POST['slab1_percent']);
if($slab1_percent==''){$slab1_percent=0;}

$slab1_duedate = test_input($_POST['slab1_duedate']);
$slab1_duedate = ($slab1_duedate == '') ? "NULL" : "'$slab1_duedate'";

$slab2_percent = test_input($_POST['slab2_percent']);
if($slab2_percent==''){$slab2_percent=0;}

$slab2_duedate = test_input($_POST['slab2_duedate']);
$slab2_duedate = ($slab2_duedate == '') ? "NULL" : "'$slab2_duedate'";

$slab3_percent = test_input($_POST['slab3_percent']);
if($slab3_percent==''){$slab3_percent=0;}

$slab3_duedate = test_input($_POST['slab3_duedate']);
$slab3_duedate = ($slab3_duedate == '') ? "NULL" : "'$slab3_duedate'";


 $sql2 = "Insert into po
 (shipping, datetime, emp_id,  payment_terms, delivery_terms, vendor_id, vendor_id2, vendor_id3, salesperson_id, total_amount,pending_amount,notes, completed, on_record,serial, serial_date, discount, shipping_charges, tax_applied, inventory_execution, month_id, cost_center, service_invoice, recurring_type, recurring_date, recurring_qty, currency, currency_rate, currency_total, create_time, create_by, dop, filesystem_id, total_truck, party_id, sales_account, credit_account,  tax_account, bwl_file_no, daily_id, company_id, inward_qc,distributor_to_id,distributor_from_id,is_approval_grn, bwl_file_attach,lpo,custom_duties,on_record5,slc_currency_rate,transporter_id, approval, approval2, pp_id, manager_1, manager_2, manager_3, slab1_percent, slab1_duedate, slab2_percent, slab2_duedate, slab3_percent, slab3_duedate)
 VALUES ('$is_shipping','$date','$loginuser','$payment_terms', '$delivery_terms','$vendor_id','$vendor_id2','$vendor_id3','$salesperson_id','$total_amount','$total_amount','$notes',0,'$on_record', '$serial', '$dcdate' , '$discount' , '$shipping', '$atax', '$inventory_execution', '$month_id', '$cost_center', '$service_invoice', '$recurring_type', '$recurring_date', '$recurring_qty','$currency', '$currency_rate', '$currency_total','$create_time','$loginuser', '$dop','$filesystem2','$total_truck', '$party_id', '$purchase_account', '$credit_account', '$tax_account', '$file_no', '$daily_id', '$current_company', '$inward_qc', '$distributor_to_id', '$distributor_from_id', '$auto_acknowledge', '$target_path','$lpo','$custom_duties','$on_record5','$slc_currency_rate','$transporter_id', '$approval', '$approval2', '$pp_id','$manager_1','$manager_2','$manager_3', '$slab1_percent', $slab1_duedate, '$slab2_percent', $slab2_duedate, '$slab3_percent', $slab3_duedate)" ;


// echo $sql2 ;
$retval2 = mysqli_query($conn, $sql2 ) or die(mysqli_error($conn));

    
$data2 = mysqli_query($conn,"SELECT MAX(id) AS id FROM po") or die(mysqli_error($conn));
$info2 = mysqli_fetch_array( $data2 );
$id= $info2['id'];

// work rice field
if (!empty($_POST['fid']) && is_array($_POST['fid'])) {
    for ($kk = 0; $kk < count($_POST['fid']); $kk++) {
        $fid = $_POST['fid'][$kk];
        $values = $_POST['values'][$kk];

        if (!empty($values)) {
            $sql = "INSERT INTO rice_field_details (sid, fid, value, stype)
                    VALUES ('$id', '$fid', '$values', '4')";
            $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
        }
    }
}

$sid= $id;
$rice_len = count(isset($_FILES['riceimage']) ? $_FILES['riceimage'] : [] );
$sql = "SELECT fid,(a.id) as idd,a.stype FROM `rice_field_details` as a ,rice_field as b  where a.fid = b.id and sid ='$sid' and b.itype='5'  and a.stype='4' 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


$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_num!='' || $tr_name!='')
{
$sql25 = "Insert into pshipping

(sid,num,name,qty,datetime, po)
VALUES ('$id','$tr_num','$tr_name','$tr_qty','$tr_date','0')" ;

$retval25 = mysqli_query($conn, $sql25 );
}
    }
}

}
 

 
    
if (isset($_POST['products'])) {
 
 
  for($i=0 ;$i < count($_POST['products']); $i++) {
$c= $_POST['products'][$i];   
$qty=$_POST['products_pcs'][$i];
$description=test_input($_POST['products_description'][$i]);
$smartbatch_enabled = ($info3000['en_smartbatch']==1 && ($info4000['grn_single_batch_qty']==1 || $info3000['open_batchgrn']==1));
$smart_batch_items = array();
$smart_total_qty = 0;
$smart_total_weight = 0;
if($smartbatch_enabled && isset($_POST['smartbatch_data'][$i])) {
  $smart_raw = trim($_POST['smartbatch_data'][$i]);
  if($smart_raw!='') {
    $smart_batches = json_decode($smart_raw, true);
    if(is_array($smart_batches)) {
      $smart_total_weight = 0;
      foreach($smart_batches as $entry) {
        if(!is_array($entry)) { continue; }
        $batch_code = isset($entry['batch']) ? trim($entry['batch']) : '';
        if($batch_code=='') {
          $batch_code = isset($entry['batch_code']) ? trim($entry['batch_code']) : '';
        }
        $batch_qty = isset($entry['qty']) ? floatval($entry['qty']) : 0;
        $batch_weight = isset($entry['weight']) ? floatval($entry['weight']) : 0;
        if($batch_code=='' || $batch_qty<=0) { continue; }
        $smart_total_qty += $batch_qty;
        $smart_total_weight += $batch_weight;
        $smart_batch_items[] = array('batch_code' => $batch_code, 'qty' => $batch_qty, 'weight' => $batch_weight);
      }
      if(!empty($smart_batch_items)) {
        $_POST['custom_field1'][$i] = $smart_total_weight;
      }
    }
  }
}
$custom_field1=$_POST['custom_field1'][$i];
$custom_field2=$_POST['custom_field2'][$i];
$custom_field3=$_POST['custom_field3'][$i];
$custom_field4=$_POST['custom_field4'][$i];
$custom_field5=$_POST['custom_field5'][$i];

if(isset($_POST['products_foc'][$i])) 
{
    $pfoc=$_POST['products_foc'][$i];
}
else 
{
    $pfoc=0;
}

$total=$_POST['products_total'][$i];

$unitcos=$_POST['unitcos'][$i];

$munit=$_POST['munit'][$i];
$con_rate=$_POST['con_rate'][$i];
$munit = ($munit) ? $munit : 0;
$con_rate = ($con_rate) ? $con_rate : 0;


if(isset($_POST['price_slc'][$i]) && $_POST['price_slc'][$i]!='') { $custom_field1=$_POST['price_slc'][$i]; }
if($smartbatch_enabled && count($smart_batch_items)>0) { $custom_field1 = $smart_total_weight; }

$packing2=$_POST['packing2'][$i];

if($packing2 == '')
    $packing2 = 1;

$discount=$_POST['products_discount'][$i];
$packing=$_POST['products_packing'][$i];

$price=$total/$qty;
if($smart_total_qty>0) {
  $qty = $smart_total_qty;
}

if(isset($_POST['products_warehouse'][$i])) {
$pwarehouse=$_POST['products_warehouse'][$i];
}
else {
    $pwarehouse=0;
    }
    

  if($info4000['grn_single_batch_qty']==1) {

if($info1000['batch_with_brand']==1){

// BRAND WORK
if(isset($_POST['batch_brand'][$i]) && $_POST['batch_brand'][$i]!='') {
    
  $batch_brand = $_POST['batch_brand'][$i];
  $brand_count = mysqli_get_var("SELECT COUNT(id) FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");

  if ($brand_count != 0) {
      $batch_brand = mysqli_get_var("SELECT id FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
  } else {
      $sql = "INSERT INTO product_brands (name) VALUES ('$batch_brand')";
      $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));

      $batch_brand = mysqli_get_var("SELECT id FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
  }

} else {
  // IT WILL CHECK IF THERE IS ANY BRAND ON EMPTY '' will get its id else 0
    $batch_brand = $_POST['batch_brand'][$i];
    $brand_count = mysqli_get_var("SELECT COUNT(id) FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
    if ($brand_count != 0) {
      $batch_brand = mysqli_get_var("SELECT id FROM product_brands WHERE LOWER(name) = LOWER('$batch_brand')");
    } else {
      $batch_brand=0;
    }
}
    
// BATCH WITH BRAND
if($smartbatch_enabled && count($smart_batch_items)>0) {
  $pbatch = 0;
}
else if(isset($_POST['products_batch'][$i])) {
    
  $pbatch=$_POST['products_batch'][$i];
  
  $batch1 = mysqli_get_var("Select count(id) from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0 && brand_id = '$batch_brand' "); 
  if($batch1!=0) {
    $pbatch = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0 && brand_id = '$batch_brand' "); 
  } else {
  
  $pexpiry=$_POST['products_expiry'][$i];
  
  $sql = "Insert into inventory_batch
  (batch_code, prd_id, exp_date, brand_id,packing)
  VALUES ('$pbatch','$c','$pexpiry','$batch_brand','$packing')";
  
  $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 && brand_id = '$batch_brand' "); 
    
  }
  

} 

}else{
if($smartbatch_enabled && count($smart_batch_items)>0) {
  $pbatch = 0;
}
else if(isset($_POST['products_batch'][$i])) {
    
    $pbatch=$_POST['products_batch'][$i];
    
    $batch1 = mysqli_get_var("Select count(id) from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0"); 
    if($batch1!=0) {
      $pbatch = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch'  && type_component=0"); 
    } else {
    
    $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 {
   if(isset($_POST['products_batch'][$i])) {
  
  $pbatch=$_POST['products_batch'][$i];
  }
  }  
    if($pbatch==''){$pbatch = 0; }

  // if(isset($_POST['products_batch'][$i])) {


// $pbatch=$_POST['products_batch'][$i];
// $pexpiry=$_POST['products_expiry'][$i];


// if($info4000['en_allbatchdisplay']==1) { 



//   $bval = mysqli_get_var("SELECT id FROM inventory_batch WHERE batch_code IN (Select batch_code from inventory_batch where id = '$pbatch' && type_component=0  ) &&  prd_id='$c' && type_component=0   "); 
     
//   if($bval!='') { $pbatch = $bval; }
// else {   
//  $bval = mysqli_get_var("Select batch_code from inventory_batch where id = '$pbatch'    ");  
//   $sql = "INSERT into inventory_batch (batch_code, prd_id, qty,type_component) VALUES ('$bval','$c',1, 0)  " ;
// $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

//  $pbatch = mysqli_get_var("SELECT id FROM inventory_batch WHERE batch_code IN (Select batch_code from inventory_batch where id = '$pbatch' && type_component=0  ) &&  prd_id='$c' && type_component=0   "); 

// } }
// else {
// $sql = "Insert into inventory_batch
// (batch_code, prd_id, exp_date, type_component)
// VALUES ('$pbatch','$c','$pexpiry',0)";

// $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

// $pbatch = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch' && type_component=0"); 


// }
// }
// else {
//  $pbatch=0;
//  }       

$taxtype=$_POST['taxtype'][$i];
$ptax=$_POST['products_tax'][$i];
$ptax2=$_POST['products_tax2'][$i];
$ptax3=$_POST['products_tax3'][$i];
$aptax=$_POST['products_tax'][$i];


$discount=$_POST['products_discount'][$i];
$discount2=$_POST['products_discount2'][$i];
$discount4=$_POST['products_discount4'][$i];
$discount3=bms_inventory_trade_offer_value($c);
$pscheme=$_POST['products_scheme'][$i];
$pscheme_qty=$_POST['products_scheme_qty'][$i];
$uom=$_POST['uom'][$i];
if($uom == '')
    $uom = 0;

if($discount == '')
    $discount = 0;
if($discount2 == '')
    $discount2 = 0;
if($discount4 == '')
    $discount4 = 0;
if($discount3 == '')
    $discount3 = 0;
    
    
if($pscheme_qty == '')
    $pscheme_qty = 0;   

$mrp_price=$_POST['mrp_price'][$i];
$tax_mrp=$_POST['tax_mrp'][$i];




$rate_in_carton = $_POST['rate_in_carton'][$i]; 
if($rate_in_carton == '')
    $rate_in_carton = 0;

if($po_withoutvalue) {
  $total = 0;
  $unitcos = 0;
  $aptax = 0;
  $ptax = 0;
  $ptax2 = 0;
  $ptax3 = 0;
  $discount = 0;
  $discount2 = 0;
  $discount3 = 0;
  $discount4 = 0;
  $mrp_price = 0;
  $tax_mrp = 0;
  $rate_in_carton = 0;
  $con_rate = 0;
}


if(0==1) {

/*---------------start update price unitcost customfield1 and customfield2--------------*/
$customfields1_mrpprice = mysqli_get_var("SELECT mrp_price FROM inventory where id = '$c' order by id desc limit 1"); 
$customfields2_unitcost = mysqli_get_var("SELECT unit_cost FROM inventory where id = '$c' order by id desc limit 1"); 

$customfields1_mrpprice=($customfields1_mrpprice>0)?$customfields1_mrpprice:$mrp_price;

$sale_price=$_POST['sale_price'][$i];
    
$sql = "UPDATE inventory SET `mrp_price`='$sale_price', `sale_price`='$sale_price' WHERE id = '$c'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    

$mrp_price = $sale_price;   
    
}




if($info4000['en_globalcustomfield']==1){
    $customfields1_mrpprice=$_POST['custom_field1'][$i];
}
      

    if($info4000['rice_standardflow']==1) {
    
    $pbatch = $_POST['brand'][$i];
}

if($info4000['en_metric_ton_qty']==1){

$qty = $qty*$info4000['metric_ton_qty'];
}     

$mrp_price=$_POST['mrp_price'][$i];
$tax_mrp=$_POST['tax_mrp'][$i];



if($mrp_price=='') $mrp_price=0;
if($tax_mrp=='') $tax_mrp=0;

if($po_withoutvalue) {
  $mrp_price = 0;
  $tax_mrp = 0;
}


if($smartbatch_enabled && count($smart_batch_items)>0) {
  $unit_price = ($qty != 0) ? ($total / $qty) : 0;
  foreach($smart_batch_items as $sb_item) {
    $pbatch_code = $sb_item['batch_code'];
    $sb_qty = $sb_item['qty'];
    $pbatch_id = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch_code' && type_component=0");
    if($pbatch_id=='') {
      $pexpiry=$_POST['products_expiry'][$i];
      $sql = "Insert into inventory_batch
      (batch_code, prd_id, exp_date)
      VALUES ('$pbatch_code','$c','$pexpiry')";
      $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
      $pbatch_id = mysqli_get_var("Select id from inventory_batch where prd_id='$c' && batch_code='$pbatch_code' && type_component=0");
    }
    $sb_total = $unit_price * $sb_qty;
    $sb_weight = isset($sb_item['weight']) ? (float)$sb_item['weight'] : 0;
    $sql = "Insert into po_details
    (order_id,prd_id, packing, packing2,prd_amount, `tp`, mrp_price, tax_mrp, custom_field1, custom_field2, custom_field3,custom_field4, custom_field5, custom_field6, discount,discount2,discount3,discount4,scheme,scheme_qty,qty,qty_purchase, tax_applied,tax_applied2,tax_applied3, tax_type,  warehouse_id, batch_id, details2, rate_in_carton, unit, unit_rate, uom, foc)
    VALUES ('$id','$c','$packing','$packing2','$sb_total','$unitcos','$mrp_price', '$tax_mrp','$sb_weight', '$custom_field2','$custom_field3','$custom_field4','$custom_field5','$custom_field6','$discount' ,'$discount2','$discount3','$discount4', '$pscheme', '$pscheme_qty', '$sb_qty','$sb_qty','$aptax','$ptax2','$ptax3', '$taxtype','$pwarehouse', '$pbatch_id', '$description','$rate_in_carton', '$munit','$con_rate', '$uom', '0')";
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  }
} else {
  $sql = "Insert into po_details
  (order_id,prd_id, packing, packing2,prd_amount, `tp`, mrp_price, tax_mrp, custom_field1, custom_field2, custom_field3,custom_field4, custom_field5, custom_field6, discount,discount2,discount3,discount4,scheme,scheme_qty,qty,qty_purchase, tax_applied,tax_applied2,tax_applied3, tax_type,  warehouse_id, batch_id, details2, rate_in_carton, unit, unit_rate, uom, foc)
  VALUES ('$id','$c','$packing','$packing2','$total','$unitcos','$mrp_price', '$tax_mrp','$custom_field1', '$custom_field2','$custom_field3','$custom_field4','$custom_field5','$custom_field6','$discount' ,'$discount2','$discount3','$discount4', '$pscheme', '$pscheme_qty',  '$qty','$qty','$aptax','$ptax2','$ptax3', '$taxtype','$pwarehouse', '$pbatch', '$description','$rate_in_carton', '$munit','$con_rate', '$uom', '$pfoc')";

  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}

if(!$po_withoutvalue) {
  $sql = "UPDATE inventory SET `unit_cost`='$unitcos' WHERE id = '$c'" ;
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}

// Sohail
$sql = "UPDATE pr_details SET qty_purchase= qty_purchase-'$qty' WHERE order_id = '$pr_id' AND prd_id = '$c'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

  }
  
}

// ===================================== Sohail
$data65 = mysqli_query($conn, "SELECT sum(qty_purchase) as Q2 FROM pr_details where order_id='$pr_id'") or die(mysqli_error($conn));
$info65 = mysqli_fetch_array($data65);

if ($info65['Q2']==0) {
    $sql = "update pr set completed='1' where id='$pr_id'";
    $retval = mysqli_query($conn, $sql) or die(mysqli_error($conn));
}



if($info2000['rice_discount']==1 && !$po_withoutvalue) {

if (isset($_POST['rice_discount'])) {
 
 
for($i=0 ;$i < count($_POST['rice_discount']); $i++) {

$c= $_POST['rice_discount'][$i];      
$qty=$_POST['rice_discount_value'][$i];
$toggleclass=$_POST['addclass'][$i];
if($toggleclass==""){
    $toggleclass=0;
}

if($qty!="")
{
    
 $sql25 = "Insert into rice_purchase_discount

(sid,type_id, amount, page,toggleclass)
VALUES ('$id','$c','$qty', 1,'$toggleclass')" ;

$retval25 = mysqli_query($conn, $sql25 );

} } 
} }



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 ID already Exist</div>";
}
else
 { $data10 = mysqli_query($conn,"SELECT MAX(id) AS id FROM po") or die(mysqli_error($conn));
$info10 = mysqli_fetch_array( $data10 );
$sid= $info10['id'];
 


if($info1000['en_pos']==1){    
 $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 '.((isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_label'] : $info4000['purchaseorder_label']).' created successfully.  <a target="_blank" class="btn btn-warning btn-xs" href="'.$info1000['printview_slug'].'print-po.php?sid='.$sid.'">Print Voucher</a>'.($po_withoutvalue ? '' : '  | <a target="_blank" class="btn btn-warning btn-xs" href="'.$info1000['printview_slug'].'print-po-rate.php?sid='.$sid.'">Print Rate Voucher</a>').' </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 '.((isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_label'] : $info4000['purchaseorder_label']).' created successfully.  <a target="_blank" class="btn btn-warning btn-xs" href="'.$info1000['printview_slug'].'print-po.php?sid='.$sid.'">Print Voucher</a> </div>';


}

}




if($info4000['sopo_accounts_hit']==1){
$poid= mysqli_get_var("SELECT max(id) as id from po");
$amount = mysqli_get_var("select SUM(prd_amount) as total from po_details where order_id= '$poid'");
if($amount != 0){
     $memo = $notes;
    ///////////-----------
//  cash transaction entries

$debit = $info4000['po_debit_account_id'];
$credit = $info4000['po_credit_account_id'];



                $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_center2' AND sales_type='1' $serialby_month1  $serialby_year1  ");
                $serial_code++;

    $sql = "Insert into cash_transaction
(datetime, account_id, credit, ref_id, description, transaction_type, arefer, user_id, company_id, filesystem_id,  cost_center )
VALUES ('$date','$credit','$amount','$ref_id','$memo', 34, '$poid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Update accounts_type Set balance=balance-'$amount' where id='$credit' && costcenter_id='$cost_center' $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));



$sql = "Insert into cash_transaction
(datetime, account_id, debit, ref_id, description, transaction_type, arefer, user_id, company_id , filesystem_id,  cost_center )
VALUES ('$date','$debit','$amount','$ref_id','$memo', 34, '$poid', '$loginuser','$current_company2','$filesystem2', '$cost_center')" ;

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

$sql = "Update accounts_type Set balance=balance+'$amount' where id='$debit' && costcenter_id='$cost_center' $caccounts_company ";

$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));



// end cashtransaction 
        
        
    
    
}
}







}



 
  
 
 ?>
 

<?php include('../layout/header.php');

 if(isset($_POST['submit2']) &&  $info2000['en_meskayinventory']==1 && $info2000['meskay_link']!='') {
    
    
    ?><script type="text/javascript">
      

        var date2 = '<?php echo $date; ?>';
        
        var po_id = '<?php echo $sid; ?>';
                
        var supplier_id = '<?php echo $vendor_id; ?>';
        
        var broker_id = '<?php echo $salesperson_id; ?>';
        
        
        var commodity_id = '<?php $commodity_id = mysqli_get_var("Select prd_id from po_details WHERE order_id = '$sid' "); echo $commodity_id ; ?>';


$.ajax
({
type: "POST",
url: "<?php echo $info2000['meskay_link']; ?>/sync-api.php",

data: { po_id : po_id, datetime2 : date2, broker_id : broker_id, supplier_id : supplier_id, commodity_id : commodity_id },
cache: false,
dataType : 'html',
success: function(html)
{


}
});
 

     

</script><?php  }  ?>

<?php include('../layout/sidebar.php'); ?>

 
 <form name="sendmail" method="post"  enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]);?>" 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-->

        <div class="row">
            <div class="col-sm-12">
                <div class="card card-height-100">
                    <div class="card-header">
                      New <?php echo (isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_label'] : $info4000['purchaseorder_label']; ?> &nbsp;&nbsp;&nbsp; (Invoice #: <b><?php if($info3000['en_customdailyid']==1) { 
                  
                  $service_invoice = mysqli_get_var("SELECT id from sales_type where 1=1 && purchase_display=1 $climit_invoicetype  ");
                 
                 echo $daily_id = get_max_daily_id("purchasing", $current_date, 0, $service_invoice, $current_company, $current_costcenter, 0); } else {  $numb = mysqli_get_var("Select max(id) from purchasing");
                                                                        echo $numb + 1; } ?></b> | PO #: <b><?php if($info3000['en_customdailyid']==1) { 
                  
                  $service_invoice = mysqli_get_var("SELECT id from sales_type where 1=1 && purchase_display=1 $climit_invoicetype  ");
                 
                 echo $daily_id = get_max_daily_id("po", $current_date, 0, $service_invoice, $current_company, $current_costcenter, 0); } else {  $numb = mysqli_get_var("Select max(id) from po");
                                                                        echo $numb + 1; } ?></b>)
                        <span class="tools pull-right">
                            <input type="number" style="width:40px; border-radius:5px; border:1px solid #e2e2e4; padding-left:5px; padding-right:5px;" id="totpc" value="0" readonly required /> Total Items &nbsp;&nbsp;&nbsp;
                       <?php if($info2000['en_purchaseservices']==1 ) { 
            ?>      <input name="on_services" type="checkbox" id="on_services" /> Services Purchase  &nbsp; <?php } ?>  <?php if($info2000['en_purchaseassets']==1 ) { 
            ?>      <input name="on_assets" type="checkbox" id="on_assets" />  <?php echo $info2000['assets_label']; ?>  Purchase  &nbsp; <?php } ?> <?php if($info2000['en_purchaserawmaterial']==1 ) { 
            ?>      <input name="on_component" type="checkbox" id="on_component" />  <?php echo $info1000['material_label']; ?> Purchase  &nbsp; <?php } ?> <input name="on_record" <?php  if($info2000['lock_onrecord']==1) { ?> onclick="return false;" <?php } ?>   <?php  if($info2000['fixed_onrecord']==1) { echo 'checked'; } ?> type="checkbox" id="on_record" /> On Record    <a href="javascript:;" class="fa fa-chevron-down"></a>
                            <a href="javascript:;" class="fa fa-cog"></a>
                            <a href="javascript:;" class="fa fa-times"></a>
                         </span>
                    </div>
                    <div class="card-body">
                       <!--Own Text -->
      
       <?php echo $mess; ?>
       <?php if(function_exists('bms_issue_trace_render_summary')) { echo bms_issue_trace_render_summary($issue_trace); } ?>
                       
        <div class="row  align-items-start">

            <!-- <div class="col-12">
        <div class="row">
            <div class="col-md-12">
                <section class="card">
                   
                    <div class="card-body">
                       <div class="row g-3 align-items-end"> -->
<?php if($info2000['en_bwl'] == 1){ ?>                        
    <div class="<?php echo $info3000['formlayout_column'] ;?>">
        <label class="form-label">File No.</label>
        <?php
        $data4 = mysqli_query($conn,"SELECT id, name, custom_code  from bwl_file_system  WHERE 1=1 order by name") or die(mysqli_error($conn)); 
        echo "<select name='file_no' required  id='file_no'  class='file_no reportselect form-control' required   >
        <option value='' >Select File No</option> ";
        while($info4 = mysqli_fetch_array( $data4 )){
            echo "<option value='".$info4['id']."' >".$info4['custom_code']." - ".$info4['name']." </option>";
        }
        echo "</select>";
        ?>
    </div>   
<?php } ?>
    <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if($info2000['en_filesystem']==0) { echo 'style="display:none;"'; } ?> >   
        <label class="form-label d-flex justify-content-between align-items-center">
            <span><?php echo $info2000['filesystem_label']; ?></span>
            <?php if($info3000['en_master_buttonlink']==1 || $inline_form_direct_enabled) { ?> 
                <a href="new-file-system.php" target="_blank" class="text-primary"><i class="fas fa-plus-circle"></i></a> 
            <?php } ?>
        </label>
        <?php
        if(isset($_GET['prid']))
        {
           $prid_val = $_GET['prid'];
           $pr_cc = mysqli_get_var("Select filesystem_id from pr where id = '$prid_val' ");
        }

        $data4 = mysqli_query($conn,"SELECT id, name, custom_code  from file_system  WHERE inactive=0 order by name") or die(mysqli_error($conn)); 

        echo "<select name='filesystem' required  id='filesystem'  class='filesystem reportselect form-control' required   >
        <option value='0' >Select ".$info2000['filesystem_label']."</option> ";
         
          $filesystem = $pr_cc;  $record_check = mysqli_get_var("Select name from file_system where  `id` = '$filesystem' ");
         
        while($info4 = mysqli_fetch_array( $data4 )) 
        {
              
        if($record_check==$info4['name']) {
         echo "<option value='".$info4['id']."' selected >".$info4['name']." | ".$info4['custom_code']." </option>";
        } else {
         echo "<option value='".$info4['id']."' >".$info4['name']." | ".$info4['custom_code']." </option>";
        }
        }

        echo "</select>";
        ?>
    </div>
<?php
 if($info3000['en_snd_purchase']){
   $distributor_from_all = mysqli_get_var("Select distributor_from_all from employee where id='$loginuser' ");  

  ?>

    <div class="<?php echo $info3000['formlayout_column'] ;?>">
      <label class="form-label"><?php echo $info3000['distributer_vendor_label']; ?></label>
     <select name="distributor_from_id" required class="form-control reportselect" id="dist_from_id">
     <?php   if(1) { ?>  <option value=""  selected >Select <?php echo $info3000['distributer_vendor_label']; ?></option> <?php } ?>
     
      <?php
      


        $data2 = mysqli_query($conn,"SELECT * from distributor where id IN (Select did from salesman_reportdistributor where eid='$loginuser' AND type=1) ");
      
        
    while($info2 = mysqli_fetch_array( $data2 )) 
     { 
      ?><option value="<?php echo $info2['id'];?>" ><?php echo $info2['dsrcode']." ".$info2['fname']." ".$info2['lname'].' ('.$info2['company_name'].')';?></option>
      
      <?php 
       }
      ?>
      </select> 
    </div>
    <div class="<?php echo $info3000['formlayout_column'] ;?>">
      <label class="form-label"><?php echo $info3000['distributer_customer_label']; ?></label>
     <select name="distributor_to_id" class="form-control reportselect" id="dist_to_id">
     <?php   if(0) { ?>  <option value="a"  selected >All</option> <?php } ?>
     
      <?php
      
    if($distributor_from_all==1) {
    $data2 = mysqli_query($conn,"SELECT * from distributor");
    }
    else {
    $data2 = mysqli_query($conn,"SELECT * from distributor WHERE 1=1 $limit_current_distributer");
    }
        
    while($info2 = mysqli_fetch_array( $data2 )) 
     { 
      ?><option value="<?php echo $info2['id'];?>" ><?php echo $info2['dsrcode']." ".$info2['fname']." ".$info2['lname'].' ('.$info2['company_name'].')';?></option>
      
      <?php 
       }
      ?>
      </select> 
    </div>

    <!-- Hamza -->
    <input   type="hidden" name="vendor_id"  id="vendor_id" value="0"  />


<?php
 }
   else {
               ?>  
        <div class="<?php echo $info3000['formlayout_column'] ;?>">
        <label class="form-label d-flex justify-content-between align-items-center">
            <span><?php echo $info1000['vendor_label']; ?></span>
        <?php if((int)$info3000['en_quickadd_vendorproduct']===1){ ?>
        <a href="../vendor/new-vendor.php?inline_direct=1" onclick="return bmsOpenInlineDirectPopup(this.href, 'vendorQuickAddWindow');" class="btn btn-sm btn-outline-primary py-0 px-2 ms-1" title="Add <?php echo $info1000['vendor_label']; ?> from this form">+ Add</a>
        <?php } ?>
        </label>
        <?php 
        $vendorid = $_POST['vendor_id'];
           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_id'  required  class='combobox reportselect cid teacher form-control'   >";
        echo "<option value=''>Select a ".$info1000['vendor_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']." ) - ".$info4['custom_code']." </option>"; } else { echo "<option value='".$info4['cid']."' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." ) - ".$info4['custom_code']."</option>"; }
        }

        echo "</select>";

    ?>

    </div>
<?php
    }
?>




    <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if($info2000['en_bwl'] == 0){ echo "style='display:none;'"; } ?> >

    <label class="form-label"><?php echo $info2000['category_label']; ?></label>
<span id="dis" class="d-block">
 <?php $data = mysqli_query($conn, "SELECT id,name from product_type where 1=1 order by name") or die(mysqli_error($conn));
 
echo "<select   tabindex='1'   accesskey='s'  class='combobox form-control catchange cat1'   >";
echo "<option value=''>Select a ".$info2000['category_label']." </option>";
 while($info = mysqli_fetch_array( $data )) 
 { 
   echo "<option value='".$info['id']."' >".$info['sku'].' '.$info['name']."</option>";
}


echo "</select>";

?>
</span>
    </div>


   <div class="<?php echo $info3000['formlayout_column']; ?>" <?php if($info2000['en_bwl'] != 1){ echo "style='display:none;'"; } ?>>
    <label class="form-label"><?php echo $info2000['producttype_label']; ?></label>
    <span id="dis" class="d-block">

        <?php 
        $data = mysqli_query($conn, "SELECT id, name FROM product_ctype ORDER BY name") 
            or die(mysqli_error($conn));

        echo "<select tabindex='1' accesskey='s' class='combobox form-control catchange cat2'>";
        
       
        echo "<option value=''>Select a " . $info2000['producttype_label'] . "</option>";

        while($info = mysqli_fetch_array($data)) { 
            echo "<option value='".$info['id']."'>".$info['name']."</option>";
        }

        echo "</select>";
        ?>
        
    </span>
</div>



    <div class="<?php echo $info3000['formlayout_column'] ;?>"  <?php  if($info1000['en_locations']==0){ echo ' style=" display:none;"';  } ?> >
<label class="form-label"><?php  echo $info2000['location_label']; ?></label>
<select  id='locationfilter' tabindex='3'    class='reportselect form-control'   >";
<option value="">Select <?php echo $info2000['location_label']; ?>..</option>
<?php
         
$data8 = mysqli_query($conn,"SELECT * FROM company_locations  where 1=1  order by id") or die(mysqli_error($conn));

while($info8 = mysqli_fetch_array( $data8 )) 
{
      
echo "<option value='".$info8['id']."'>".$info8['name']."</option>";
 }
?>

</select>

</div>




<?php 

if($info4000['warehousefilter_invoice']==1 || $info3000['customer_warehousetransfer']==1){
?>
    <div class="<?php echo $info3000['formlayout_column'] ;?> warehouse">
        <label class="form-label"><?php if($info3000['customer_warehousetransfer']==1){ echo 'Stock Transfer From'; } else { echo $info2000['warehouse_label']; } ?></label>

<select name='warehousefilter' id='warehousefilter' tabindex='3'    class='reportselect form-control'   >";
<option value="">Select <?php echo $info2000['warehouse_label']; ?>..</option>
<?php
         
$data8 = mysqli_query($conn,"SELECT * FROM inventory_warehouse  where 1=1 && inactive=0 $wlimit_warehouse   $climit_warehouse $iw1  $iw2 order by id") or die(mysqli_error($conn));

while($info8 = mysqli_fetch_array( $data8 )) 
{
      
echo "<option value='".$info8['id']."'>".$info8['name']."</option>";
 }
?>

</select>


</div>
<?php } ?>


<?php
$count_inventory = mysqli_get_var("SELECT COUNT(id) FROM inventory where inactive=0");
$use_ajax_search = 0;
if($count_inventory > 500){
  $use_ajax_search = 1;
}
if(isset($info3000['search_cher']) && (int)$info3000['search_cher'] === 0){
  $use_ajax_search = 0;
}
$stop_query = " AND 1=1";
if($info2000['en_bwl'] == 1 && $use_ajax_search==1){
  $stop_query = " AND 1=2";
}
?>

    <!-- <div class=" brandfilter"> -->

<?php if($info3000['form_categoryfilter'] == 1){ ?>
<!-- <div class="row g-3 mb-2"> -->
  <div class="<?php echo $info3000['formlayout_column'] ;?>">
    <label class="form-label"><?php echo $info2000['category_label']; ?></label>
    <span class="inv-cat-wrap">
      <?php $data = mysqli_query($conn, "SELECT id, name from product_type where 1=1 order by name") or die(mysqli_error($conn));
      echo "<select id='inv_cat' class='combobox reportselect form-control'   >";
      echo "<option value='a' selected>All</option>";
       while($info = mysqli_fetch_array( $data )) 
       { 
         echo "<option value='".$info['id']."' >".$info['sku'].' '.$info['name']."</option>";
      }
      echo "</select>";
      ?>
    </span>
  </div>

  <div class="<?php echo $info3000['formlayout_column'] ;?>">
    <label class="form-label"><?php echo $info2000['subcategory_label']; ?></label>
    <span class="inv-subcat-wrap">
      <?php $data = mysqli_query($conn, "SELECT id, name from product_subtype where 1=1 order by name") or die(mysqli_error($conn));
      echo "<select id='inv_subcat' class='combobox reportselect form-control'   >";
      echo "<option value='a' selected>All</option>";
       while($info = mysqli_fetch_array( $data )) 
       { 
         echo "<option value='".$info['id']."' >".$info['name']."</option>";
      }
      echo "</select>";
      ?>
    </span>
  </div>

  <div class="<?php echo $info3000['formlayout_column'] ;?>">
    <label class="form-label"><?php echo $info2000['subsubcategory_label']; ?></label>
    <span class="inv-subsub-wrap">
      <?php $data = mysqli_query($conn, "SELECT id, name from product_subsubtype where 1=1 order by name") or die(mysqli_error($conn));
      echo "<select id='inv_subsub' class='combobox reportselect form-control'   >";
      echo "<option value='a' selected>All</option>";
       while($info = mysqli_fetch_array( $data )) 
       { 
         echo "<option value='".$info['id']."' >".$info['name']."</option>";
      }
      echo "</select>";
      ?>
    </span>
  </div>
<!-- </div> -->
<?php } ?>

<div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if($info2000['brand_filter']==0 && !brandwise_enabled()) { echo ' style=" display:none;"';} ?>>
  <label class="form-label">Brand</label>
  <span class="inv-brand-wrap">
    <?php
      $bb_brand = "";
      if($en_brand==0) {
        $bb_brand = " && id IN (Select aid from salesman_reportbrand where eid='$loginuser') ";
      }
      $data = mysqli_query($conn, "SELECT id, name from product_brands where 1=1 $bb_brand $climit_productbrand order by name") or die(mysqli_error($conn));
      $selected_inv_brand = isset($_POST['inv_brand']) ? test_input($_POST['inv_brand']) : (isset($_POST['brandfilter']) ? test_input($_POST['brandfilter']) : (isset($_SESSION['brandfilter']) ? test_input($_SESSION['brandfilter']) : 'a'));
      $brand_required = brandwise_enabled() ? " required " : "";
      echo "<select id='inv_brand' name='inv_brand' class='combobox reportselect form-control' $brand_required >";
      echo "<option value='a' ".(($selected_inv_brand=='a' || $selected_inv_brand=='') ? "selected" : "").">Select Brand</option>";
      while($info = mysqli_fetch_array($data))
      {
        $bsel = ($selected_inv_brand == $info['id']) ? " selected " : "";
        echo "<option value='".$info['id']."' $bsel >".$info['name']."</option>";
      }
      echo "</select>";
    ?>
  </span>
</div>

<?php $lock_item_add = ($info2000['en_project']==1); ?>

<div class="<?php echo $info3000['formlayout_column'] ;?>" >
<label class="form-label d-flex justify-content-between align-items-center">
    <span><?php echo 'Search '.$info1000['product_label']; ?></span>
  <?php if((int)$info3000['en_quickadd_vendorproduct']===1){ ?>
  <a href="../products/new-item.php?inline_direct=1" onclick="return bmsOpenInlineDirectPopup(this.href, 'itemQuickAddWindow');" class="btn btn-sm btn-outline-primary py-0 px-2 ms-1" title="Add <?php echo $info1000['product_label']; ?> from this form">+ Add</a>
  <?php } ?>
</label>
<div class="itemchange">
 <?php 
 
   if($en_brand==0) { $bb= " && brand_id IN (Select aid from salesman_reportbrand where eid='$loginuser') ";}
 if($use_ajax_search==0){
  $data = mysqli_query($conn,"SELECT id, name, sku, details, barcode from inventory where inactive=0 $bb $stop_query $climit_product  order by name") or die(mysqli_error($conn));
 }

$lock_attr = $lock_item_add ? " disabled" : "";
$product_search_class = ($use_ajax_search==1) ? "form-control purchase-product-ajax" : "reportselect form-control";
echo "<select name='teacher_id' id='product_search'  accesskey='s'  class='".$product_search_class."' data-minimum-input-length='".((isset($info3000['search_cher']) && (int)$info3000['search_cher'] >= 0 && (int)$info3000['search_cher'] <= 5) ? (int)$info3000['search_cher'] : 0)."'".$lock_attr." >";
echo "<option value=''>Select a ".$info1000['product_label']."...</option>";
if($use_ajax_search==0){
 while($info = mysqli_fetch_array( $data )) 
 { 
 $itemstocka = "";
 if($info4000['itemqty_insearch']==1) { $itemstock=$info['id']; 
 $aqty = mysqli_get_var("SELECT sum(qty) from warehouse_transaction wt, warehouse_transaction_type wtt where type_component=0 && wt.tran_type=wtt.id && (wt.tran_type!=1 || wt.verified_by!=0)  && type=1 && deleted=0   && item_id='$itemstock'  ");


 $lqty = mysqli_get_var("SELECT sum(qty) from warehouse_transaction wt, warehouse_transaction_type wtt where type_component=0 && wt.tran_type=wtt.id && (wt.tran_type!=1 || wt.verified_by!=0)  && type=0 && deleted=0   && item_id='$itemstock'  ");

  
  $itemstocka=$aqty-$lqty;
  
  $itemstocka = " ( Stock: ".$itemstocka." ) ";
  
  }
  if($info3000['en_anastraders']==1) {
    echo "<option value='".$info['id']."' >".$info['barcode'].' '.$info['sku'].' '.$info['name'].(trim($info['details'])!='' ? ' ('.$info['details'].')' : '').$itemstocka."</option>";
  } else {
    echo "<option value='".$info['id']."' >".$info['barcode'].' '.$info['sku'].' '.$info['name'].$itemstocka."</option>";
  }
 }
}


echo "</select>";

?>
</div>
    </div>


    <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if($info4000['rice_standardflow']==0) echo 'style="display:none;"'; ?>>  
<label class="form-label"><?php echo "Purchase Man"; ?></label>
<?php $data4 = mysqli_query($conn,"SELECT *, u.username AS cid,e.id AS aid from vendor e, user u WHERE u.id=e.id  $climit_user  AND u.inactive=0 and en_broker=1 ") or die(mysqli_error($conn)); 

echo "<select name='salesperson_id'   class=' sales_man teacher form-control'   >";

echo "<option  value='0'   >Select Purchaseman </option>";

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 $a =$info4['cid'];
 
   echo "<option  value='".$info4['aid']."' > ".$info4['company_name']."</option>";
   
}

echo "</select>";

?>
</div>



<?php if($info3000['en_master_buttonlink']==1) { ?>
    <div class="col-12 d-flex justify-content-end">
        <a href="#" class="btn btn-success itemchange5"><i class="fas fa-sync"></i></a>
    </div>
<?php } ?>
<!-- </div> -->


                       
                       <!--Own Text End -->
                    <!-- </div>
                </div>
            </div>
        </div>
        </div> -->
        
        
        
        <!-- <div class="col-12">
        <div class="row">
            <div class="col-md-12">
                <div class="card card-height-100">
                   
                    <div class="card-body"> -->
                       <!--Own Text -->
                        <!-- <div class="row g-3 align-items-end detail-grid"> -->
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label">Date</label>
                                <input name="date" type="date" <?php if($info1000['en_backdatedposting']==0) { echo 'max="'.$max_date.'" min="'.$min_date.'"'; } ?> id="date" class="form-control" />
                            </div>
<?php if($info2000['en_extra_party'] == 1){ ?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label">Party Name</label>
                                <?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>";
?>  
                            </div>
<?php } ?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if($info1000['en_barcode']==0) echo 'style="display:none;"'; ?> >
                                <label class="form-label">Scan Barcode</label>
                                <input type="text"  class="form-control"  id="search4" placeholder="Enter Barcode..." <?php echo $lock_item_add ? 'disabled' : ''; ?> />
                            </div>   


 <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if(($info1000['en_salepersondisplay']==0 && $info2000['en_meskayinventory']==0) || $info3000['en_khurram']==1) echo 'style="display:none;"'; ?>>
                                <label class="form-label"><?php echo "Purchaseman"; ?></label>
<?php   if($info4000['rice_standardflow']==1) { $salespersontxtname= "salesperson_id2222"; } else { $salespersontxtname= "salesperson_id";  }  ?>
<?php $data4 = mysqli_query($conn,"SELECT *, u.username AS cid,e.id AS aid from employee e, user u WHERE u.id=e.id  $climit_user  AND u.inactive=0 AND u.id IN (Select eid from salesman_settings) $tsolimit ") or die(mysqli_error($conn)); 

echo "<select name='".$salespersontxtname."'   class=' sales_man teacher form-control'   >";

echo "<option  value='0'   >Select Purchaseman </option>";

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 $a =$info4['cid'];
 if ($a==1)
   echo "<option selected='selected' value='".$info4['aid']."' >".$info4['fname']." ".$info4['lname']."</option>";
   else echo "<option value='".$info4['aid']."' >".$info4['fname']." ".$info4['lname']."</option>";
}

echo "</select>";

?>
                            </div>



                            <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php  if($info2000['custom_onrecord']==0) { echo 'style="display:none;"'; } ?>>
                                <label class="form-label">Invoice #</label>
  <input name="on_record5"  class="form-control"   type="text" id="on_record5"   /> 
                            </div> 


                            <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php  if($info1000['en_servicesales']==0) { echo 'style="display:none;"'; } ?>>

                                <label class="form-label"><?php echo $info3000['sales_type_label'];?></label>
<?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 )) 
 { 
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}

echo "</select>";
 ?>             </div> 



                            <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php  if($info3000['show_item_on_top']==0) { echo 'style="display:none;"'; } ?>>

                                <label class="form-label"><?php echo $info1000['product_label']; ?></label>
<?php $data4 = mysqli_query($conn,"SELECT * from inventory where inactive = 0 ") or die(mysqli_error($conn)); 

$lock_attr = $lock_item_add ? " disabled" : "";
echo "<select name='pp_id' id='pp_id' class='form-control reportselect'".$lock_attr." >";
echo "<option value=''>Select a ".$info1000['product_label']."</option>";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}

echo "</select>";
 ?>
                            </div> 







<?php if($info2000['en_bwl'] == 1){ ?>                        
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
    <label class="form-label">Attach Files</label>
  <input name="file"  tabindex='1' type="file"   id="aFile_upload" class="form-control file_add"/>

</div> 



                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
<label class="form-label">Company PO NO</label>

<input type="text" name="company_po_num" id="company_po_num" class="form-control">
 
 </div> 


<?php } ?>              


   <?php 
   if(isset($_GET['prid']))
   {
       $prid_val = $_GET['prid'];
       $pr_cc = mysqli_get_var("Select cost_center from pr where id = '$prid_val' ");
   }
    $data4 = mysqli_query($conn,"SELECT * from cost_center where active=1 $climit_costcenter $xlimit_costcenter ") or die(mysqli_error($conn)); 
?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
    <label class="form-label"><?php echo $info1000['costcenter_label']; ?></label>
<?php
echo "<select name='cost_center' id='combobox'  class='teacher form-control'  required >";


 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
     if($info4['id'] == $pr_cc)
     {
        echo "<option value='".$info4['id']."' selected>".$info4['name']."</option>";   
     }
     else
     {
        echo "<option value='".$info4['id']."' >".$info4['name']."</option>"; 
     }
}

echo "</select>";

?>
                            </div>

                        <!-- </div> -->

                       
                       <!--Own Text End -->
                    <!-- </div>
                </div>
            </div>
        </div> -->
        <!-- </div> -->
        
        
        <!-- <div class="col-12">
        <div class="row">
            <div class="col-md-12">
                <div class="card card-height-100">
                   
                    <div class="card-body"> -->
                       <!--Own Text -->



    <input name="amount_received" type="hidden"  value="0" id="amount_received" /> 

                        <!-- <div class="row g-3 align-items-end secondary-grid"> -->
<?php if(!($info1000['en_grn']==1 || $info4000['po_dcdate']==0)) { ?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label">DC No.</label>
  <input name="number"  class="form-control"   type="number" id="number"  required value="0" />  
<span id="serial"></span>
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label">DC Date</label>
  <input name="dcdate"  class="form-control"   type="date" id="dcdate" /> 
                            </div>
<?php } ?>

                            <div class="<?php echo $info3000['formlayout_column'] ;?>"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label">Total Amount</label>
 <input name="total"    type="text"      class="total-display form-control" readonly="readonly"/>                         
                            </div>

<?php if (!($info4000['en_razik']==0 && $info3000['vendor_comission']==0)) { ?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label"><?php echo $info3000['vendor2_label']; ?></label>
        <?php 
           if($en_vendor==0) { $vv= " && v.id IN (Select aid from salesman_reportvendor where eid='$loginuser') ";}

         if($info2000['customervendor_same'] == 1)
        {
            $data4 = mysqli_query($conn,"SELECT *, v.id AS cid from customer v, user u WHERE u.id=v.id $vv AND u.inactive=0 $climit_user $climit_zone order by u.company_name") or die(mysqli_error($conn));
        }
        else
        {
            $data4 = mysqli_query($conn,"SELECT *, v.id AS cid from vendor v, user u WHERE u.id=v.id $vv AND u.inactive=0  $vlimit_user $vlimit_zone   order by u.company_name") or die(mysqli_error($conn));    
        }

        echo "<select name='vendor_id2'  required  class=' combobox teacher form-control' >";
    echo "<option value='0'>Select a ".$info3000['vendor2_label']."...</option>";

         while($info4 = mysqli_fetch_array( $data4 )) 
         { 
         if($info4['cid']==$vendorid) { echo "<option value='".$info4['cid']."' selected='selected' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; } else { echo "<option value='".$info4['cid']."' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; }
        }

        echo "</select>";

    
?>
                            </div>
<?php } ?>

<?php if ($info3000['vendor_comission']!=0) { ?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label"><?php echo $info3000['vendor3_label']; ?></label>
  <?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 { echo "<option value='".$info4['cid']."' >".$info4['company_name'].' ( '.$info4['fname']." ".$info4['lname']." )</option>"; }
        }

        echo "</select>";

    
?>
                            </div>
<?php } ?>

<input id="prid" name="prid" type="hidden" value="<?php echo isset($_GET['prid']) ? $_GET['prid'] : 0; ?>" />                         


                            <div class="<?php echo $info3000['formlayout_column'] ;?>" style="<?php  if($info3000['en_ajk']==1) { echo "display:none;"; } ?>"><label class="duebalance" ></label></div>


<?php  if($info4000['selectso_onpo']==1) {  ?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
<label class="form-label"><?php echo $info2000['saleorder_label']; ?></label>
<select class="form-control selectso_onpo"  >
 <option value='0' >Select <?php echo $info2000['saleorder_label']; ?></option> 
<?php  
$result2 = mysqli_query($conn, "SELECT * FROM so WHERE completed=0 && approval!=0 ") or die(mysqli_error($conn));
        
        while($myrow2 = mysqli_fetch_array($result2)){
            $soname = $myrow2['customer_id']; 
 $soname = mysqli_get_var(" Select company_name from `user` where id='$soname' ");
 
   echo "<option value='".$myrow2['id']."' >".$myrow2['id']." ".$myrow2['lpo']." ".date('-m-y ', strtotime($myrow2['datetime']))." ".$soname."</option>";           
            
                    } ?>
           </select>
                            </div>
<?php } ?>

                            <div class="<?php echo $info3000['formlayout_column'] ;?>" style=" <?php  if($info1000['en_lpo']==0) { echo "display:none;"; } ?>">
    
    <label class="form-label"><?php echo $info2000['lpo_label']; ?></label>
    <input name="lpo"  class="form-control"   type="text" id="lpo"  />
            
</div>  
                        <!-- </div> -->



  
   <div <?php if($info3000['en_lowlevelstock_reordering']==0) { echo ' style=" display:none;"';} ?> >
     
     <br />
<br />
<?php if($error==1) {  echo $mess = "<div class='alert alert-danger alert-border-left alert-dismissible fade show'><button type='button' class='btn btn-danger btn-xs'>Alert</button> You uploaded wrong file. kindly reupload</div>"; } ?>

  <label>Upload CSV File</label>

  <table class="table table-bordered table-striped table-condensed">


  <tr>
 <td width="40%">Sample Import File (CSV format)</td> 
  <td><a href="report-stock-status-report.php" >Sample File</a></td> 
  </tr>
  
  

<tr>
                 <td>
Product File </td><td> <input type="file" name="customerfile" accept="text/csv"    /> 
</td>

</tr>







</table>




<br>
<br><input name="create10" type="submit" id="create" class="btn btn-success" value="Upload"  />

</div>
                
        
  
  <div style=" display:none;" <?php if($info2000['en_mastqalandarshipment']==0) { echo ' style=" display:none;"'; } ?> >
 <label>Total Truck(s)</label>
  <input name="total_truck" value="0" type="number"   required   class="form-control" />                         
<br> 
 </div>    
 
 
  <div class="payment_terms_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_terms'   class=' form-control' required >";

if($info2000['en_paymentterms']=="0"){ echo "<option value='0' >Select Payment Terms</option>"; }

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 

   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";

 }
echo "</select>";
 ?>
           
<br> 
 </div>
 
 
  <div  <?php if($info2000['en_shippingterms']=="0" ) { echo ' style=" display:none;"'; } ?> >
 

<label>Delivery Terms</label>

<?php $data4 = mysqli_query($conn,"SELECT * from delivery_terms where 1=1  ") or die(mysqli_error($conn)); 

echo "<select name='delivery_terms'  class=' form-control' required >";

if($info2000['en_shippingterms']=="0"){ echo "<option value='0' >Select Delivery Terms</option>"; }

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 

   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="0" type="number"   required   class="form-control" />                         
 
 </div>


<!-- <div class="row g-3 align-items-end accounts-meta-grid"> -->
    <div class="<?php echo $info3000['formlayout_column'] ;?>"<?php if($info2000['en_ricetrade']==0  && $info4000['salepurchase_accountdynamic']==0  && $info2000['en_appollo']==0) { echo ' style=" display:none;" ';  } ?>>
        <label class="form-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='purchase_account'   class='form-control  reportselect'   >";
        while($info4 = mysqli_fetch_array( $data4 )) { 
            if($info4['id']==$info2000['purchase_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>"; ?>
    </div>
    <div class="<?php echo $info3000['formlayout_column'] ;?>"<?php if($info3000['dynamic_creditaccount']==0) { echo ' style=" display:none;" ';  } ?>>
        <label class="form-label">Credit Account</label>
                    <?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'] == 4)
                            $selected = 'selected';
                        echo "<option value='".$info4['id']."' ".$selected.">".$info4['a_code']." ".$info4['name']."</option>"; 
                      }
                      echo "</select>";
                      ?>
    </div>
    <div class="<?php echo $info3000['formlayout_column'];?>"  <?php if($info3000['dynamic_creditaccount']==0) { echo ' style=" display:none;" ' ;  } ?>>

        <label>Tax Account </label><br>
        <?php $data4 = mysqli_query($conn,"SELECT id, a_code, name  from accounts_type where  1=1  $caccounts_company  group by id, a_code, name  order by a_code ")or die(mysqli_error($conn)); 
            echo "<select name='tax_account' required  class='form-control reportselect'   >";
            echo "<option value='' >Select Tax Account</option>"; 
            while($info4 = mysqli_fetch_array( $data4 )) { 
                $selected = '';
                if($info4['id'] == $info3000['purchasetax_account'])
                    $selected = 'selected';
                echo "<option value='".$info4['id']."' ".$selected.">".$info4['a_code']." ".$info4['name']."</option>"; 
            }
            echo "</select>";
        ?>
    </div>
    <div class="<?php echo $info3000['formlayout_column'] ;?> multi_currency"<?php if($info2000['multi_currency']==0) { echo ' style=" display:none;"';} ?>>
        <label class="form-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['import_selected']==1) {
  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'] ;?> multi_currency"<?php if($info2000['multi_currency']==0) { echo ' style=" display:none;"';} ?>>
        <label class="form-label">Currency Rate</label>
        <div class="currencyfilter"><input type="text" name="currency_rate" class="form-control" value="1" /></div>
    </div>
<!-- </div> -->
 

<div <?php if($info4000['rice_standardflow']==0) echo 'style="display:none;"'; ?>>  
        
 <label>Port Of Discharge</label>   
<select name="portofdischarge" id="portofdischarge" class="form-control portofdischarge">   
        
    <option value="0">Please Select</option>    
<?php   
$sql3="select * from cities where 1=1"; 
$data3=mysqli_query($conn,$sql3);   
while($info3=mysqli_fetch_array($data3))    
  { 
  ?>    
<option value="<?php echo $info3['id'] ?>"> <?php echo $info3['name'] ?></option>   
        
<?php } 
?>  
        
</select>   
<br />
</div>

<?php  if($info3000['en_goodluck']) { ?>
    <br>
  <label>SLC Currency Rate</label>

<div class="slc_currencyfilter"><input type="text" name="slc_currency_rate" class="form-control" value="1" /></div>

</div>  
<?php  } ?>
           
          
      
      
                
               <?php if($info2000['multiple_batch']==1) { ?> 
  <div class="text-right"  > <br>

    <input type="button" value="+ Duplicate Article # " class="form-control tr_clone_add" />  
<br>
</div>

<?php } ?>
                    
         
         
                        
                           <!--Own Text End -->
                    <!-- </div>
                </div>
            </div>
        </div>
        </div>  -->
        

<!-- pk start work -->
<!-- <div class="col-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">
             <div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if($info3000['en_lowlevelstock_reordering']==0) { echo ' style=" display:none;"';} ?> >

<label >Below Stock Level Items</label>
<?php 

echo "<select  id='itemlevel'     class='combobox form-control minchange '   >";
$ii=0;

   echo "<option value='0' >No</option>";
   
     echo "<option value='1' >Yes</option>";

echo "</select>";



?>
</div>


<div class="pos-reorder-filters row g-3 align-items-end" <?php if($info1000['en_pos']==0) echo ' style="display:none;"'; ?>>
<div class="<?php echo $info3000['formlayout_column'] ;?>" >
<label >Reordering Level</label>
<?php 

echo "<select  id='reorderlevel'     class='combobox form-control  minchange '   >";
$ii=0;

   echo "<option value='0' >Minimum Level</option>";
   
     echo "<option value='1' >Maximum Level</option>";
     
    echo "<option value='2' >Manual Entry</option>"; 

echo "</select>";



?>
</div>


<div class="<?php echo $info3000['formlayout_column'] ;?>" >
<label ><?php echo $info1000['vendor_label']; ?> Limit</label>
<?php 

echo "<select  id='vendorlimit'     class='combobox form-control  minchange '   >";
$ii=0;

   echo "<option value='0' >No</option>";
   
     echo "<option value='1' selected='selected' >Yes</option>";
     

echo "</select>";



?>
</div>

<div class="<?php echo $info3000['formlayout_column'] ;?>" >
<label ><?php echo $info1000['product_label']; ?> <?php echo $info2000['producttype_label']; ?></label>
<?php 

echo "<select  id='product_ctype'     class=' form-control combobox  minchange '   >";
$ii=0;

   $data4 = mysqli_query($conn,"SELECT * from product_ctype where 1=1 ") or die(mysqli_error($conn)); 
   
    while($info4 = mysqli_fetch_array( $data4 )) 
 { $ii++;
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}
if ($ii==1) echo "<option value='a' >Select  ".$info2000['producttype_label']." </option>";
else echo "<option value='a' selected>Select  ".$info2000['producttype_label']." </option>";
     

echo "</select>";



?>
</div>



<div class="<?php echo $info3000['formlayout_column'] ;?>" >
<label ><?php echo $info2000['warehouse_label']; ?></label>
<?php 

echo "<select  id='reorderwarehouse'     class='combobox form-control  minchange '   >";
$ii=0;

  $data4 = mysqli_query($conn,"SELECT * from inventory_warehouse where 1=1 $wlimit_warehouse $climit_warehouse ") or die(mysqli_error($conn)); 


     if($info3000['warehousewise_inventorylimit']==1) {
         
         
echo "<option value='a' selected='selected' >All</option>";

     }


 while($info4 = mysqli_fetch_array( $data4 )) 
 { $ii++;
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}


echo "</select>";

     


echo "</select>";



?>
</div>

<div class="<?php echo $info3000['formlayout_column'] ;?>" >
<label >Brand</label>
<?php $data4 = mysqli_query($conn,"SELECT * from product_brands where 1=1 $climit_productbrand") or die(mysqli_error($conn)); 

echo "<select  id='reorderbrand'     class='reportselect combobox form-control  minchange '  multiple  >";
$ii=0;

echo "<option value='a' selected='selected' >All</option>";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { $ii++;
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}


echo "</select>";



?>
</div>

<div class="<?php echo $info3000['formlayout_column'] ;?>" >
<label >Category</label>
<?php $data4 = mysqli_query($conn,"SELECT * from product_type where 1=1 $climit_producttype") or die(mysqli_error($conn)); 

echo "<select  id='reordercategory' multiple   class='reportselect combobox form-control  minchange '   >";
$ii=0;
echo "<option value='a' selected='selected' >All</option>";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { $ii++;
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}



echo "</select>";



?>

</div>
</div> <!-- /.pos-reorder-filters -->
            </div>
                
                
                
                
                    <!-- <div class="row g-3 align-items-end"> -->
<?php
                     
            $result = mysqli_query($conn, "SELECT * from rice_field where  en_purchase = 1   $climit_rice_field && `inventory`=1  AND po = 1 order by orderby ASC ")or die(mysqli_error($conn));
            $count_rows = mysqli_num_rows($result);
            $again = 1;
            if($count_rows > 0){
              $again = 0;
            ?>
<?php
         while($myrow = mysqli_fetch_array($result)){
         $field_id = (int)$myrow['id'];
         $text = 'number';
         $step = ' step="0.0001"';
         $text_name = 'values[]';
         $value = mysqli_get_var("SELECT value FROM rice_field_details WHERE sid = '$id' AND fid = '".$myrow['id']."' AND stype = 6 order by id");
         if($value == ''){
             $value = $myrow['value'];
         }
?>
    <div class="<?php echo $info3000['formlayout_column'] ;?>">
        <label class="form-label"><?php echo $myrow['label']; ?></label>
        <input type="hidden" name="fid[]" value="<?php echo $field_id; ?>">
<?php
         if($myrow['itype'] == 1){
             $text = 'text';
             $step = '';
         } else if($myrow['itype'] == 3){
             $text = 'date';
             $step = '';
         } else if($myrow['itype'] == 10){
             $text = 'time';
             $step = '';
         } else if($myrow['itype'] == 2){
             $value = mysqli_get_var("SELECT value FROM rice_field_details WHERE sid = '$id' AND fid = '".$myrow['id']."' AND stype = 6 order by id");
             if($value == ''){
                 $value = $myrow['value'];
             }
             $str_sel = $myrow['value'];
             $arry_sel = explode("|", $str_sel);
             $text = 'hidden';
             $step = '';
             $text_name = 'values_disabled[]';
?>
        <select class="form-control <?php echo $myrow['class']; ?>" name="values[]" <?php if($myrow['required'] == 1){ echo 'required'; } ?>>
            <option value="" <?php echo ($value=='')?"selected":''; ?>>Select</option>
            <?php foreach($arry_sel as $rice_sel){ ?>
                <option value="<?php echo $rice_sel; ?>" <?php echo ($value==$rice_sel)?'selected':''; ?>><?php echo $rice_sel; ?></option>
            <?php } ?>
        </select>
<?php
         } else if($myrow['itype'] == 4){
             if($value == ''){
                 $value = $myrow['value'];
             }
             $text = 'hidden';
             $step = '';
             $text_name = 'values_disabled[]';
?>
        <textarea class="form-control <?php echo $myrow['class']; ?>" name="values[]" <?php if($myrow['required'] == 1){ echo 'required'; } ?>><?php echo $value; ?></textarea>
<?php
         } else if($myrow['itype'] == 5){
             $rice_id = $myrow['id'];
             if($value == ''){
                 $value = $myrow['value'];
             }
             $text = 'hidden';
             $step = '';
             $text_name = 'values_disabled[]';
?>
        <script>
            (function(){
                const input = document.getElementById('image_<?php echo $myrow['id']; ?>');
                if (input && '<?php echo $value; ?>') {
                    const file = new File(['<?php echo $value; ?>'], '<?php echo $value; ?>', { type: 'text/plain', lastModified: Date.now() });
                    const transfer = new DataTransfer();
                    transfer.items.add(file);
                    input.files = transfer.files;
                }
            })();
            function resetimage(id){
                $(".arrival_image_" + id).html('');
            }
        </script>
        <input type="file" onclick="resetimage(<?php echo $myrow['id']; ?>)" name ="riceimage[]" maxlength="255" id="image_<?php echo $myrow['id']; ?>" class="form-control filess ricefield_image <?php echo $myrow['class']; ?>" value="<?php echo $value; ?>" <?php if($myrow['required'] == 1){ echo 'required'; } ?>>
        <div id="asettext_<?php echo $myrow['id']; ?>">
            <input type="hidden" name="values[]" value="<?php echo ($value=='')?'Not Upload':$value; ?>"/>
            <?php if($value!=''){ ?>
                <span class="arrival_image_<?php echo $myrow['id']; ?>"><img src="ricefield_images/<?php echo $value; ?>" height="150" width="225" class="img-thumbnail" /></span>
            <?php } ?>
        </div>
<?php
         }
?>
        <input type="<?php echo $text; ?>"<?php echo $step; ?> class="form-control <?php echo $myrow['class']; ?>" name="<?php echo $text_name; ?>" value="<?php echo $value; ?>" <?php if($myrow['required'] == 1){ echo 'required'; } ?>>
    </div>
<?php
     }
?>
</div>
<?php
     }
    ?>
                <!-- </div>
            </div>
        </div>
    </div>
</div> -->
 <!-- pk end work --> 
        
        
        <!-- </div> -->
        <!-- /.row -->
        
<div style=" width:100%; clear:both;">

        


<div id="psearch" class="psearch"> </div>

 
<?php
$grnn = 0;
if($info1000['direct_invoicep']==1 || $info2000['batch_grnonly'] == 0) {
        $grnn=1; 
}
?>
 
<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 || $info3000['en_aico']==1) echo ' style="display:none;"';  ?> ><div><?php echo $info3000['qta_avl_label']; ?></div></th>
                 <th <?php if($info3000['en_ajk'] ==0) echo ' style="display:none;"'; ?> >
                      <div>History</div>
                    </th>
                 <th ><div><?php echo $info1000['multi_unit_labela']; ?></div></th>
                 <?php  if($info2000['uom_display']==1) { ?> <th align="center"><?php echo $info2000['uom_label']; ?></th><?php } ?>
                <?php if($info3000['en_goodluck'] == 1){ ?> <th>Weightage</th><?php  } ?> 
                  <th <?php if($info1000['no_purchasepacking']==1 || $info2000['pcs_hidec']==1) echo ' style="display:none;"';  ?>  ><div><?php echo $info1000['single_unit_label']; ?></div></th>
         
   <th <?php if($info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info2000['customfield1c_display'];  ?></div></th>
                            
  <th <?php if($info4000['en_customfield2c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info4000['customfield2c_label'];  ?></div></th>
  <th <?php if($info4000['en_customfield3c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info4000['customfield3c_label'];  ?></div></th>                        
<th <?php if($info3000['en_customfield4c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info3000['customfield4c_label'];  ?></div></th>
                <th <?php if($info3000['en_customfield5c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info3000['customfield5c_label'];  ?></div></th>
                <th <?php if($info3000['en_customfield6c']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info3000['customfield6c_label'];  ?></div></th> 

                              <th <?php if($info3000['en_goodluck']==0 || $info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?> ><div><?php echo $info2000['customfield1c_display'];  ?></div></th>
              <th <?php if($info3000['en_goodluck']==0 || $info2000['en_customfield1c']==0) echo 'style="display:none;"';  ?> ><div><?php echo $info2000['customfield1c_display']." Difference  ";  ?></div></th>

         
               <?php if($info1000['en_warehouse']==1) {  echo  '  <th ><div>'.$info2000['warehouse_label'].'</div></th> '; } ?>
     
      <th <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  ><div>Stock Level</div></th>
       <th <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  ><div>Sale  Price</div></th>
     <th <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  ><div>Margin %</div></th>
     
     <?php if($info1000['en_inventorybatch']==1 && $info1000['batch_with_brand']==1) {  echo  '  <th ><div>Brand</div></th> ';  } ?> 
     <?php 
     if($info1000['en_inventorybatch']==1 && $grnn==1 && $info2000['batch_grnonly'] == 0) {  echo  '  <th ><div>'.$info1000['batch_label'].' </div></th> ';  } ?> 
    
    <?php if($info2000['multiple_batch']==1) {   echo  '  <th ><div>'.$info1000['batch_label'].' </div></th> '; } ?>
    
       <?php if($info1000['en_expirydisplayc']==1 && 1==$info1000['direct_invoicep']) {   echo  '  <th ><div>Expiry </div></th> '; } ?>          
                 <th <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>  ><div><?php echo $info1000['packing_label']; ?></div></th>
                 <th ><div><?php echo $info4000['price_labelp']; ?></div></th>
           <th <?php if($info4000['separate_mrpcolumnp']==0) echo ' style="display:none;"';  ?>  class="recurringhide" ><div><?php echo $info4000['mrp_label']; ?></div></th> 
                  <?php if( $info4000['itemmulti_unit']==1) { 
                    echo '<th ><div>Unit</div></th>
                    <th style="display:none;" ><div>Unit Rate</div></th>'; 
                } ?>
                   <?php  if($info4000['invoice_cartonratep']==1) {  ?>
            <th ><div>Rate Apply</div></th>
            <?php } ?>
               
          
          <th <?php if($info2000['en_ricetrade']==0) echo ' style="display:none;"';  ?> ><div><?php echo $info2000['itemcustomunit_label']; ?></div></th>
          
                      <?php if($info1000['vendor_discount1']==1) {  echo  '  <th ><div>'.$info1000['disc1_label'].'</div></th> '; } ?> 
             <?php if($info1000['vendor_discount2']==1) {  echo  '  <th ><div>'.$info1000['disc2_label'].'</div></th> '; } ?>
               <?php if($info1000['vendor_discount4']==1) {  echo  '  <th ><div>'.$info1000['disc3_label'].'</div></th> '; } ?>   
         
          <?php if($info4000['vendor_foc']==1) {  echo  '  <th ><div>'.$info4000['vendorfoc_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($info4000['invoice_cartonratep']==1) {  ?>
            <th ><div>Pipe Rate</div></th>
            <?php } ?>
        <?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 
 


  
     if($ncart2!='') {
         
         

    // echo "this is ".$ncart2;
             //farhan
           
       $data2 = mysqli_query($conn,"SELECT * from inventory where 1=1 && id IN ($ncart2) ");
  $sub_total=0;     
while($info2 = mysqli_fetch_array( $data2 )) 
 {
     
    
    
     
      ?>
  <tr class="carttr">
  
    <td><input type="hidden" name="products[]" class="products" value="<?php echo $info2['id'];?>"  id="<?php echo "code".$info2['id'];?>" /> <?php echo $info2['sku'].' '.$info2['name'];?>
   
      <input type="hidden" id="<?php echo "pptax".$info2['id'];?>" name="taxtype[]" value="<?php echo $info2['is_taxable'];?>"  />
   <?php if($info1000['en_lastprice']==1) {
         $data200 = mysqli_query($conn,"SELECT sd.* from purchasing_details sd, purchasing s  where sd.prd_id='$sid' AND s.type_component=0 AND sd.`order_id`=s.`id`  order by sd.id DESC Limit 1 ") or die(mysqli_error($conn));
         $info200 = mysqli_fetch_array( $data200 ); 

        }
    else if($info1000['en_lastprice']==2 ) {
        $data200 = mysqli_query($conn,"SELECT sd.* from purchasing_details sd, purchasing s  where sd.prd_id='$sid' AND s.type_component=0 AND sd.`order_id`=s.`id` AND s.vendor_id='$cid' order by sd.id DESC Limit 1 ") or die(mysqli_error($conn));
         $info200 = mysqli_fetch_array( $data200 ); 

      }    ?> 
     <div  <?php if($info1000['item_description']==0) echo ' style="display:none;"';   ?>  >
          <textarea name="products_description[]" class="form-control" placeholder="Details.."></textarea> 
        </div>  
    </td>
    <td class="triggeravailable" <?php if($info1000['hide_qavailable']==1 || $info3000['en_aico']==1 || $type_component == 3) echo ' style="display:none;"';  ?>><?php 
  
    /*if($info2000['qta_inpacking']==0) { $a=' SUM(qty) '; } else { $a=' SUM(qty/packing) '; } 
    $sid = $info2['id'];
    $transfer_in = mysqli_get_var("SELECT $a as sum FROM warehouse_transaction w, warehouse_transaction_type tt WHERE w.item_id='$sid' && w.tran_type=tt.id && tt.type='1'  && w.type_component=0 $wlimit_warehouse8   ");
    $transfer_out = mysqli_get_var("SELECT $a as sum FROM warehouse_transaction w, warehouse_transaction_type tt WHERE w.item_id='$sid' && w.tran_type=tt.id && tt.type='0'   && w.type_component=0 $wlimit_warehouse8  ");
    echo  $product_qta = $transfer_in-$transfer_out;*/

    $sp = mysqli_get_var("SELECT id FROM inventory_warehouse where 1=1 $wlimit_warehouse $climit_warehouse ");
    $stocksingle = $info2['id'];

    if(1) { $a=' SUM(qty) '; } else { $a=' SUM(qty/packing) '; }
    $minus = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=0 && w.deleted=0 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' "); 
    if($info1000['inventory_limit']==1) {
      $minus2 = mysqli_get_var("SELECT $a AS sqty FROM so_details WHERE warehouse_id='$sp' && prd_id='$stocksingle' && order_id IN (SELECT id FROM so WHERE completed=0)  "); 
    }else{
      $minus2 = 0;
    }
    $plus = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=1 && w.deleted=0 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' "); 
    $minus3 = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && w.deleted=0 && (w.tran_type=1 || w.tran_type=21) && verified_by=0 && t.type=1 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' ");
    $product_qta=$plus-$minus-$minus2-$minus3;
    if($info2000['qta_inpacking']==0) {
      echo number_format($product_qta, 2);
    }else{
      $packing5 = mysqli_get_var("SELECT packing FROM inventory WHERE id = '$stocksingle' ");
      echo number_format($product_qta/$packing5, 2);
    }


  
  ?></td>
    <td>
   <input  type="text" <?php if($info2000['multiple_batch']==1) { echo "value='1'  ";  } ?> size="4" min="1"  class="highlight searchp <?php if($info1000['no_purchasepacking']==1) echo ' change5';  ?>  income_count  packing"  id="<?php echo $info2['id'];?>" value="<?php echo $orderqty; ?>" tabindex="1"/></td>
   
   
    <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>> <!--<input type="hidden" name="<?php// echo $info2['id'];?>_packing" id="p<?php// echo $info2['id'];?>" class="searchqty income_count form-control" tabindex="1"  value="<?php// echo $info2['packing'];?>"  /> -->
    
    
     <input type="text" size="4" min="1" value="0"  class="searchqty change change5 income_count totalorder" tabindex="1" id="pcs<?php echo $info2['id'];?>"/> </td>
    
    
     <td <?php if($info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?> ><input name="custom_field1[]"     id="customfield<?php echo $info2['id'];?>" type="text"  tabindex="1" class="form-control custom_field1" /> </td>   
           
     
     
      <?php if($info1000['en_warehouse']==1) { ?>
             <td><?php $data4 = mysqli_query($conn,"SELECT * from inventory_warehouse where 1=1 $wlimit_warehouse $climit_warehouse  ") or die(mysqli_error($conn)); 

echo "<select name='products_warehouse[]' tabindex='1' class='teacher warehouse form-control change6'  >";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 if($info4['id']==$cwarehouse)
{
   echo "<option value='".$info4['id']."' selected='selected' >".$info4['name']."</option>"; 
}
else { 
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}
 }

echo "</select>";

?></td>

<?php } ?>

<td <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  >
      
         Min Qty <b><?php echo $info2['min_qty'];?></b><br>
           Max Qty <b><?php echo $info2['max_qty'];?></b>  
      
      </td>
       <td <?php if($info1000['en_pos']==0) echo ' style="display:none;"';  ?>  >
      
           <input  tabindex="1" name="sale_price[]" type="text"  required class="  <?php if($info1000['open_ratecolumn']==1) { echo 'change15';  } else { echo 'edit-input'; } ?>  income_count  " value="<?php echo $info2['mrp_price'];?>"  size="4"  />
      
      </td>

 <?php if($return==1) { if($info1000['en_inventorybatch']==1 && $grnn==1) { ?>
  <td><?php $pid =  $info2['id']; $data4 = mysqli_query($conn,"SELECT * from inventory_batch where active=1 && prd_id='$pid' && qty>0  && type_component=0 ") or die(mysqli_error($conn)); 
$ii=0;
echo "<select name='products_batch[]' tabindex='1'  class='teacher reportselect batch7 inventory3 change7' required  >";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
if($ii==0) { $maxx = $info4['qty']; $unitc = $info4['unit_cost']; }
 $ii=5;
 
 $batch_code = "";
$batch_code2 = $info4['batch_code'];

if($batch_code2!="") { $batch_code=$batch_code2;} else {
if($info1000['month_code']==1) {  $batch_code= $batch_code.$info1000['invoicecode'];  $batch_code= $batch_code.str_pad($info4['month_id'], 4, '0', STR_PAD_LEFT);  $batch_code= $batch_code.date('-m-y ', strtotime($info4['production_date']));  } else {   $batch_code= $info4['id']; }
}
 
echo "<option value='".$info4['id']."' >".$info4['batch_code']."</option>";
}

echo "</select>";

?><input type="hidden" name="batch_old[]" value="1" /></td>

<?php } } else { ?>


  <?php if($info1000['en_inventorybatch']==1 && $grnn==1) { ?>
  
  
  <td><div class="batchdiv"><input type="text" name="products_batch[]" <?php  if($info2['is_batch']==0) { echo 'readonly';  }?>  value="<?php  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 if($info2000['multiple_batch']==1) { ?>
  <td><input type="text" name="multi_batch[]" value="-" readonly="readonly" /> </td>

<?php } ?>

 <?php  if($info1000['en_expirydisplay']==1 && $grnn==1) {  ?>
     
     <td <?php if($return==1) { echo ' style=" display:none;"'; } ?>><input type="date" name="products_expiry[]" <?php  if($info2['is_batch']==0) { echo 'readonly';  }?> value="" tabindex="1" <?php if($return==0) { ?> required <?php } ?>  class="change8 form-control expiry7" id="<?php echo "expiry".$info2['id'];?>" /></td>
     <?php } ?>
      <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>>
      
      <input name="products_packing[]" type="number" min="0.1" step="0.001" size="4" min="1" class="edit-input change income_count totalorder" id="p<?php echo $info2['id'];?>" tabindex="1"  value="<?php echo $info2['packing'];?>" readonly="readonly" required/>

      </td>
     <td>
                
          <?php
$data15 = mysqli_query($conn,"SELECT vendor_type from vendor where  id='$cid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 


$ttid=$info15['vendor_type'];
$ppid=$info2['id'];



 $data15 = mysqli_query($conn,"SELECT price from vendor_type_pricing where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

 <input id="<?php echo "pp".$info2['id'];?>" tabindex="1" name="unitcos[]" type="text" value="<?php echo $info15['price'];?>" required class="  <?php if($info1000['open_ratecolumn']==1) { echo 'change15';  } else { echo 'edit-input'; } ?>  income_count chk8ange totalorder"  size="4"  />

<?php } elseif($info1000['en_lastprice']!=0 && $info2000['prd_amount']!='') {
  
  $discount=$info2000['discount']/100; 
$discount2=$info2000['discount2']/100; 
$discount4=$info2000['discount4']/100;
// $discount3=$info2['dd3']/100; 
$toffer = $info2000['discount3']*($info2000['qty']-$info2000['scheme_qty']);

$tax= $info2000['tax_applied']/100;
$tax2= $info2000['tax_applied2']/100;
$tax3= $info2000['tax_applied3']/100;


$discount=1-$discount;  
$discount2=1-$discount2;  
//$discount3=1-$discount3; 
$discount4=1-$discount4; 


$aaqty = $info2000['qty']-$info2000['scheme_qty'];

 $sb = $info2000['prd_amount'];
 $n = $info2000['qty'] * ($tax + $tax2 + $tax3);
$m = $aaqty * $discount * $discount2 * $discount4;

$nm = $n + $m ;
$x = ($info2000['prd_amount'] +($toffer*$discount*$discount2*$discount4)  ) / $nm;



$price= $x;
    ?>
 <input id="<?php echo "pp".$info2['id'];?>" tabindex="1" name="unitcos[]" type="text" value="<?php echo $price;?>" required class="  <?php if($info1000['open_ratecolumn']==1) { echo 'change15';  } else { echo 'edit-input'; } ?>  income_count chk8ange totalorder"  size="4" />
<?php }
else {  ?>
 <input id="<?php echo "pp".$info2['id'];?>" tabindex="1" name="unitcos[]" type="text" required  value="<?php echo $info2['unit_cost'];?>" class="  <?php if($info1000['open_ratecolumn']==1) { echo 'change15';  } else { echo 'edit-input'; } ?>  income_count chk8ange totalorder"  size="4" />
<?php } ?>
         
   
          

<input name="packing2[]" type="hidden" step="0.0001" class='teacher income_count' value="1" id="<?php echo "packk".$info2['id'];?>" />

<input type="hidden" name="discount5[]" value="0" id="<?php echo "pppl".$info2['id'];?>"  tabindex="1"  class="edit-input income_count"   size="4"   /> 


             
        </td>



 <td <?php  if($info4000['invoice_cartonratep']==0) { echo ' style=" display:none;"'; } ?>>
                
           
 <select name='rate_in_carton[]' class='teacher income_count'  id="<?php echo "ric".$info2['id'];?>"  >
 <option value='0' >Default</option>
 <option value='1' ><?php echo $info1000['packing_label']; ?></option>
 <option value='2' ><?php echo $info1000['multi_unit_label']; ?></option>
 <option value='3' ><?php echo $info2000['customfield1_display'];  ?></option>
 </select>
            </td>         
        

              
           <td <?php  if($info2000['en_ricetrade']==0) { echo ' style=" display:none;"'; } ?> ><input name="packing2[]" type="number" step="0.0001" class='teacher income_count'  value="<?php echo (isset($info2['pac2']) && $info2['pac2'] !== '' ? $info2['pac2'] : 0); ?>"  id="<?php echo "packk".$info2['id'];?>"   required/> </td>      

 <?php if($info1000['vendor_discount1']==1) { 
 echo '<td >';
$bid=$info2['brand_id'];
 $data15 = mysqli_query($conn,"SELECT discount from vb_discount where vid='$cid' AND bid='$bid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);


$data17 = mysqli_query($conn,"SELECT discount from vendor_type_discount1 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info17 = mysqli_fetch_array( $data17 ); 

$num_rows2 = mysqli_num_rows($data17);


if($num_rows!=0) {
?>
<input name="products_discount[]" type="number" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['discount'];?>" size="4"  required/>

<?php }
else if($num_rows2!=0) {
?>
<input name="products_discount[]" type="number" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info17['discount'];?>" size="4"  required/>

<?php }  else if($info1000['en_lastprice']==1 && $info2000['discount']!='') { ?>

<input name="products_discount[]"  type="number" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['discount'];?>" size="4"  required/>


 <?php }
 else {  ?>
<input name="products_discount[]"  type="number" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"  tabindex="1"  value="0" size="4"  required/>
<?php } echo '</td>'; } 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) { 
 
$data15 = mysqli_query($conn,"SELECT discount from vendor_type_discount2 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input name="products_discount2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppn".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['discount'];?>" size="4" /></td>
<?php }
elseif($info1000['en_lastprice']==1 && $info2000['discount2']!='') { ?>

<td><input name="products_discount2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppn".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['discount2'];?>" size="4" /></td>

 <?php }
 else {  ?>

<td><input name="products_discount2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppn".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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) { 
 
$data15 = mysqli_query($conn,"SELECT discount from vendor_type_discount4 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input name="products_discount4[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppx".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['discount'];?>" size="4" /></td>
<?php }
else if($info1000['en_lastprice']==1 && $info2000['discount4']!='') { ?>

<td><input name="products_discount4[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppx".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['discount4'];?>" size="4" /></td>

 <?php }
 else {  ?>

<td><input name="products_discount4[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppx".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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  ) { 
  $foc = mysqli_get_var("SELECT discount_percentage FROM amount_discountp where min_amount='$sid' ");
  $foc_value = mysqli_get_var("SELECT discount_value FROM amount_discountp where min_amount='$sid' ");
  if($foc=="") {  $foc=0; }
  if($foc_value=="") {  $foc_value=0; }
 ?>
                    <td>
                        <input type="number" name="products_foc[]" class="gggg form-control foc income_count a1" id="<?php echo "pfoc".$info2['id'];?>" required size="4" value="0" />
                        <input type="hidden" class="foc_scheme" id="<?php echo "pfoc_scheme".$info2['id'];?>" value="<?php echo $foc; ?>" />
                        <input type="hidden" class="foc_value" id="<?php echo "pfoc_value".$info2['id'];?>" value="<?php echo $foc_value; ?>" />
                    </td>
                    <?php } 

else { 
    ?>
                    <input type="hidden" name="products_foc[]" value="0" class="foc income_count a2"
                        id="<?php echo "pfoc".$info2['id'];?>" required size="4" />
                    <?php }
 
  if($info1000['vendor_discount3']==1) { 
$data15 = mysqli_query($conn,"SELECT discount from vendor_type_discount3 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input name="products_discount3[]" type="text" class="edit-input income_count totalorder products_discount3" id="<?php echo "pppm".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['discount'];?>" size="4" /></td>
<?php } else if($info1000['en_lastprice']==1 && $info2000['discount3']!='') {?>

<td><input name="products_discount3[]" type="text" class="edit-input income_count totalorder products_discount3" id="<?php echo "pppm".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['discount3'];?>" size="4" /></td>


<?php }  else {  ?>

<td><input name="products_discount3[]" type="text" class="edit-input income_count totalorder products_discount3" id="<?php echo "pppm".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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) { 
$data15 = mysqli_query($conn,"SELECT scheme from vendor_type_scheme where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input  name="products_scheme[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['scheme'];?>" size="4" />
</td>
<?php } else if($info1000['en_lastprice']==1 && $info2000['scheme']!='') { ?>

<td><input name="products_scheme[]"  type="text" class="edit-input income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['scheme'];?>" size="4" /></td>

<?php } else {  ?>

<td><input  name="products_scheme[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></td>
<?php } } else { ?>

<input name="products_scheme[]"  type="hidden" class="edit-input income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></td>

<?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 $info15['scheme'];?>" size="4" /> <input  name="products_pcs[]" type="text" size="4" min="1" class="edit-input total_pcs" id="<?php echo "t".$info2['id'];?>" readonly="readonly" /></td>
  
  <?php if(1==1){   ?>     
     <td  <?php if($info4000['display_taxamount']==0){ echo ' style="display:none;"';    }  ?> >
   <input name="display_totaltax2[]" type="text" class="income_count display_totaltax2" id="<?php echo "ppptttt".$info2['id'];?>"    value="0" size="4" readonly/>
</td>
<?php } ?>

   <?php if($info1000['vendor_tax1']==1) { 
$data15 = mysqli_query($conn,"SELECT tax from vendor_type_tax1 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($info2000['en_maintaxc']==1) {
?>

  <td ><input name="products_tax[]" type="number" class="edit-input income_count test" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($st==1) {  if($cfiler==1) { echo $info2000['filer_taxc']; } else { echo $info2000['nonfiler_taxc']; }  } else { echo 0; } ?>" size="4" readonly="readonly"  required/></td>

<?php }
else if($num_rows!=0) {
?>

  <td ><input name="products_tax[]" type="number" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1 && $st==1) { echo $info15['tax']; } else { echo 0;}?>" size="4" readonly="readonly"  required/></td>

<?php } elseif($info1000['en_lastprice']==1 && $info2000['tax_applied']!='') { ?>

 <td>     <input name="products_tax[]" type="number" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1) { echo $info2000['tax_applied']; } else { echo 0;}?>" size="4"   required/></td>
   
   
 <?php } else {  ?>

  <td ><input name="products_tax[]" type="number" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1 && $st==1) { echo 0; } else { echo 0;}?>" size="4" readonly="readonly"  required/></td>


<?php } } else { ?>

      <input name="products_tax[]" type="hidden" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1 && $st==1) { echo 0; } else { echo 0;}?>" size="4" readonly="readonly" /></td>
   
   <?php } ?>

 <td <?php if($info4000['invoice_cartonratep']==0) { echo ' style=" display:none;" '; } ?>  ><input  type="text" class="edit-input income_count" tabindex="1" id="<?php echo "pipe".$info2['id'];?>" value="<?php  echo 0; ?>" size="4" readonly="readonly" /></td>

   
 <?php  if($info1000['vendor_tax2']==1) { 
 
$data15 = mysqli_query($conn,"SELECT tax from vendor_type_tax2 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input name="products_tax2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppptt".$info2['id'];?>"  tabindex="1"  value="<?php if($info1000['en_tax']==1 && $st==1) { echo $info15['tax']; } else { echo 0;}?>" size="4" /></td>
<?php } 
else if($info1000['en_lastprice']==1 && $info2000['tax_applied2']!='') { ?>
<td><input name="products_tax2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppptt".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['tax_applied2']; ?>" size="4" /></td>

 <?php } else {  ?>

<td><input name="products_tax2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppptt".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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" /></td>

 <?php } if($info1000['vendor_tax3']==1) { 
$data15 = mysqli_query($conn,"SELECT tax from vendor_type_tax3 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {

?>

<td><input name="products_tax3[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppttt".$info2['id'];?>"  tabindex="1"  value="<?php if($info1000['en_tax']==1 && $st==1) { echo $info15['tax']; } else { echo 0;}?>" size="4" /></td>
<?php } else if($info1000['en_lastprice']==1 && $info2000['tax_applied3']!='') { ?>

<td><input name="products_tax3[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppttt".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['tax_applied3']; ?>" size="4" /></td>

 <?php }  else {  ?>

<td><input name="products_tax3[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppttt".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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" /></td>

 <?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[]" type="number" size="5"  class="<?php echo $info2['id'];?> ptotal sub_total readonly" id="newtotal<?php echo $info2['id'];?>" tabindex = "-1" min="0" onkeypress="return false;"   required value="0"/></td>
               <td><?php
               $smart_last_batch_number = mysqli_get_var("SELECT MAX(CAST(batch_code AS UNSIGNED)) FROM inventory_batch WHERE prd_id='".$info2['id']."' AND type_component=0 AND batch_code REGEXP '^[0-9]+$'");
               if($smart_last_batch_number=='') { $smart_last_batch_number = 0; }
               if($info3000['en_smartbatch']==1 && ($info4000['grn_single_batch_qty']==1 || $info3000['open_batchgrn']==1)) { ?>
                <div <?php if($info2['is_batch'] != 1){ echo "class='hide'"; } ?> style="display:inline-block; margin-right:6px;">
                  <button type="button" class="btn btn-default btn-sm smartbatch-open" data-item="<?php echo htmlspecialchars($info2['sku'].' '.$info2['name']); ?>" data-lastbatch="<?php echo (int)$smart_last_batch_number; ?>">+</button>
                  <span class="smartbatch-view text-muted" style="display:none;"></span>
                </div>
                <input type="hidden" name="smartbatch_data[]" class="smartbatch-data" value="" />
               <?php } else { ?>
                <input type="hidden" name="smartbatch_data[]" class="smartbatch-data" value="" />
               <?php } ?><?php if(1==1) { ?><input type="button" class="edit receipt_edit_hide5" value="Edit" /><input type="button" class="save" value="Save" /><?php } ?><?php if(1==1) { ?><input type="button" class="delete receipt_delete_edit5" value="Delete" /><?php } ?></td> 
                
      </tr>
            <?php } 
            
     }
         
         
     
     
     
     
 if(isset($_POST['create10']) && $error==0)
{    


if(file_exists($_FILES['customerfile']['tmp_name']) || is_uploaded_file($_FILES['customerfile']['tmp_name'])) {
   
    

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['customerfile']['type'],$mimes)){
    
    
  
 $csvFile = fopen($_FILES['customerfile']['tmp_name'], 'r');
            
            //skip first line
            fgetcsv($csvFile);
 
 
 while(($line = fgetcsv($csvFile)) !== FALSE){
     
     $countv = count($line);


if($countv ==9 || $countv ==1)
{

  
  
$reorderlevel=test_input($_POST['pdemand']);

$vendorid=test_input($_POST['vendorid']);


$itemlevel=test_input($_POST['itemlevel']);
$reorderwarehouse=test_input($_POST['reorderwarehouse']);

$reorderbrand=test_input($_POST['reorderbrand']);

$reordercategory=test_input($_POST['reordercategory']);

$vendorlimit = test_input($_POST['vendorlimit']);

if($vendorlimit=='0') { 
$vendorlimit2=" && 1=1  ";  }
else {
  
$vendorlimit2=" && vendor_id='$vendorid'  ";  
  }
  
if($reorderwarehouse=='a')
{
$reorderwarehouse2=" AND 1=1    ";    }
else {
  
$reorderwarehouse2="  AND warehouse_id='$reorderwarehouse'   "; 
  } 


if($reorderfilter=='n')
{
$aaa=" AND qty<min_qty    ";    }
else {
  
$aaa="  AND qty<min_qty   "; 
  } 
  
  
 
if ($reorderbrand=='a')
{
$reorderbrand2=" ";
}
else
{
    
$reorderbrand = str_replace("a, "," ",$reorderbrand);   
$reorderbrand2=" AND brand_id IN ($reorderbrand) ";
}


if ($reordercategory=='a')
{
$reordercategory2=" ";
}
else
{
    
$reordercategory = str_replace("a, "," ",$reordercategory); 
$reordercategory2=" AND type_id IN ($reordercategory) ";
} 


$vendorid = $_POST['vendor_id'];

$cwarehouse = mysqli_get_var("Select inventory_warehouse from vendor where `id` = '$vendorid'");


$item2 = test_input($line[1]);

$orderqty = test_input($line[8]);

   ?>



                
           
       <?php  $data2 = mysqli_query($conn,"SELECT * from inventory where 1=1 && id='$item2' ");
  $sub_total=0;     
while($info2 = mysqli_fetch_array( $data2 )) 
 {
     
    
    
     
      ?>
  <tr class="carttr">
  
    <td><input type="hidden" name="products[]" class="products" value="<?php echo $info2['id'];?>"  id="<?php echo "code".$info2['id'];?>" /> <?php echo $info2['sku'].' '.$info2['name'];?>
   
      <input type="hidden" id="<?php echo "pptax".$info2['id'];?>" name="taxtype[]" value="<?php echo $info2['is_taxable'];?>"  />
   <?php if($info1000['en_lastprice']==1) {
         $data200 = mysqli_query($conn,"SELECT sd.* from purchasing_details sd, purchasing s  where sd.prd_id='$sid' AND s.type_component=0 AND sd.`order_id`=s.`id`  order by sd.id DESC Limit 1 ") or die(mysqli_error($conn));
         $info200 = mysqli_fetch_array( $data200 ); 

        }
    else if($info1000['en_lastprice']==2 ) {
        $data200 = mysqli_query($conn,"SELECT sd.* from purchasing_details sd, purchasing s  where sd.prd_id='$sid' AND s.type_component=0 AND sd.`order_id`=s.`id` AND s.vendor_id='$cid' order by sd.id DESC Limit 1 ") or die(mysqli_error($conn));
         $info200 = mysqli_fetch_array( $data200 ); 

      }    ?> 
     <div  <?php if($info1000['item_description']==0) echo ' style="display:none;"';   ?>  >
          <textarea name="products_description[]" class="form-control" placeholder="Details.."></textarea> 
        </div>  
    </td>
    <td class="triggeravailable" <?php if($info1000['hide_qavailable']==1 || $info3000['en_aico']==1 || $type_component == 3) echo ' style="display:none;"';  ?>><?php 
  
    /*if($info2000['qta_inpacking']==0) { $a=' SUM(qty) '; } else { $a=' SUM(qty/packing) '; } 
    $sid = $info2['id'];
    $transfer_in = mysqli_get_var("SELECT $a as sum FROM warehouse_transaction w, warehouse_transaction_type tt WHERE w.item_id='$sid' && w.tran_type=tt.id && tt.type='1'  && w.type_component=0 $wlimit_warehouse8   ");
    $transfer_out = mysqli_get_var("SELECT $a as sum FROM warehouse_transaction w, warehouse_transaction_type tt WHERE w.item_id='$sid' && w.tran_type=tt.id && tt.type='0'   && w.type_component=0 $wlimit_warehouse8  ");
    echo  $product_qta = $transfer_in-$transfer_out;*/

    $sp = mysqli_get_var("SELECT id FROM inventory_warehouse where 1=1 $wlimit_warehouse $climit_warehouse ");
    $stocksingle = $info2['id'];

    if(1) { $a=' SUM(qty) '; } else { $a=' SUM(qty/packing) '; }
    $minus = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=0 && w.deleted=0 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' "); 
    if($info1000['inventory_limit']==1) {
      $minus2 = mysqli_get_var("SELECT $a AS sqty FROM so_details WHERE warehouse_id='$sp' && prd_id='$stocksingle' && order_id IN (SELECT id FROM so WHERE completed=0)  "); 
    }else{
      $minus2 = 0;
    }
    $plus = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=1 && w.deleted=0 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' "); 
    $minus3 = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && w.deleted=0 && (w.tran_type=1 || w.tran_type=21) && verified_by=0 && t.type=1 &&  `item_id` = '$stocksingle' &&  `warehouse_id` = '$sp' ");
    $product_qta=$plus-$minus-$minus2-$minus3;
    if($info2000['qta_inpacking']==0) {
      echo number_format($product_qta, 2);
    }else{
      $packing5 = mysqli_get_var("SELECT packing FROM inventory WHERE id = '$stocksingle' ");
      echo number_format($product_qta/$packing5, 2);
    }


  
  ?></td>
    <td>
   <input  type="text" <?php if($info2000['multiple_batch']==1) { echo "value='1'  ";  } ?> size="4" min="1"  class="highlight searchp <?php if($info1000['no_purchasepacking']==1) echo ' change5';  ?>  income_count  packing"  id="<?php echo $info2['id'];?>" value="<?php echo $orderqty; ?>" tabindex="1"/></td>
   
   
    <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>> <!--<input type="hidden" name="<?php// echo $info2['id'];?>_packing" id="p<?php// echo $info2['id'];?>" class="searchqty income_count form-control" tabindex="1"  value="<?php// echo $info2['packing'];?>"  /> -->
    
    
     <input type="text" size="4" min="1" value="0"  class="searchqty change change5 income_count totalorder" tabindex="1" id="pcs<?php echo $info2['id'];?>"/> </td>
    
    
     <td <?php if($info2000['en_customfield1c']==0) echo ' style="display:none;"';  ?> ><input name="custom_field1[]"     id="customfield<?php echo $info2['id'];?>" type="text"  tabindex="1" class="form-control custom_field1" /> </td>   
           
     
     
      <?php if($info1000['en_warehouse']==1) { ?>
             <td><?php $data4 = mysqli_query($conn,"SELECT * from inventory_warehouse where 1=1 $wlimit_warehouse $climit_warehouse  ") or die(mysqli_error($conn)); 

echo "<select name='products_warehouse[]' tabindex='1' class='teacher warehouse form-control change6'  >";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 if($info4['id']==$cwarehouse)
{
   echo "<option value='".$info4['id']."' selected='selected' >".$info4['name']."</option>"; 
}
else { 
   echo "<option value='".$info4['id']."' >".$info4['name']."</option>";
}
 }

echo "</select>";

?></td>

<?php } ?>

 <?php if($return==1) { if($info1000['en_inventorybatch']==1 && $grnn==1) { ?>
  <td><?php $pid =  $info2['id']; $data4 = mysqli_query($conn,"SELECT * from inventory_batch where active=1 && prd_id='$pid' && qty>0  && type_component=0 ") or die(mysqli_error($conn)); 
$ii=0;
echo "<select name='products_batch[]' tabindex='1'  class='teacher reportselect batch7 inventory3 change7' required  >";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
if($ii==0) { $maxx = $info4['qty']; $unitc = $info4['unit_cost']; }
 $ii=5;
 
 $batch_code = "";
$batch_code2 = $info4['batch_code'];

if($batch_code2!="") { $batch_code=$batch_code2;} else {
if($info1000['month_code']==1) {  $batch_code= $batch_code.$info1000['invoicecode'];  $batch_code= $batch_code.str_pad($info4['month_id'], 4, '0', STR_PAD_LEFT);  $batch_code= $batch_code.date('-m-y ', strtotime($info4['production_date']));  } else {   $batch_code= $info4['id']; }
}
 
echo "<option value='".$info4['id']."' >".$info4['batch_code']."</option>";
}

echo "</select>";

?><input type="hidden" name="batch_old[]" value="1" /></td>

<?php } } else { ?>


  <?php if($info1000['en_inventorybatch']==1 && $grnn==1) { ?>
  
  
  <td><div class="batchdiv"><input type="text" name="products_batch[]" <?php  if($info2['is_batch']==0) { echo 'readonly';  }?>  value="<?php  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 if($info2000['multiple_batch']==1) { ?>
  <td><input type="text" name="multi_batch[]" value="-" readonly="readonly" /> </td>

<?php } ?>

 <?php  if($info1000['en_expirydisplay']==1 && $grnn==1) {  ?>
     
     <td <?php if($return==1) { echo ' style=" display:none;"'; } ?>><input type="date" name="products_expiry[]" <?php  if($info2['is_batch']==0) { echo 'readonly';  }?> value="" tabindex="1" <?php if($return==0) { ?> required <?php } ?>  class="change8 form-control expiry7" id="<?php echo "expiry".$info2['id'];?>" /></td>
     <?php } ?>
      <td <?php if($info1000['no_purchasepacking']==1) echo ' style="display:none;"';  ?>>
      
      <input name="products_packing[]" type="number" min="0.1" step="0.001" size="4" min="1" class="edit-input change income_count totalorder" id="p<?php echo $info2['id'];?>" tabindex="1"  value="<?php echo $info2['packing'];?>" readonly="readonly" required/>
  <input name="products_packing2[]" type="hidden" class="edit-input change income_count totalorder" id="pack2<?php echo $info2['id'];?>" tabindex="1"  value="<?php echo $info2['packing2'];?>" />

      </td>
     <td>
                
          <?php
$data15 = mysqli_query($conn,"SELECT vendor_type from vendor where  id='$cid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 


$ttid=$info15['vendor_type'];
$ppid=$info2['id'];



 $data15 = mysqli_query($conn,"SELECT price from vendor_type_pricing where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

 <input id="<?php echo "pp".$info2['id'];?>" tabindex="1" name="unitcos[]" type="text" value="<?php echo $info15['price'];?>" required class="  <?php if($info1000['open_ratecolumn']==1) { echo 'change15';  } else { echo 'edit-input'; } ?>  income_count chk8ange totalorder"  size="4"  />

<?php } elseif($info1000['en_lastprice']!=0 && $info2000['prd_amount']!='') {
  
  $discount=$info2000['discount']/100; 
$discount2=$info2000['discount2']/100; 
$discount4=$info2000['discount4']/100;
// $discount3=$info2['dd3']/100; 
$toffer = $info2000['discount3']*($info2000['qty']-$info2000['scheme_qty']);

$tax= $info2000['tax_applied']/100;
$tax2= $info2000['tax_applied2']/100;
$tax3= $info2000['tax_applied3']/100;


$discount=1-$discount;  
$discount2=1-$discount2;  
//$discount3=1-$discount3; 
$discount4=1-$discount4; 


$aaqty = $info2000['qty']-$info2000['scheme_qty'];

 $sb = $info2000['prd_amount'];
 $n = $info2000['qty'] * ($tax + $tax2 + $tax3);
$m = $aaqty * $discount * $discount2 * $discount4;

$nm = $n + $m ;
$x = ($info2000['prd_amount'] +($toffer*$discount*$discount2*$discount4)  ) / $nm;



$price= $x;
    ?>
 <input id="<?php echo "pp".$info2['id'];?>" tabindex="1" name="unitcos[]" type="text" value="<?php echo $price;?>" required class="  <?php if($info1000['open_ratecolumn']==1) { echo 'change15';  } else { echo 'edit-input'; } ?>  income_count chk8ange totalorder"  size="4" />
<?php }
else {  ?>
 <input id="<?php echo "pp".$info2['id'];?>" tabindex="1" name="unitcos[]" type="text" required  value="<?php echo $info2['unit_cost'];?>" class="  <?php if($info1000['open_ratecolumn']==1) { echo 'change15';  } else { echo 'edit-input'; } ?>  income_count chk8ange totalorder"  size="4" />
<?php } ?>
         
   
           <?php
          if($info4000['separate_mrpcolumnp']==0)
          {
            ?>
       
          <input name="mrp_price[]" size="4"   type="hidden" class="edit-input income_count totalorder" id="<?php echo "mrp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2['pmrp_price'];?>"  />
          <?php
        }
     
        ?>

                  
                <input name="tax_mrp[]" size="4"   type="hidden" class="edit-input income_count totalorder" id="<?php echo "mrptax".$info2['id'];?>"    value="<?php echo $info2['ptax_mrp'];?>"  />     
         
            </td>

    
    <?php if($info4000['separate_mrpcolumnp']==1) { ?><td >
      
      
               <input name="mrp_price[]" size="4"   type="number" step="0.0001" required class="edit-input income_count totalorder" id="<?php echo "mrp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2['pmrp_price'];?>"  readonly="readonly" />
          
      
    
    </td>
    <?php } ?>



 <td <?php  if($info4000['invoice_cartonratep']==0) { echo ' style=" display:none;"'; } ?>>
                
           
 <select name='rate_in_carton[]' class='teacher income_count'  id="<?php echo "ric".$info2['id'];?>"  >
 <option value='0' >Default</option>
 <option value='1' ><?php echo $info1000['packing_label']; ?></option>
 <option value='2' ><?php echo $info1000['multi_unit_label']; ?></option>
 <option value='3' ><?php echo $info2000['customfield1_display'];  ?></option>
 </select>
            </td>         
        

              
           <td <?php  if($info2000['en_ricetrade']==0) { echo ' style=" display:none;"'; } ?> ><input name="packing2[]" type="number" step="0.0001" class='teacher income_count'  value="<?php echo (isset($info2['pac2']) && $info2['pac2'] !== '' ? $info2['pac2'] : 0); ?>"  id="<?php echo "packk".$info2['id'];?>"   required/> </td>      

 <?php if($info1000['vendor_discount1']==1) { 
 echo '<td >';
$bid=$info2['brand_id'];
 $data15 = mysqli_query($conn,"SELECT discount from vb_discount where vid='$cid' AND bid='$bid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);


$data17 = mysqli_query($conn,"SELECT discount from vendor_type_discount1 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info17 = mysqli_fetch_array( $data17 ); 

$num_rows2 = mysqli_num_rows($data17);


if($num_rows!=0) {
?>
<input name="products_discount[]" type="number" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['discount'];?>" size="4"  required/>

<?php }
else if($num_rows2!=0) {
?>
<input name="products_discount[]" type="number" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info17['discount'];?>" size="4"  required/>

<?php }  else if($info1000['en_lastprice']==1 && $info2000['discount']!='') { ?>

<input name="products_discount[]"  type="number" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['discount'];?>" size="4"  required/>


 <?php }
 else {  ?>
<input name="products_discount[]"  type="number" class="edit-input income_count totalorder" id="<?php echo "ppp".$info2['id'];?>"  tabindex="1"  value="0" size="4"  required/>
<?php } echo '</td>'; } 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"  required/>


 <?php } if($info1000['vendor_discount2']==1) { 
 
$data15 = mysqli_query($conn,"SELECT discount from vendor_type_discount2 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input name="products_discount2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppn".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['discount'];?>" size="4" /></td>
<?php }
elseif($info1000['en_lastprice']==1 && $info2000['discount2']!='') { ?>

<td><input name="products_discount2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppn".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['discount2'];?>" size="4" /></td>

 <?php }
 else {  ?>

<td><input name="products_discount2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppn".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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) { 
 
$data15 = mysqli_query($conn,"SELECT discount from vendor_type_discount4 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input name="products_discount4[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppx".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['discount'];?>" size="4" /></td>
<?php }
else if($info1000['en_lastprice']==1 && $info2000['discount4']!='') { ?>

<td><input name="products_discount4[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppx".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['discount4'];?>" size="4" /></td>

 <?php }
 else {  ?>

<td><input name="products_discount4[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppx".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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($info1000['vendor_discount3']==1) { 
$data15 = mysqli_query($conn,"SELECT discount from vendor_type_discount3 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input name="products_discount3[]" type="text" class="edit-input income_count totalorder products_discount3" id="<?php echo "pppm".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['discount'];?>" size="4" /></td>
<?php } else if($info1000['en_lastprice']==1 && $info2000['discount3']!='') {?>

<td><input name="products_discount3[]" type="text" class="edit-input income_count totalorder products_discount3" id="<?php echo "pppm".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['discount3'];?>" size="4" /></td>


<?php }  else {  ?>

<td><input name="products_discount3[]" type="text" class="edit-input income_count totalorder products_discount3" id="<?php echo "pppm".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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) { 
$data15 = mysqli_query($conn,"SELECT scheme from vendor_type_scheme where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input  name="products_scheme[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="<?php echo $info15['scheme'];?>" size="4" />
</td>
<?php } else if($info1000['en_lastprice']==1 && $info2000['scheme']!='') { ?>

<td><input name="products_scheme[]"  type="text" class="edit-input income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['scheme'];?>" size="4" /></td>

<?php } else {  ?>

<td><input  name="products_scheme[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></td>
<?php } } else { ?>

<input name="products_scheme[]"  type="hidden" class="edit-input income_count totalorder" id="<?php echo "ppps".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></td>

<?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 $info15['scheme'];?>" size="4" /> <input  name="products_pcs[]" type="text" size="4" min="1" class="edit-input total_pcs" id="<?php echo "t".$info2['id'];?>" readonly="readonly" /></td>
  
   <?php if($info1000['vendor_tax1']==1) { 
$data15 = mysqli_query($conn,"SELECT tax from vendor_type_tax1 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($info2000['en_maintaxc']==1) {
?>

  <td ><input name="products_tax[]" type="text" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($st==1) {  if($cfiler==1) { echo $info2000['filer_taxc']; } else { echo $info2000['nonfiler_taxc']; }  } else { echo 0; } ?>" size="4" readonly="readonly" /></td>

<?php }
else if($num_rows!=0) {
?>

  <td ><input name="products_tax[]" type="text" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1 && $st==1) { echo $info15['tax']; } else { echo 0;}?>" size="4" readonly="readonly" /></td>

<?php } elseif($info1000['en_lastprice']==1 && $info2000['tax_applied']!='') { ?>

 <td>     <input name="products_tax[]" type="text" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1) { echo $info2000['tax_applied']; } else { echo 0;}?>" size="4" readonly="readonly" /></td>
   
   
 <?php } else {  ?>

  <td ><input name="products_tax[]" type="text" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1 && $st==1) { echo 0; } else { echo 0;}?>" size="4" readonly="readonly" /></td>


<?php } } else { ?>

      <input name="products_tax[]" type="hidden" class="edit-input income_count" tabindex="1" id="<?php echo "pppp".$info2['id'];?>" value="<?php if($info1000['en_tax']==1 && $st==1) { echo 0; } else { echo 0;}?>" size="4" readonly="readonly" /></td>
   
   <?php } ?>

 <td <?php if($info4000['invoice_cartonratep']==0) { echo ' style=" display:none;" '; } ?>  ><input  type="text" class="edit-input income_count" tabindex="1" id="<?php echo "pipe".$info2['id'];?>" value="<?php  echo 0; ?>" size="4" readonly="readonly" /></td>

   
 <?php  if($info1000['vendor_tax2']==1) { 
 
$data15 = mysqli_query($conn,"SELECT tax from vendor_type_tax2 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {
?>

<td><input name="products_tax2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppptt".$info2['id'];?>"  tabindex="1"  value="<?php if($info1000['en_tax']==1 && $st==1) { echo $info15['tax']; } else { echo 0;}?>" size="4" /></td>
<?php } 
else if($info1000['en_lastprice']==1 && $info2000['tax_applied2']!='') { ?>
<td><input name="products_tax2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppptt".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['tax_applied2']; ?>" size="4" /></td>

 <?php } else {  ?>

<td><input name="products_tax2[]" type="text" class="edit-input income_count totalorder" id="<?php echo "ppptt".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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" /></td>

 <?php } if($info1000['vendor_tax3']==1) { 
$data15 = mysqli_query($conn,"SELECT tax from vendor_type_tax3 where pid='$ttid' AND tid='$ppid' ") or die(mysqli_error($conn));
    
$info15 = mysqli_fetch_array( $data15 ); 

$num_rows = mysqli_num_rows($data15);

if($num_rows!=0) {

?>

<td><input name="products_tax3[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppttt".$info2['id'];?>"  tabindex="1"  value="<?php if($info1000['en_tax']==1 && $st==1) { echo $info15['tax']; } else { echo 0;}?>" size="4" /></td>
<?php } else if($info1000['en_lastprice']==1 && $info2000['tax_applied3']!='') { ?>

<td><input name="products_tax3[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppttt".$info2['id'];?>"  tabindex="1"  value="<?php echo $info2000['tax_applied3']; ?>" size="4" /></td>

 <?php }  else {  ?>

<td><input name="products_tax3[]" type="text" class="edit-input income_count totalorder" id="<?php echo "pppttt".$info2['id'];?>"  tabindex="1"  value="0" size="4" /></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" /></td>

 <?php } ?>
  
    <td><input name="products_total[]" type="number" size="5"  class="<?php echo $info2['id'];?> ptotal sub_total readonly " id="newtotal<?php echo $info2['id'];?>" tabindex = "-1" min="0" onkeypress="return false;"   required value="0"/></td>
               <td><?php
               $smart_last_batch_number = mysqli_get_var("SELECT MAX(CAST(batch_code AS UNSIGNED)) FROM inventory_batch WHERE prd_id='".$info2['id']."' AND type_component=0 AND batch_code REGEXP '^[0-9]+$'");
               if($smart_last_batch_number=='') { $smart_last_batch_number = 0; }
               if($info3000['en_smartbatch']==1 && ($info4000['grn_single_batch_qty']==1 || $info3000['open_batchgrn']==1)) { ?>
                <div <?php if($info2['is_batch'] != 1){ echo "class='hide'"; } ?> style="display:inline-block; margin-right:6px;">
                  <button type="button" class="btn btn-default btn-sm smartbatch-open" data-item="<?php echo htmlspecialchars($info2['sku'].' '.$info2['name']); ?>" data-lastbatch="<?php echo (int)$smart_last_batch_number; ?>">+</button>
                  <span class="smartbatch-view text-muted" style="display:none;"></span>
                </div>
                <input type="hidden" name="smartbatch_data[]" class="smartbatch-data" value="" />
               <?php } else { ?>
                <input type="hidden" name="smartbatch_data[]" class="smartbatch-data" value="" />
               <?php } ?><?php if(1==1) { ?><input type="button" class="edit receipt_edit_hide5" value="Edit" /><input type="button" class="save" value="Save" /><?php } ?><?php if(1==1) { ?><input type="button" class="delete receipt_delete_edit5" value="Delete" /><?php } ?></td> 
                
      </tr>
            <?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>
<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'>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(){
  $(this).closest('tr').find('.edit').hide();
  $(this).closest('tr').find('.save').show();
  
  $(this).closest('tr').find('.edit-input').attr("readonly", false);
});

$(document).on('click', ".save", function(){
  $(this).closest('tr').find('.save').hide();
  $(this).closest('tr').find('.edit').show();
  
  $(this).closest('tr').find('.edit-input').attr("readonly", true); 
   // Hamza
   $("input[name='currency_rate']").trigger('change');
  //Hamza end
});
     
    
    
           $('.delete').on('click',function() {
    
    
  $(this).closest( 'tr').remove();
 


//Total Quantity Sum  (Pcs)
    var sum = 0;
    $(".total_pcs").each(function(){
        sum += +$(this).val();
    });
    $("#total_pcs").val(sum);


//Total Quantity Sum  (Carton)
    var sum3 = 0;
    $(".packing").each(function(){
        sum3 += +$(this).val();
    });
    $("#packing").val(sum3);



//Total Amount Sum  (Sub Total)
    var sum2 = 0;
    $(".sub_total").each(function(){
        sum2 += +$(this).val();
    });
    $("#sub_total").val(sum2);



  var n4 = $("#sub_total").val();
      
   var n5 = $("#paid_amount").val();
    var n6 = $("#pending_amount").val();
    

     var total = +n4 ;
   var pending = +total - n5;
      $("#total_amount").val(total);
      if (isNaN(pending) || pending === null || pending === '') {
        pending = 0;
    }
    $("#pending_amount").val(pending);

  
     });

 });  
   
   
    </script>    



<?php
 
  
}

 }
 
 
 
} ?>
    
        </tbody>
        </table>

</div>    

 



<br>

<div class="col-12">
        <div class="row">
            <!-- <div class="col-md-12">
                <div class="card card-height-100">
                   
                    <div class="card-body"> -->
                       <!--Own Text -->
   
   
  
<?php
$prid = $_GET['prid'];
$pr_notes = mysqli_get_var("Select notes from pr where id = '$prid' ");
$transportHidden = $info2000['hide_oldtransport']==1 ? ' style="display:none;"' : '';
?>

<!-- <div class="row g-3 align-items-end notes-meta-grid"> -->
    <div id="customerdisc" class="<?php echo $info3000['formlayout_column'] ;?>"<?php  if($info1000['en_discount']==0 || $po_withoutvalue) { echo ' style="display:none;"'; } ?>>
        <label class="form-label">Discount (%)</label>
        <input name="discount" type="number" id="discount" class="form-control"  accesskey="d" value="0" required />
    </div>
    <div class="<?php echo $info3000['formlayout_column'] ;?> invoicetax"<?php  if($info1000['en_tax']==0 || $po_withoutvalue) { echo ' style="display:none;"'; } ?>>
        <label class="form-label">Tax Applied</label>
        <input name="tax" type="number" id="tax" value="0" class="form-control" required />
    </div>
    <div class="<?php echo $info3000['formlayout_column'] ;?> shipping5"<?php  if($info1000['en_shipping']==0 || $po_withoutvalue) { echo ' style="display:none;"'; } ?>>
        <label class="form-label">Freight Charges</label>
        <input name="shipping" accesskey="f" type="text" id="shipping" value="0"  class="form-control" />
    </div>
    <div class="<?php echo $info3000['formlayout_column'] ;?>">
        <label class="form-label">Notes</label>
        <textarea name="notes" <?php if($info1000['notes_required']==1) { echo 'required';  } ?> class="form-control" rows="2" style="resize: vertical;"><?php echo $pr_notes; ?></textarea>
    </div>
    <div class="<?php echo $info3000['formlayout_column'] ;?>"<?php echo $transportHidden; ?>>
        <label class="form-label">Transport Details</label>
        <select name="tr" id="tr"   class="form-control">
            <option value="n">No</option>
            <option value="y">Yes</option>
        </select>
    </div>
<!-- </div> -->
<?php if($info2000['hide_oldtransport']!=1){ ?>
<div class="trdiv <?php echo $info3000['formlayout_column'];?>" >
<table width="100%" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <th scope="col"><?php echo $info2000['transport_details_label']; ?> Number</th>
    <th scope="col"><?php echo $info2000['transport_details_label']; ?> Name</th>
    <th scope="col"><?php echo $info2000['transport_details_label']; ?> Quantity</th>
    <th scope="col"><?php echo $info2000['transport_details_label']; ?> Date</th>
    
  </tr>
  
  <tr>
    <td>
   <input name="shipping_details[]" value="1_" type="hidden" />
    <input name="1_tr_num" type="text" class="form-control" id="tr_num"/></td>
    <td><input name="1_tr_name" type="text" class="form-control" id="tr_name"/></td>
    <td><input name="1_tr_qty" type="text" class="form-control" id="tr_qty"/> </td>
    <td><input name="1_tr_date" type="date" class="form-control" id="tr_date"/></td>
      </tr>
  <tr>
    <td> <input name="shipping_details[]" value="2_" type="hidden" />
    <input name="2_tr_num" type="text" class="form-control" id="tr_num"/></td>
    <td><input name="2_tr_name" type="text" class="form-control" id="tr_name"/></td>
    <td><input name="2_tr_qty" type="text" class="form-control" id="tr_qty"/> </td>
    <td><input name="2_tr_date" type="date" class="form-control" id="tr_date"/></td>
   
  </tr>
<tr>
    <td> <input name="shipping_details[]" value="3_" type="hidden" /> <input name="3_tr_num" type="text" class="form-control" id="tr_num"/></td>
    <td><input name="3_tr_name" type="text" class="form-control" id="tr_name"/></td>
    <td><input name="3_tr_qty" type="text" class="form-control" id="tr_qty"/> </td>
    <td><input name="3_tr_date" type="date" class="form-control" id="tr_date"/></td>
   
  </tr>
  <tr>
    <td> <input name="shipping_details[]" value="4_" type="hidden" />
    <input name="4_tr_num" type="text" class="form-control" id="tr_num"/></td>
    <td><input name="4_tr_name" type="text" class="form-control" id="tr_name"/></td>
    <td><input name="4_tr_qty" type="text" class="form-control" id="tr_qty"/> </td>
    <td><input name="4_tr_date" type="date" class="form-control" id="tr_date"/></td>
    
  </tr>

</table>


</div>
<?php } ?>




                       
                       <!--Own Text End -->
                    <!-- </div>
                </div>
            </div>
        </div>
        </div> -->
        
        
        <!-- <div class="col-12">
        <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 && !$po_withoutvalue) { ?>
<?php
$count = mysqli_get_var("SELECT COUNT(id) from rice_discount WHERE purchase_side=1 && inventory=1  $climit_ricediscount AND po = 1 ");
if($count > 0){ 
?>       
<div class="col-md-6">      
<table width="100%" border="1" cellspacing="0" cellpadding="5">
  
<?php $data4 = mysqli_query($conn,"SELECT * from rice_discount where   1=1 $climit_ricediscount && inventory=1  && `purchase_side`=1 AND po = 1 order by code") or die(mysqli_error($conn));
 while($info4 = mysqli_fetch_array( $data4 )) 
 {  


if($info4000['en_nooriinternational']==1) {
   $toggleclass = mysqli_get_var("Select toggleclass from rice_purchase_discount where type_id='".$info4['id']."' && sid='$id' && page=2 ");
  }


  $specialclass=$info4['specialclass']; ?>
 <tr class="drice <?php echo $specialclass  ?>">


  <td scope="col" <?php  if($info4000['en_nooriinternational']==0) {  echo 'style="display:none;"' ; }  ?>> 

      <select name="addclass[]" class="form-control addclass" id="addclass">
    <?php 
           if($toggleclass==1){
              echo '<option value="0">No</option>';
           echo '<option value="1" selected>Yes</option> ';  

           }
           else{
            echo '<option value="0" selected>No</option>';
           echo '<option value="1" >Yes</option> ';  
           }
     ?>
    
   </select>
  </td>

    <td><?php echo $info4['label']; ?> 
    <input  type="hidden" value="<?php echo $type_id =  $info4['id']; ?>" class="rice_discount" name="rice_discount[]"  />
    <input type="hidden" value="<?php echo $info4['less']; ?>" class="rice_type" name="rice_type[]"  />
    <input type="hidden" value="<?php echo $info4['amount_type']; ?>" name="rice_percent[]"  class="rice_percent" />
        <input type="hidden" value="<?php echo $info4['specialclass']; ?>" class="specialclass" name="specialclass[]"  />
    <input type="hidden" value="<?php echo $info4['specialclass2']; ?>" class="specialclass2" name="specialclass2[]"  />    
        
   <input type="hidden" value="<?php echo $info4['coa_id']; ?>" class="coa_id" name="coa_id[]"  />
    </td>
     <td><input value="<?php 
         $po_id=$info5['po_id'];
         
        $chages_send= mysqli_get_var(" Select id  from rice_purchase_discount where sid IN (Select id from purchasing where po_id='$po_id')   AND type_id='$type_id'  && page=3  ");
              if(!$chages_send){
                $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" class="form-control rice_discount_value" step="0.001"   required/></td>
  </tr>
  <?php } ?>
</table>
        </div><br>
  <?php } ?>
<br>

<?php } ?>   
 
<div style="display:none;">
    <div class="row g-3 align-items-end manager-grid">
        <div class="<?php echo $info3000['formlayout_column'] ;?>">
            <label class="form-label">Manager 1</label>
            <?php 
                $selected_manager1_id = mysqli_get_var("Select reporting_1 from employee where id = '$loginuser'");
                $data4 = mysqli_query($conn,"SELECT  id, fname from `user` where id IN (Select id from `employee`) && inactive=0  "); 
                echo "<select name='manager_1' id='manager_1' class='teacher form-control reportselect' >";
                echo "<option value='' >None</option>";  
                while($info4 = mysqli_fetch_array( $data4 )) 
                {
                    if($selected_manager1_id==$info4["id"]){
                        echo "<option value='".$info4['id']."' selected='selected' >".$info4['fname']."</option>";
                    }else{
                        echo "<option value='".$info4['id']."' >".$info4['fname']."</option>";  
                    }
                }
                echo "</select>";
            ?>
        </div>
        <div class="<?php echo $info3000['formlayout_column'] ;?>">
            <label class="form-label">Manager 2</label>
            <?php 
                $selected_manager2_id = mysqli_get_var("Select reporting_2 from employee where id = '$loginuser'");
                $data4 = mysqli_query($conn,"SELECT  id, fname from `user` where id IN (Select id from `employee`) && inactive=0  "); 
                echo "<select name='manager_2' id='manager_2' class='teacher form-control reportselect'   >";
                echo "<option value='' >None</option>";   
                while($info4 = mysqli_fetch_array( $data4 )) 
                {
                    if($selected_manager2_id==$info4["id"]){
                        echo "<option value='".$info4['id']."' selected='selected' >".$info4['fname']."</option>";
                    }else{
                        echo "<option value='".$info4['id']."' >".$info4['fname']."</option>";  
                    }
                }
                echo "</select>";
            ?>
        </div>
        <div class="<?php echo $info3000['formlayout_column'] ;?>">
            <label class="form-label">Manager 3</label>
            <?php 
                $selected_manager3_id = mysqli_get_var("Select reporting_3 from employee where id = '$loginuser'");
                $data4 = mysqli_query($conn,"SELECT  id, fname from `user` where id IN (Select id from `employee`) && inactive=0  "); 
                echo "<select name='manager_3' id='manager_3' class='teacher form-control reportselect'   >";
                echo "<option value='' >None</option>";   
                while($info4 = mysqli_fetch_array( $data4 )) 
                {
                    if($selected_manager3_id==$info4["id"]){
                        echo "<option value='".$info4['id']."' selected='selected' >".$info4['fname']."</option>";
                    }else{
                        echo "<option value='".$info4['id']."' >".$info4['fname']."</option>";  
                    }
                }
                echo "</select>";
            ?>
        </div>
    </div>    
</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($info1000['en_grn']==1) { echo ' selected '; } ?>  >No</option>
</select> 

<br>
</div> 

                       
<?php

if($info1000['invoice_pay']==1) {
?>
Paid Amount <input name="paid_amount" type="text" class="form-control" id="paid_amount" accesskey="p"  value="0"/>



<br />
    



Cash Account <?php $data4 = mysqli_query($conn,"SELECT * from accounts_type where dept_id=1  $caccounts_company ") or die(mysqli_error($conn)); 

echo "<select name='bank'  class='form-control allinone-payment-bank'   >";
 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 echo "<option value='".$info4['id']."' >".$info4['name']."</option>"; 
   
}

echo "</select>";


?><br>

<?php } else { echo '<input name="paid_amount"  type="hidden" id="paid_amount" value="0" /> <input name="bank" type="hidden"  value="0"/>'; } ?>                       
                       
                       <?php 
if($info50['invoice_pay']==1) {
?>
                   
Mode of Payment <select name="mode" class="form-control allinone-payment-mode">
<option value="1" >Cash</option>
<option value="2" >Check</option>
</select> 
<br>
      <?php }   else { echo '<input name="mode" type="hidden"  value="0"/>'; }?>  
<div class="<?php echo $info3000['formlayout_column'] ;?>" <?php if(!$inline_form_direct_enabled || $info50['invoice_pay']!=1) { echo 'style="display:none;"'; } ?>>
Payment Date <input name="all_in_one_payment_date" type="date" class="form-control allinone-payment-date" value="<?php echo date('Y-m-d'); ?>" />
</div>



                 
                       <!--Own Text End -->
                    <!-- </div>
                </div>
            </div>
        </div>
        </div> -->
        
        
        
        <!-- <div class="col-12">
        <div class="row">
            <div class="col-md-12">
                <div class="card card-height-100">
                   
                    <div class="card-body"> -->
                       <!--Own Text -->

                        <!-- <div class="row g-3 align-items-end totals-meta-grid"> -->
<?php  if($info3000['en_carton_display']==1 && $info1000['no_purchasepacking']!=1){ ?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label"><?php echo $info3000['purchase_total_ctn_label']; ?></label>
                                <input type="text" name="total_carton" id="packing" value="0" readonly class="form-control">
                            </div>
<?php } ?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label"><?php echo $info3000['purchase_total_pcs_label']; ?></label>
                                <input name="total_pcs" type="text" id="total_pcs" value="0" readonly class="form-control">
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>">
                                <label class="form-label">Total # of Items</label>
                                <input name="total_items_count" type="text" id="total_items_count" value="0" readonly class="form-control">
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label"><?php echo $info1000['product_label']; ?> Subtotal</label>
                                <input name="sub_total" type="text" class="form-control" id="sub_total"  readonly="readonly"/>
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label">Cost Per Piece</label>
                                <input type="text" name="total_cost_peice" id="total_cost_peice" class="form-control" value="0" readonly>
                            </div>
                        <!-- </div> -->

    <input   class="form-control"   type="hidden" id="grossamount" />  



<div style=" <?php  if($info1000['en_purchase']==0 || 1==1) { echo "display:none;"; } ?>">
    <table width="100%" border="1" cellspacing="0" cellpadding="5" class="table table-striped table-hover align-middle dt-responsive nowrap display w-100">  
        <tr style="display: none;">    
            <td>Slab Details</td>  
            <td>%</td>     
            <td>Due Date</td>     
        </tr>   
        <tr>    
            <td style="text-wrap: nowrap;">Slab 1</td> 
            <td><input type="number" class="form-control" id="slab1_percent" name="slab1_percent" placeholder="%" required value="0"></td> 
            <td><input type="date" class="form-control" id="slab1_duedate" name="slab1_duedate"></td> 
        </tr>   
        <tr>    
            <td style="text-wrap: nowrap;">Slab 2</td> 
            <td><input type="number" class="form-control" id="slab2_percent" name="slab2_percent" placeholder="%" required value="0"></td> 
            <td><input type="date" class="form-control" id="slab2_duedate" name="slab2_duedate"></td> 
        </tr>   
        <tr>    
            <td style="text-wrap: nowrap;">Slab 3</td> 
            <td><input type="number" class="form-control" id="slab3_percent" name="slab3_percent" placeholder="%" required value="0"></td> 
            <td><input type="date" class="form-control" id="slab3_duedate" name="slab3_duedate"></td> 
        </tr>   
    </table>    
</div>


<div class="<?php echo $info3000['formlayout_column'];?>"  style=" <?php  if($info1000['en_recurringinvoices']==0) { echo "display:none;"; } ?>">
Recurring 
<table width="100%" border="0" cellspacing="5" cellpadding="5">
  <tr>
    <td width="30%"><input name="recurring_qty" type="text" class="form-control" value="0" 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 )) 
 { 
   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-12">
        <div class="row">
            <div class="col-md-12">
                <div class="card card-height-100">
                   
                    <div class="card-body"> -->
                       <!--Own Text -->

                        <!-- <div class="row g-3 align-items-end totals-summary-grid"> -->
                            <div class="<?php echo $info3000['formlayout_column'] ;?>"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label">Pending Amount</label>
                                <input name="pending_amount" type="text" class="form-control" id="pending_amount" readonly />
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?>" id="oldr"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label"> Old Payable</label>
                                <input name="old" type="text" class="form-control"  id="old" readonly="readonly"/>
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?> taxexcludingdisplay"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label">Amount Excluding Tax</label>
                                <input name="invoice_excludingtax" type="text" class="form-control" id="invoice_excludingtax" value="0" readonly/>
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?> taxexcludingdisplay"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label">Invoice Tax</label>
                                <input name="invoice_tax" type="text" class="form-control" id="invoice_tax" value="0" readonly/>
                            </div>
<?php  if($info3000['en_goodluck']==1){?>
                            <div class="<?php echo $info3000['formlayout_column'] ;?> oldr-block"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label">Total SLC Amount</label>
                                <input name="total_slc" type="text" class="form-control"  id="total_slc" readonly="readonly"/>
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?> oldr-block"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label">Total SLC Amount Price Difference</label>
                                <input name="total_slc_price" type="text" class="form-control"  id="total_slc_price" readonly="readonly"/>
                            </div>
                            <div class="<?php echo $info3000['formlayout_column'] ;?> oldr-block"<?php if($po_withoutvalue) { echo ' style="display:none;"'; } ?>>
                                <label class="form-label">Total SLC Amount Difference Amount</label>
                                <input name="total_slc_amount" type="text" class="form-control"  id="total_slc_amount" readonly="readonly"/>
                            </div>
<?php  } ?>
                        </div>
                       
                        <!--Own Text End -->
                    <!-- </div> -->
                <!-- </div> -->
            <!-- </div>
          </div>
        </div> -->
       
<br>
<!-- Basit -->
<div class="purchaseinv_history">
    
</div>   
<!---->                
        
 
<div style="clear:both">

<div class="po-value-summary-block" <?php if($po_withoutvalue) { echo 'style="display:none;"'; } ?>>
<h3>Total</h3> <input name="total_amount" type="text" class="form-control" id="total" readonly="readonly" required   /><br /><br />
</div>

<?php if($info1000['direct_invoicep']==1 && !$po_withoutvalue) { ?>
 <input name="submit" type="submit" id="submit" class="btn btn-success create_hide5"  value="Create <?php echo (isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_invoice_label'] : 'Purchase Invoice'; ?> "  /> 
<?php } ?>
 
<?php if($info1000['indirect_invoicep']==1) { ?>
  <input name="submit2" type="submit" id="submit2" class="btn btn-warning create_hide5"  value="Create <?php echo (isset($_GET['shipping']) && $_GET['shipping']==1) ? $info3000['shipping_label'] : $info4000['purchaseorder_label']; ?> "  />
<?php } ?>  
   
<?php if(($info3000['po_payment_vcoucher']==1 || $inline_form_direct_enabled) && !$po_withoutvalue) { ?>
  <?php if($inline_form_direct_enabled) { ?>
    <button type="button" class="btn btn-info" onclick="return bmsOpenPurchasePaymentFrame();">Create Payment</button>
  <?php } else { ?>
    <a href="../treasury/ppayment-voucher.php" target="_blank">
      <input type="button" class="btn btn-info" value="Create Payment" />
    </a>
  <?php } ?>
<?php } ?>  
  

</div>





                       
                       <!--Own Text End -->
                    </div>
                </section>
            </div>
        </div>
       </div>
     </div>
      </div>
      </div>
     </div>
            </div>
      
    <!--main content end-->
    
     </form>

<?php if (function_exists('bms_render_hidden_required_guard_script')) { bms_render_hidden_required_guard_script('#slip'); } else { ?>
<script>
(function () {
  var form = document.querySelector('#slip');
  if (!form) { return; }
  function syncHiddenRequiredFields() {
    var fields = form.querySelectorAll('input, select, textarea');
    for (var i = 0; i < fields.length; i++) {
      var field = fields[i];
      if (!field) { continue; }
      var hidden = field.offsetParent === null;
      if (hidden) {
        if (field.required && !field.hasAttribute('data-bms-required-guard')) {
          field.setAttribute('data-bms-required-guard', '1');
          field.required = false;
        }
      } else if (field.getAttribute('data-bms-required-guard') === '1') {
        field.required = true;
        field.removeAttribute('data-bms-required-guard');
      }
    }
  }
  syncHiddenRequiredFields();
  form.addEventListener('change', syncHiddenRequiredFields, true);
  form.addEventListener('submit', syncHiddenRequiredFields, true);
})();
</script>
<?php } ?>

<?php if($info3000['en_smartbatch']==1 && ($info4000['grn_single_batch_qty']==1 || $info3000['open_batchgrn']==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 smartbatch-close" data-dismiss="modal" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Serial/Lot Items</h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-4">
            <label>Warehouse</label>
            <input type="text" id="smartbatch-warehouse" class="form-control" readonly="readonly" />
          </div>
          <div class="col-md-4">
            <label>Item</label>
            <input type="text" id="smartbatch-item" class="form-control" readonly="readonly" />
          </div>
          <div class="col-md-4">
            <label>Total <?php echo $info1000['multi_unit_labela']; ?></label>
            <input type="text" id="smartbatch-totalqty" class="form-control" readonly="readonly" />
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <div class="col-md-4">
            <label>UoM</label>
            <input type="text" id="smartbatch-uom" class="form-control" readonly="readonly" />
          </div>
          <div class="col-md-4">
            <label>Total Count</label>
            <input type="text" id="smartbatch-count" 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><?php echo $info1000['batch_label']; ?></th>
                <th style="width:140px;"><?php echo $info1000['multi_unit_labela']; ?></th>
                <th style="width:140px;">Weight</th>
                <th style="width:90px;"></th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
          <button type="button" class="btn btn-default btn-sm" id="smartbatch-add">Add Row</button>
          <div class="row" style="margin-top:10px;">
            <div class="col-md-4 col-md-offset-4">
              <label>Total Weight</label>
              <input type="text" id="smartbatch-totalweight" class="form-control" readonly="readonly" value="0.0000" />
            </div>
            <div class="col-md-4">
              <label>Total <?php echo $info1000['multi_unit_labela']; ?> Entered</label>
              <input type="text" id="smartbatch-subtotal" class="form-control" readonly="readonly" value="0.0000" />
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default smartbatch-close" data-dismiss="modal" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="smartbatch-save">Save</button>
      </div>
    </div>
  </div>
</div>
<?php } ?>

<?php if($po_withoutvalue) { ?>
<script type="text/javascript">
(function($) {
  var valueCellSelectors = [
    "input[name='unitcos[]']",
    "input[name='sale_price[]']",
    "input[name='mrp_price[]']",
    "select[name='rate_in_carton[]']",
    "input[name='products_discount[]']",
    "input[name='products_discount2[]']",
    "input[name='products_discount3[]']",
    "input[name='products_discount4[]']",
    "input[name='products_tax[]']",
    "input[name='products_tax2[]']",
    "input[name='products_tax3[]']",
    "input[name='display_totaltax[]']",
    "input[name='display_totaltax2[]']",
    "input[name='products_total[]']",
    "input[id^='pipe']",
    ".price_margin"
  ].join(',');
  var headerExactPatterns = [
    'sale price',
    'margin %',
    'rate apply',
    'pipe rate',
    'exclusive of gst amount',
    'total',
    'unit rate'
  ];
  var headerContainsPatterns = <?php echo json_encode(array_values(array_filter(array(
    strtolower(trim((string)$info4000['price_labelp'])),
    strtolower(trim((string)$info4000['mrp_label'])),
    strtolower(trim((string)$info1000['disc1_label'])),
    strtolower(trim((string)$info1000['disc2_label'])),
    strtolower(trim((string)$info1000['disc3_label'])),
    strtolower(trim((string)$info1000['toffer_label'])),
    strtolower(trim((string)$info1000['tax1_label'])),
    strtolower(trim((string)$info1000['tax2_label'])),
    strtolower(trim((string)$info1000['tax3_label'])),
    strtolower(trim((string)$info4000['taxamount_label']))
  )))); ?>;

  function normalizeHeaderText(text) {
    return $.trim(String(text).replace(/\s+/g, ' ').toLowerCase());
  }

  function isValueHeader(text) {
    if ($.inArray(text, headerExactPatterns) !== -1) {
      return true;
    }

    for (var i = 0; i < headerContainsPatterns.length; i++) {
      if (headerContainsPatterns[i] && text.indexOf(headerContainsPatterns[i]) !== -1) {
        return true;
      }
    }

    return false;
  }

  function resetPoValueInputs($table) {
    if (!$table.length) {
      return;
    }

    $table.find("input[name='unitcos[]'], input[name='sale_price[]'], input[name='mrp_price[]'], input[name='products_discount[]'], input[name='products_discount2[]'], input[name='products_discount3[]'], input[name='products_discount4[]'], input[name='products_tax[]'], input[name='products_tax2[]'], input[name='products_tax3[]'], input[name='display_totaltax[]'], input[name='display_totaltax2[]'], input[name='products_total[]'], input[id^='pipe'], .price_margin").each(function() {
      $(this).val(0);
    });

    $table.find("select[name='rate_in_carton[]']").each(function() {
      var $select = $(this);
      if ($select.find("option[value='0']").length) {
        $select.val('0');
      } else if ($select.find("option").length) {
        $select.prop('selectedIndex', 0);
      }
    });
  }

  function hidePoValueColumns($table) {
    if (!$table.length) {
      return;
    }

    var hiddenIndexes = {};
    $table.find('thead tr').first().children().each(function(index) {
      if (isValueHeader(normalizeHeaderText($(this).text()))) {
        hiddenIndexes[index] = true;
      }
    });

    $table.find('tbody tr.carttr').each(function() {
      $(this).children('td').each(function(index) {
        if ($(this).find(valueCellSelectors).length) {
          hiddenIndexes[index] = true;
        }
      });
    });

    resetPoValueInputs($table);

    $.each(hiddenIndexes, function(index) {
      $table.find('tr').each(function() {
        $(this).children().eq(parseInt(index, 10)).hide();
      });
    });
  }

  function applyPoWithoutValueLayout() {
    hidePoValueColumns($('#acart'));
    $('#psearch').find('table').each(function() {
      hidePoValueColumns($(this));
    });
  }

  $(function() {
    applyPoWithoutValueLayout();

    var tbody = document.querySelector('#acart tbody');
    if (tbody && window.MutationObserver) {
      new MutationObserver(applyPoWithoutValueLayout).observe(tbody, {
        childList: true,
        subtree: true
      });
    }

    var psearch = document.getElementById('psearch');
    if (psearch && window.MutationObserver) {
      new MutationObserver(applyPoWithoutValueLayout).observe(psearch, {
        childList: true,
        subtree: true
      });
    }
  });
})(jQuery);
</script>
<?php } ?>

<?php if($info3000['en_smartbatch']==1 && ($info4000['grn_single_batch_qty']==1 || $info3000['open_batchgrn']==1)) { ?>
<script type="text/javascript">
$(function() {
  var currentRow = null;
  var currentBatchStart = 0;

  function getSmartBatchDataField($row) {
    if (!$row || !$row.length) {
      return $();
    }
    var $fields = $row.find('.smartbatch-data');
    if ($fields.length > 1) {
      $fields.not(':first').remove();
      $fields = $row.find('.smartbatch-data');
    }
    return $fields.first();
  }

  function getSmartBatchWeightField($row) {
    if (!$row || !$row.length) {
      return $();
    }
    return $row.find("input[name='custom_field1[]']").first();
  }

  function toggleSmartBatchModal(action) {
    var modalEl = document.getElementById('smartBatchModal');
    if (!modalEl) {
      return;
    }

    if (window.bootstrap && window.bootstrap.Modal) {
      var instance = window.bootstrap.Modal.getOrCreateInstance(modalEl);
      if (action === 'show') {
        instance.show();
      } else {
        instance.hide();
      }
    } else if ($.fn.modal) {
      $('#smartBatchModal').modal(action);
    } else if (action === 'show') {
      $('#smartBatchModal').show().addClass('in show');
      $('body').addClass('modal-open');
      if (!$('.modal-backdrop').length) {
        $('<div class="modal-backdrop fade in show"></div>').appendTo(document.body);
      }
    } else {
      $('#smartBatchModal').hide().removeClass('in show');
      $('body').removeClass('modal-open');
      $('.modal-backdrop').remove();
    }

    if (action === 'hide') {
      currentRow = null;
      currentBatchStart = 0;
    }
  }

  function closeSmartBatchModal() {
    toggleSmartBatchModal('hide');
  }

  function decorateSmartBatchButtons($scope) {
    if (!$scope || !$scope.length) {
      $scope = $(document);
    }

    $scope.find('tr.carttr').each(function() {
      var $row = $(this);
      if ($row.find('.smartbatch-open').length) {
        getSmartBatchDataField($row);
        return;
      }

      var hasBatchField = $row.find("input[name='products_batch[]'], select[name='products_batch[]'], .LoadBatchWarehouseWise").length > 0;
      if (!hasBatchField) {
        return;
      }

      var noBatchLabel = $.trim($row.find('.LoadBatchWarehouseWise .text-muted').text()).toLowerCase();
      var batchInputValue = $.trim($row.find("input[name='products_batch[]']").first().val() || '');
      if (noBatchLabel === 'no batch' || batchInputValue === 'No Batch') {
        return;
      }

      var $actionCell = $row.children('td').last();
      if (!$actionCell.length) {
        return;
      }

      if (!getSmartBatchDataField($row).length) {
        $actionCell.prepend('<input type="hidden" name="smartbatch_data[]" class="smartbatch-data" value="" />');
      }

      var itemText = getRowItemText($row);
      var buttonHtml = '<div style="display:inline-block; margin-right:6px;">' +
        '<button type="button" class="btn btn-default btn-sm smartbatch-open" data-item="' + $('<div>').text(itemText).html() + '" data-lastbatch="0">+</button> ' +
        '<span class="smartbatch-view text-muted" style="display:none;"></span>' +
      '</div>';
      $actionCell.prepend(buttonHtml);
    });
  }
  function getRowItemText($row) {
    var text = $row.find('td').eq(0).text();
    return $.trim(text.replace(/\s+/g, ' '));
  }

  function getRowWarehouseText($row) {
    var $wh = $row.find("select[name='products_warehouse[]']");
    if ($wh.length) {
      return $wh.find('option:selected').text();
    }
    return '';
  }

  function getRowUomText($row) {
    var $munit = $row.find("select[name='munit[]']");
    if ($munit.length) {
      return $munit.find('option:selected').text();
    }
    var $uom = $row.find("select[name='uom[]']");
    if ($uom.length) {
      return $uom.find('option:selected').text();
    }
    var $uomHidden = $row.find("input[name='uom[]']");
    if ($uomHidden.length) {
      var $cell = $uomHidden.closest('td');
      var text = $cell.clone().children().remove().end().text();
      return $.trim(text.replace(/\s+/g, ' '));
    }
    return '';
  }

  function parseSmartBatchNumber(value) {
    var parsed = parseFloat(value);
    return isNaN(parsed) ? 0 : parsed;
  }

  function formatSmartBatchNumber(value) {
    var rounded = Math.round(parseSmartBatchNumber(value) * 10000) / 10000;
    if (!isFinite(rounded)) {
      rounded = 0;
    }
    var text = rounded.toFixed(4).replace(/\.?0+$/, '');
    return text === '' ? '0' : text;
  }

  function sumSmartBatchEntries(entries) {
    var total = 0;
    $.each(entries || [], function(_, entry) {
      total += parseSmartBatchNumber(entry.qty);
    });
    return total;
  }

  function getRowVisibleQtyField($row) {
    var selectors = [
      "input.searchqty.packing",
      "input.searchp.packing",
      "input[id^='ctn']",
      "input[name='stitch_pcs[]']",
      "input.searchqty",
      "input.searchp"
    ];

    for (var i = 0; i < selectors.length; i++) {
      var $field = $row.find(selectors[i]).filter(':enabled').first();
      if ($field.length) {
        return $field;
      }
    }

    return $();
  }

  function getRowTotalQtyField($row) {
    var $field = $row.find("input[name='products_pcs[]']").first();
    if ($field.length) {
      return $field;
    }
    return $row.find(".total_pcs").first();
  }

  function getSmartBatchRowTotalQty($row, entries) {
    var totalQty = parseSmartBatchNumber(getRowTotalQtyField($row).val());
    if (totalQty > 0) {
      return totalQty;
    }

    var visibleQty = parseSmartBatchNumber(getRowVisibleQtyField($row).val());
    if (visibleQty > 0) {
      return visibleQty;
    }

    return sumSmartBatchEntries(entries);
  }

  function syncSmartBatchQtyToRow($row, entries) {
    if (!$row || !$row.length) {
      return;
    }

    var sumQty = sumSmartBatchEntries(entries);
    var formattedQty = formatSmartBatchNumber(sumQty);
    var $visibleQty = getRowVisibleQtyField($row);
    var $totalQty = getRowTotalQtyField($row);

    if ($visibleQty.length) {
      $visibleQty.val(formattedQty);
    }

    if ($totalQty.length) {
      $totalQty.val(formattedQty);
    }

    if ($visibleQty.length) {
      $visibleQty.trigger('change').trigger('focusout');
    } else if ($totalQty.length) {
      $totalQty.trigger('change');
      $row.find('.income_count').first().trigger('change');
    } else {
      $row.find('.income_count').first().trigger('change');
    }

    $("input[name='currency_rate']").trigger('change');
  }

  function updateSmartBatchCount() {
    var count = $('#smartbatch-table tbody tr').length;
    $('#smartbatch-count').val(count);
    $('#smartbatch-table tbody tr').each(function(index) {
      $(this).find('.sb-index').text(index + 1);
    });
    updateSmartBatchTotals();
  }

  function updateSmartBatchTotals() {
    var subtotal = 0;
    var totalWeight = 0;
    $('#smartbatch-table tbody tr').each(function() {
      subtotal += parseSmartBatchNumber($(this).find('.sb-qty').val());
      totalWeight += parseSmartBatchNumber($(this).find('.sb-weight').val());
    });
    $('#smartbatch-subtotal').val(subtotal.toFixed(4));
    $('#smartbatch-totalweight').val(totalWeight.toFixed(4));
  }

  function syncSmartBatchWeightToRow($row) {
    if (!$row || !$row.length) {
      return;
    }
    var totalWeight = 0;
    var entries = parseSmartBatchData(getSmartBatchDataField($row).val());
    $.each(entries, function(_, entry) {
      var weight = parseFloat(entry.weight);
      if (!isNaN(weight)) {
        totalWeight += weight;
      }
    });
    getSmartBatchWeightField($row).val(totalWeight ? totalWeight.toFixed(4) : '0').trigger('change');
  }

  function getNextBatchValue() {
    var maxVal = currentBatchStart;
    $('#smartbatch-table tbody tr').each(function() {
      var val = parseInt($(this).find('.sb-batch').val(), 10);
      if (!isNaN(val) && val > maxVal) {
        maxVal = val;
      }
    });
    return maxVal + 1;
  }

  function addSmartBatchRow(batchVal, qtyVal, weightVal) {
    var $row = $('<tr>' +
      '<td class="sb-index"></td>' +
      '<td><input type="text" class="form-control sb-batch" /></td>' +
      '<td><input type="number" step="0.0001" class="form-control sb-qty" required value="0" /></td>' +
      '<td><input type="number" step="0.0001" class="form-control sb-weight" required value="0" /></td>' +
      '<td><button type="button" class="btn btn-danger btn-xs smartbatch-remove">Delete</button></td>' +
    '</tr>');
    if (batchVal === undefined || batchVal === '') {
      batchVal = getNextBatchValue();
    }
    $row.find('.sb-batch').val(batchVal).prop('readonly', true);
    if (qtyVal !== undefined) {
      $row.find('.sb-qty').val(qtyVal);
    }
    if (weightVal !== undefined) {
      $row.find('.sb-weight').val(weightVal);
    }
    $('#smartbatch-table tbody').append($row);
    updateSmartBatchCount();
  }

  function parseSmartBatchData(raw) {
    if (!raw) {
      return [];
    }
    try {
      var data = JSON.parse(raw);
      if ($.isArray(data)) {
        return data;
      }
    } catch (e) {}
    return [];
  }

  function renderSmartBatchRows(entries) {
    $('#smartbatch-table tbody').empty();
    if (!entries.length) {
      addSmartBatchRow('', '', '');
      return;
    }
    $.each(entries, function(_, entry) {
      addSmartBatchRow(entry.batch || entry.batch_code || '', entry.qty || '', entry.weight || '');
    });
  }

  $(document)
    .off('click.smartbatchOpen', '.smartbatch-open')
    .on('click.smartbatchOpen', '.smartbatch-open', function() {
      currentRow = $(this).closest('tr');
      var lastBatch = parseInt($(this).data('lastbatch'), 10);
      currentBatchStart = isNaN(lastBatch) ? 0 : lastBatch;
      var itemText = $(this).data('item') || getRowItemText(currentRow);
      var entries = parseSmartBatchData(getSmartBatchDataField(currentRow).val());
      var totalQty = getSmartBatchRowTotalQty(currentRow, entries);
      $('#smartbatch-warehouse').val(getRowWarehouseText(currentRow));
      $('#smartbatch-item').val(itemText);
      $('#smartbatch-totalqty').val(formatSmartBatchNumber(totalQty));
      $('#smartbatch-uom').val(getRowUomText(currentRow));
      renderSmartBatchRows(entries);
      syncSmartBatchWeightToRow(currentRow);
      toggleSmartBatchModal('show');
    });

  $(document)
    .off('click.smartbatchAdd', '#smartbatch-add')
    .on('click.smartbatchAdd', '#smartbatch-add', function() {
      addSmartBatchRow('', '', '');
    });

  $(document)
    .off('click.smartbatchRemove', '.smartbatch-remove')
    .on('click.smartbatchRemove', '.smartbatch-remove', function() {
      $(this).closest('tr').remove();
      updateSmartBatchCount();
    });

  $(document)
    .off('input.smartbatchTotals change.smartbatchTotals', '.sb-qty, .sb-weight')
    .on('input.smartbatchTotals change.smartbatchTotals', '.sb-qty, .sb-weight', function() {
      updateSmartBatchTotals();
      if (currentRow) {
        getSmartBatchWeightField(currentRow).val($('#smartbatch-totalweight').val()).trigger('change');
      }
    });

  $(document)
    .off('keydown.smartbatchQty', '#smartbatch-table .sb-qty')
    .on('keydown.smartbatchQty', '#smartbatch-table .sb-qty', function(e) {
      if (e.key === 'Enter' || e.keyCode === 13) {
        e.preventDefault();
        addSmartBatchRow('', '', '');
        $('#smartbatch-table tbody tr:last .sb-qty').focus();
      }
    });

  $(document)
    .off('click.smartbatchClose', '#smartBatchModal .smartbatch-close, #smartBatchModal [data-dismiss="modal"], #smartBatchModal [data-bs-dismiss="modal"]')
    .on('click.smartbatchClose', '#smartBatchModal .smartbatch-close, #smartBatchModal [data-dismiss="modal"], #smartBatchModal [data-bs-dismiss="modal"]', function(e) {
      e.preventDefault();
      closeSmartBatchModal();
    });

  $('#smartbatch-save')
    .off('click.smartbatchSave')
    .on('click.smartbatchSave', function() {
      if (!currentRow) {
        return;
      }
      var entries = [];
      var totalQty = parseFloat($('#smartbatch-totalqty').val());
      var sumQty = 0;
      var hasError = false;
      $('#smartbatch-table tbody tr').each(function() {
        var batch = $.trim($(this).find('.sb-batch').val());
        var qty = parseSmartBatchNumber($(this).find('.sb-qty').val());
        var weight = parseSmartBatchNumber($(this).find('.sb-weight').val());
        if (batch === '' && (isNaN(qty) || qty === 0) && (isNaN(weight) || weight === 0)) {
          return;
        }
        if (batch === '' || qty <= 0 || weight < 0) {
          hasError = true;
          return false;
        }
        entries.push({ batch: batch, batch_code: batch, qty: qty.toFixed(4), weight: weight.toFixed(4) });
        sumQty += qty;
      });
      if (hasError || entries.length === 0) {
        alert('Please enter valid batch code, quantity, and weight for each row.');
        return;
      }
      if (!isNaN(totalQty) && totalQty > 0 && Math.abs(sumQty - totalQty) > 0.0001) {
        alert('Batch total qty must equal Total Qty.');
        return;
      }
      getSmartBatchDataField(currentRow).val(JSON.stringify(entries));
      currentRow.find('.smartbatch-view').text('View (' + entries.length + ')').show();

      syncSmartBatchQtyToRow(currentRow, entries);
      syncSmartBatchWeightToRow(currentRow);
      closeSmartBatchModal();
    });

  $('form')
    .off('submit.smartbatchValidation')
    .on('submit.smartbatchValidation', function(e) {
      var missing = false;
      $('.smartbatch-open').each(function() {
        var $row = $(this).closest('tr');
        if ($(this).is(':visible') && getSmartBatchDataField($row).val() === '') {
          missing = true;
          return false;
        }
      });
      if (missing) {
        alert('Please enter batch details for all items.');
        e.preventDefault();
      }
    });


  decorateSmartBatchButtons($('#psearch'));
  var psearchNode = document.getElementById('psearch');
  if (psearchNode && window.MutationObserver) {
    new MutationObserver(function() {
      decorateSmartBatchButtons($('#psearch'));
    }).observe(psearchNode, {
      childList: true,
      subtree: true
    });
  }
});
</script>
<?php } ?>

    
    <?php include('../layout/sidebar2.php'); ?>

<script type="text/javascript">
(function($){
  var shippingMode = <?php echo (isset($_GET['shipping']) && $_GET['shipping']==1) ? 'true' : 'false'; ?>;
  if (shippingMode) {
    return;
  }

  function hideKgUnitOnTable($table) {
    if (!$table || !$table.length) {
      return;
    }

    var columnIndexes = [];

    $table.find("input[name='custom_field1[]']").each(function() {
      var colIndex = $(this).closest("td").index();
      if (colIndex >= 0 && $.inArray(colIndex, columnIndexes) === -1) {
        columnIndexes.push(colIndex);
      }
    });

    if (!columnIndexes.length) {
      $table.find("th").each(function(index) {
        var headerText = $.trim($(this).text()).replace(/\s+/g, " ").toLowerCase();
        if (headerText === "kg / unit" || headerText === "kg/unit" || headerText.indexOf("kg / unit") !== -1) {
          if ($.inArray(index, columnIndexes) === -1) {
            columnIndexes.push(index);
          }
        }
      });
    }

    if (!columnIndexes.length) {
      return;
    }

    $table.find("tr").each(function() {
      var $cells = $(this).children("th,td");
      $.each(columnIndexes, function(_, index) {
        $cells.eq(index).hide();
      });
    });
  }

  function applyKgUnitVisibility() {
    hideKgUnitOnTable($("#acart"));
    $("#psearch").find("table").each(function() {
      hideKgUnitOnTable($(this));
    });
  }

  $(document).ready(function() {
    applyKgUnitVisibility();
    setTimeout(applyKgUnitVisibility, 200);

    if (window.MutationObserver) {
      var cartBody = document.querySelector("#acart tbody");
      if (cartBody) {
        new MutationObserver(applyKgUnitVisibility).observe(cartBody, {
          childList: true,
          subtree: true
        });
      }

      var psearchNode = document.getElementById("psearch");
      if (psearchNode) {
        new MutationObserver(applyKgUnitVisibility).observe(psearchNode, {
          childList: true,
          subtree: true
        });
      }
    }
  });
})(jQuery);
</script>

      
        
<script type="text/javascript">

<?php if($info3000['en_vendor_detailinvoicehistory'] == 1){ ?>  
$(document).on("change", ".cid", function(e)
{
    var cid = $(".cid").val();
    $.ajax
    ({
        type: "POST",
        url: "../ajax/receipt-query5.php",
        
        data: { vid_history : cid },
        cache: false,
        dataType : 'html',
        success: function(html)
        {
            $(".purchaseinv_history").html(html);
        }
    });
});
<?php } ?>




</script> 

<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>

<script type="text/javascript">
 
 
  $(document).ready(function () {
    
    $('.save').hide();
 $('.edit-input').attr("readonly", true);
 
 $(document).on('click', ".edit", function(){
  $(this).closest('tr').find('.edit').hide();
  $(this).closest('tr').find('.save').show();
  
  $(this).closest('tr').find('.edit-input').attr("readonly", false);
});

$(document).on('click', ".save", function(){
  $(this).closest('tr').find('.save').hide();
  $(this).closest('tr').find('.edit').show();
  
  $(this).closest('tr').find('.edit-input').attr("readonly", true); 
   // Hamza
   $("input[name='currency_rate']").trigger('change');
//Hamza end
});
     
    
    
           $('.delete').on('click',function() {
    

 var ee = $(this).closest( 'tr').find('.products').val();
    
    
$.ajax
({
type: "POST",
url: "../ajax/receipt-query3.php",

data: { ncart2 : ee },
cache: false,
dataType : 'html',
success: function(html)
{
alert(html);

}
});
 

    
  $(this).closest( 'tr').remove();
 


//Total Quantity Sum  (Pcs)
    var sum = 0;
    $(".total_pcs").each(function(){
        sum += +$(this).val();
    });
    $("#total_pcs").val(sum);


//Total Quantity Sum  (Carton)
    var sum3 = 0;
    $(".packing").each(function(){
        sum3 += +$(this).val();
    });
    $("#packing").val(sum3);



//Total Amount Sum  (Sub Total)
    var sum2 = 0;
    $(".sub_total").each(function(){
        sum2 += +$(this).val();
    });
    $("#sub_total").val(sum2);



  var n4 = $("#sub_total").val();
      
   var n5 = $("#paid_amount").val();
    var n6 = $("#pending_amount").val();
    

     var total = +n4 ;
   var pending = +total - n5;
      $("#total_amount").val(total);
      if (isNaN(pending) || pending === null || pending === '') {
        pending = 0;
    }
    $("#pending_amount").val(pending);

  
     });

 });  
   
   
    </script>    





<script type="text/javascript">


<?php if($info3000['en_ajk']==1){?>
    $("#vendor_id").change(function() {
        var vendorId = $(this).val();
    
        $.ajax({
            url: "../ajax/ajax-pk4.php", 
            method: "POST",
            data: { vid5533 : vendorId },
            success: function(response) {
                $('.duebalance').text(response);
            }
        });
    });
<?php }?>

var $form = $('#slip'),
    $summands = $form.find('.income_count'),
    $sumDisplay = $('#income_sum');

$(".income_count").change( function(){
    
    var sum = 0;
    $summands.each(function ()
    {
        
        var value = Number($(this).val());
        if (!isNaN(value)) sum += value;
    });
    $sumDisplay.val(sum);
});  

function ptotal(id){
var a=id;
var val= $("#" + a).val();
var val2= $("#n" + a).val();
ptot=val*val2;

 $("." + a).val(ptot);
};


var $form = $('#slip'),
    $summands2 = $form.find('.ptotal'),
    $sumDisplay2 = $('#sub_total');

$(".income_count").change( function(){
    
    var sum2 = 0;
    $summands2.each(function ()
    {
        
        var value = Number($(this).val());
        if (!isNaN(value)) sum2 += value;
    });
    $sumDisplay2.val(sum2);
});  


$(document).on("change", "#currency", function(e){

        
        
        var empid = $("#currency").val();


$.ajax
({
type: "POST",
url: "../ajax/receipt-query2.php",

data: { currencyrate : empid },
cache: false,
dataType : 'html',
success: function(html)
{
$(".currencyfilter").html(html);

}
});
 
      
    
       });
             
             
 $("#currency").trigger("change");             

// Basit
<?php if($info3000['en_hapaperhub'] == 1){ ?>
$(document).on('change', '.mycf', function(e) 
{
    var row = $(this).closest(".carttr");
    var id = this.id.replace('customfield', '');
    var customfield1new = $(this).val() || "";
    
    if (customfield1new) 
    {
        var values = customfield1new.toString().replace(/\s/g, '').split(',');
        var sum = 0;
        
        for (var i = 0; i < values.length; i++) 
        {
            var num = parseFloat(values[i]) || 0;
            sum += num;
        }
        
        row.find("#ctn" + id)
            .val(sum)
            .trigger('change');
        
        // console.log("Sum calculated:", sum);
    }
});
<?php } ?>

$(".searchqty, .income_count, #sub_total, #paid_amount, #pending_amount, #paid_amount, #order_cost").change( function(){

    var decimal_point = "<?php echo $info2000['total_decimal']; ?>";

    var n4 = $("#sub_total").val();
    var n5 = $("#paid_amount").val();
    var n6 = $("#pending_amount").val();
      
    var total = +n4;
    var pending = +total - n5;
    total = total.toFixed(decimal_point);
    pending = pending.toFixed(decimal_point);
    $("#total_amount").val(total);
    if (isNaN(pending) || pending === null || pending === '') {
        pending = 0;
    }
    $("#pending_amount").val(pending);


});

 



</script> 


<?php
if ($info3000['multiplemanager_approvals'] == 1) {
    $approval1 = mysqli_get_var("SELECT level FROM approval_level WHERE stype = 4 AND approval = 1");
    $approval2 = mysqli_get_var("SELECT level FROM approval_level WHERE stype = 4 AND approval = 2");
    $approval3 = mysqli_get_var("SELECT level FROM approval_level WHERE stype = 4 AND approval = 3");
    ?>
    <script type="text/javascript">
      console.log("in section");
    $(document).ready(function(){
        $(document).on("change", ".income_count", function(e){
            setTimeout(function(){
              console.log("Total changed");
              var total_amount = parseFloat($("#total").val()) || 0;
              <?php if (!empty($approval1)) { ?>
                  if(total_amount >= <?php echo (float)$approval1; ?>){
                      $("#manager_1").prop('required', true);
                  } else {
                      $("#manager_1").prop('required', false);
                  }
              <?php } ?>
              <?php if (!empty($approval2)) { ?>
                  if(total_amount >= <?php echo (float)$approval2; ?>){
                      $("#manager_2").prop('required', true);
                  } else {
                      $("#manager_2").prop('required', false);
                  }
              <?php } ?>
              <?php if (!empty($approval3)) { ?>
                  if(total_amount >= <?php echo (float)$approval3; ?>){
                      $("#manager_3").prop('required', true);
                  } else {
                      $("#manager_3").prop('required', false);
                  }
              <?php } ?>
            },500);
        });
    });
    </script>
    <?php
}
?>

<script type="text/javascript">
  
       $(document).ready(function () {
         
<?php  if($info4000['en_nooriinternational']==1) { ?>

$(".addclass").change(function(){
var value=$(this).val();
// console.log(value);
// alert(value);

 var closestRow = $(this).closest("tr");

   // Check if the condition is met (e.g., value is equal to 1)
      // Replace this with your actual condition
       
        if (value == 1) {
         
            closestRow.addClass("trade_no_impact");
            
            closestRow.find('.specialclass').val('trade_no_impact');
           
            $(".searchqty, .rice_discount_value, .income_count, #sub_total, #paid_amount, #pending_amount, #paid_amount, #order_cost, #tax, #shipping, #discount").trigger("change");
       
        } else {

            closestRow.removeClass("trade_no_impact"); 
            closestRow.find('.specialclass').val('');
            $(".searchqty, .rice_discount_value, .income_count, #sub_total, #paid_amount, #pending_amount, #paid_amount, #order_cost, #tax, #shipping, #discount").trigger("change");
            // Replace "highlight" with your desired class name
        }

});

<?php } ?>

         
          <?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 } ?>
         
    
         
         
            $('.cid').focus();
        var lockPurchaseItemAdd = <?php echo $lock_item_add ? 'true' : 'false'; ?>;
      var useAjaxProductSearch = <?php echo ($use_ajax_search==1 ? 'true' : 'false'); ?>;
      var purchaseSearchMinChars = <?php echo (isset($info3000['search_cher']) && (int)$info3000['search_cher'] >= 0 && (int)$info3000['search_cher'] <= 5) ? (int)$info3000['search_cher'] : 0; ?>;
        function enforceProjectItemLock($scope) {
          if (!lockPurchaseItemAdd) {
            return;
          }
          var $ctx = ($scope && $scope.length) ? $scope : $(document);
          $ctx.find("#product_search, #searchbox, #search4").prop("disabled", true);
          if ($.fn.select2) {
            $ctx.find("#product_search.select2-hidden-accessible, #searchbox.select2-hidden-accessible").each(function() {
              $(this).trigger("change.select2");
            });
          }
        }
        enforceProjectItemLock($(".itemchange"));

function getPurchaseProductSearchFilters() {
  return {
    cat: ($("#inv_cat").val() || "a"),
    subcat: ($("#inv_subcat").val() || "a"),
    subsub: ($("#inv_subsub").val() || "a"),
    brand: ($("#inv_brand").val() || "a")
  };
}

function initPurchaseProductSearch($scope) {
  if (!$.fn.select2) {
    return;
  }
  var $ctx = ($scope && $scope.length) ? $scope : $(document);
  var $targets = $ctx.find("#product_search, #searchbox");
  if (!$targets.length && $ctx[0] !== document) {
    $targets = $("#product_search, #searchbox");
  }
  $targets.each(function() {
    var $select = $(this);
    var placeholderText = $select.find("option:first").text() || "Select a <?php echo $info1000['product_label']; ?>...";
    if ($select.hasClass("select2-hidden-accessible")) {
      $select.filter(".select2-hidden-accessible").select2("destroy");
    }
    if (useAjaxProductSearch && !$select.prop("disabled")) {
      $select.empty().append(new Option(placeholderText, ""));
      $select.select2({
        width: "100%",
        minimumInputLength: purchaseSearchMinChars,
        placeholder: placeholderText,
        allowClear: true,
        ajax: {
          url: "../ajax/serial-query.php",
          type: "POST",
          dataType: "json",
          delay: 250,
          data: function(params) {
            var filters = getPurchaseProductSearchFilters();
            return {
              purchase_product_search: 1,
              term: params.term || "",
              cat: filters.cat,
              subcat: filters.subcat,
              subsub: filters.subsub,
              brand: filters.brand
            };
          },
          processResults: function(data) {
            if (data && data.results) {
              return data;
            }
            if ($.isArray(data)) {
              return { results: data };
            }
            return { results: [] };
          },
          cache: true
        }
      });
    } else {
      $select.select2();
    }
  });
}

function selectPurchaseProductById(productId) {
  var pid = $.trim(String(productId || ""));
  if (!pid) {
    return;
  }
  var $productSelect = $("#product_search");
  if (!$productSelect.length) {
    $productSelect = $("#searchbox");
  }
  if (!$productSelect.length) {
    return;
  }
  if (!useAjaxProductSearch) {
    $productSelect.val(pid).trigger("change");
    return;
  }
  $.ajax({
    type: "POST",
    url: "../ajax/serial-query.php",
    dataType: "json",
    data: {
      purchase_product_by_id: 1,
      id: pid
    },
    success: function(res) {
      if (res && res.id) {
        var option = new Option(res.text, res.id, true, true);
        $productSelect.append(option).trigger("change");
      } else {
        $productSelect.val(pid).trigger("change");
      }
    }
  });
}

window.bmsReinitPurchaseProductSearch = function($scope) {
  initPurchaseProductSearch(($scope && $scope.length) ? $scope : $(".itemchange"));
};

initPurchaseProductSearch($(".itemchange"));
           
               
      $('#brandfilter').change(function () { 
        
        
        var empid = $("#brandfilter").val();


$.ajax
({
type: "POST",
url: "../ajax/receipt-query2.php",

data: { brandfilter : empid },
cache: false,
dataType : 'html',
success: function(html)
{
$(".brandfilter").html(html);
if (!lockPurchaseItemAdd) { $('#product_search').focus(); }

}
});
 
      
    
       });
       

function reinitPurchaseSelect2($scope) {
  if (!$.fn.select2) {
    enforceProjectItemLock($scope);
    return;
  }
  $scope.find(".combobox, .reportselect").each(function() {
    var $select = $(this);
    var isProductSearch = ($select.attr("id") === "product_search" || $select.attr("id") === "searchbox");
    if (isProductSearch && useAjaxProductSearch) {
      return;
    }
    if ($select.hasClass("select2-hidden-accessible")) {
      $select.filter('.select2-hidden-accessible').select2("destroy");
    }
    $select.select2();
  });
  initPurchaseProductSearch($scope);
  enforceProjectItemLock($scope);
}

function applyPurchaseProductFilters(productId) {
  if (!productId) {
    return;
  }

  $.ajax({
    type: "POST",
    url: "../ajax/serial-query.php",
    data: { product_meta: productId },
    dataType: "json",
    success: function(meta) {
      var cat = meta && meta.cat ? String(meta.cat) : "a";
      var subcat = meta && meta.subcat ? String(meta.subcat) : "a";
      var subsub = meta && meta.subsub ? String(meta.subsub) : "a";
      var brand = meta && meta.brand ? String(meta.brand) : "a";

      $("#inv_cat").val(cat);

      var subcatRequest = $.ajax({
        type: "POST",
        url: "../ajax/serial-query.php",
        data: { inv_subtype_by_type: cat },
        cache: false,
        dataType: "html",
        success: function(html) {
          var $wrap = $(".inv-subcat-wrap");
          $wrap.html(html);
          reinitPurchaseSelect2($wrap);
          $("#inv_subcat").val(subcat);
        }
      });

      var subsubRequest = $.ajax({
        type: "POST",
        url: "../ajax/serial-query.php",
        data: { inv_subsub_by_subtype: subcat },
        cache: false,
        dataType: "html",
        success: function(html) {
          var $wrap = $(".inv-subsub-wrap");
          $wrap.html(html);
          reinitPurchaseSelect2($wrap);
          $("#inv_subsub").val(subsub);
        }
      });

      $.when(subcatRequest, subsubRequest).done(function() {
        $("#inv_brand").val(brand).trigger("change");
      });
    }
  });
}

function updatePurchaseProducts() {
  var cat = $("#inv_cat").val();
  var subcat = $("#inv_subcat").val();
  var subsub = $("#inv_subsub").val();
  var brand = $("#inv_brand").val();

  var $wrap = $(".itemchange");
  if (useAjaxProductSearch) {
    initPurchaseProductSearch($wrap);
    enforceProjectItemLock($wrap);
    return;
  }

  var $existing = $wrap.find("#product_search");
  if ($existing.length && $existing.hasClass("select2-hidden-accessible")) {
    $existing.filter('.select2-hidden-accessible').select2("destroy");
  }

  $.ajax({
    type: "POST",
    url: "../ajax/serial-query.php",
    data: {
      inv_items_filter: 1,
      cat: cat,
      subcat: subcat,
      subsub: subsub,
      brand: brand
    },
    cache: false,
    dataType: "html",
    success: function(html) {
      $wrap.html(html);
      reinitPurchaseSelect2($wrap);
      enforceProjectItemLock($wrap);
    }
  });
}

$(document).on("change", "#inv_cat", function() {
  var cat = $("#inv_cat").val();
  $("#inv_subcat").val("a");
  $("#inv_subsub").val("a");
  $("#inv_brand").val("a");

  $.ajax({
    type: "POST",
    url: "../ajax/serial-query.php",
    data: { inv_subtype_by_type: cat },
    cache: false,
    dataType: "html",
    success: function(html) {
      var $wrap = $(".inv-subcat-wrap");
      $wrap.html(html);
      $("#inv_subcat").val("a");
      reinitPurchaseSelect2($wrap);
    }
  });

  $.ajax({
    type: "POST",
    url: "../ajax/serial-query.php",
    data: { inv_subsub_by_subtype: "a" },
    cache: false,
    dataType: "html",
    success: function(html) {
      var $wrap = $(".inv-subsub-wrap");
      $wrap.html(html);
      $("#inv_subsub").val("a");
      reinitPurchaseSelect2($wrap);
    }
  });

  $.ajax({
    type: "POST",
    url: "../ajax/serial-query.php",
    data: { inv_brand_by_type: cat },
    cache: false,
    dataType: "html",
    success: function(html) {
      var $wrap = $(".inv-brand-wrap");
      $wrap.html(html);
      $("#inv_brand").val("a");
      reinitPurchaseSelect2($wrap);
    }
  });

  updatePurchaseProducts();
});

$(document).on("change", "#inv_subcat", function() {
  var subcat = $("#inv_subcat").val();
  $("#inv_subsub").val("a");
  $.ajax({
    type: "POST",
    url: "../ajax/serial-query.php",
    data: { inv_subsub_by_subtype: subcat },
    cache: false,
    dataType: "html",
    success: function(html) {
      var $wrap = $(".inv-subsub-wrap");
      $wrap.html(html);
      $("#inv_subsub").val("a");
      reinitPurchaseSelect2($wrap);
    }
  });

  updatePurchaseProducts();
});

$(document).on("change", "#inv_subsub", function() {
  updatePurchaseProducts();
});

$(document).on("change", "#inv_brand", function() {
  updatePurchaseProducts();
});

$(document).on("select2:select select2:clear", "#inv_cat, #inv_subcat, #inv_subsub, #inv_brand", function() {
  updatePurchaseProducts();
});

function focusPurchaseProductSearch() {
  var $target = $("#searchbox:visible:not([disabled])");
  if ($target.length) {
    $target.focus();
    return;
  }
  $target = $(".baccodesearch:visible:not([disabled])");
  if ($target.length) {
    $target.first().focus();
    return;
  }
  $target = $("#product_search");
  if ($target.length) {
    if ($target.prop("disabled")) {
      return;
    }
    if ($target.data("select2")) {
      $target.select2("open");
    } else {
      $target.focus();
    }
  }
}

$(document).on("keydown", "#acart input, #acart select, #acart textarea", function(e) {
  if (e.key !== "Tab" || e.shiftKey) {
    return;
  }
  var $row = $(this).closest("tr");
  var $focusables = $row
    .find("input, select, textarea")
    .filter(":visible:not([disabled])");
  if (!$focusables.length) {
    return;
  }
  if ($focusables.index(this) === $focusables.length - 1) {
    e.preventDefault();
    focusPurchaseProductSearch();
  }
});


$(document).on('click', '.itemchange5', function () { 
  var cid = $(".cat1").val();
   $.ajax({
    type: "POST",
    url: "../ajax/serial-query.php",
    data: { depart2900 : cid  },
    cache: false,
    dataType : 'html',
    success: function(html){
        $(".itemchange").html(html);
      reinitPurchaseSelect2($(".itemchange"));
    }
  });
});        
    
         <?php if($info2000['noduplicate_item'] == 1){ ?>
          let serial_values = [];
      <?php } ?>
        $(document).on("change", "#product_search, #searchbox", function(e){
        if (lockPurchaseItemAdd) {
          $(this).val("");
          return;
        }
        
        var $productSelect = $(this);
        var empid = $productSelect.val();
    applyPurchaseProductFilters(empid);
        var cid = $(".cid").val();
            var dist_id = $("#dist_to_id").val(); 
        var wid = $("#warehousefilter").val();      
        var lid = $("#locationfilter").val(); 


if($('#on_record').prop("checked") == true){
               var sst = 1;
            }
            else {
                var sst = 1;
            }
      <?php if($info2000['noduplicate_item'] == 1){ ?>
      let check_val = empid;

     if (serial_values.includes(check_val)) {
        $productSelect.val("");
        alert('Product already exists!');
        return;
    } else    
        serial_values.push(check_val);
    <?php } ?>
$.ajax({
type: "POST",
url: "../ajax/receipt-query.php",

data: { pid : empid , vendorid : cid  , st : sst, return : 0 , dist_id : dist_id, lid : lid, po_withoutvalue : <?php echo $po_withoutvalue ? 1 : 0; ?> },
cache: false,
dataType : 'html',
success: function(html)
{
$("#psearch").html(html);
// $("#psearch").html(html);
 if ($("select.munit:first")[0]) {
        $("select.munit:first").trigger("change");
    } else {
        console.log("munit select box nahi mila!");
    }
<?php if($info4000['warehousefilter_invoice']==1){ ?>
    $(".psearch").find(".warehouse").val(wid);
<?php } ?>
    $(".psearch").find(".warehouse").trigger("change");
    var $tempRowTrigger = $("#psearch").find(".change15, .change8, .change7, .change6, .change5").first();
    if ($tempRowTrigger.length) {
        $tempRowTrigger.trigger("focusout");
    }
$productSelect.val('');
$('.searchp:first').focus();

<?php if($info3000['en_buraqcorp']==1){ ?>
    $(".customfield1").attr('type', 'date');
    $(".customfield2").attr('type', 'date');
<?php } ?>
}
});
    
 
        // Hamza
       $("input[name='currency_rate']").trigger('change');
       //Hamza end
    
       });
       
<?php
if($info4000['warehousefilter_invoice']==1){
?>
$('#warehousefilter').on('change', function() {

var wid = this.value;

$(".warehouse").val(wid);
$('.warehouse').trigger('change');
}); 
<?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);

}
});
 
      
    
       });

       
// Hamza
<?php if($info1000['en_inventorybatch']==1 && $info3000['open_batchgrn']==1  && $info2000['batch_grnonly']==1){ ?>

let typingTimer;
let doneTypingInterval = 200;
$(document).on("input", "input[name='products_batch[]']", function() {
    clearTimeout(typingTimer);
    let currentInput = $(this);
    typingTimer = setTimeout(function() {
        let currentValue = currentInput.val().trim();
        if (currentValue !== "") {
            let isDuplicate = false;
            $("input[name='products_batch[]']").each(function(index, element) {
                if (element !== currentInput[0] && $(element).val().trim() === currentValue) {
                    isDuplicate = true;
                    return false;
                }
            });
            if (isDuplicate) {
                alert("Duplicate value found: " + currentValue);
                currentInput.val("").focus();
                return;
            }
            let next = $("input[name='products_batch[]']").eq(
                $("input[name='products_batch[]']").index(currentInput) + 1
            );
            if (next.length) {
                next.attr("tabindex", 1000).focus();
            }
        }
    }, doneTypingInterval);
});

$(document).on('change blur', '.qtyCheck', function() {
    let qty = parseInt($('.searchp').val()) || 0;
    let price = parseInt($('.ptotal').val()) || 0;
    let ptotal = 0;
    if(qty > 1){
         ptotal = price/qty;
    }else{
        ptotal = price;
    }
    let tbody = $('#acart').find('tbody');
    let get_tbody = $('#dynamic-table').find('tbody tr').first(); 

    for (let i = 0; i < qty; i++) {
        let row = get_tbody.clone(); 
        // row.find('input[name="products_packing[]"]').closest('td').hide();
        // row.find('input[name="products_packing2[]"]').closest('td').hide();
        row.find('.searchp').val(1);
        row.find('input[name="products_pcs[]"]').val(1);
        row.find('input[name="products_total[]"]').val(ptotal);
        row.find('.qtyCheck').removeClass('qtyCheck');
        tbody.append(row);
    }
    $('#psearch').empty();
});

<?php } ?>

// Hamza end
$('#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">

$('input').bind('keydown',function(e) {
    if (e.keyCode==40) {
        $(this).next('input').focus();
    }
});



$('#on_services').click(function () {
if ( $(this).is(':checked') ){
       window.open("new-purchases.php", "_self");
}

});



$('#on_assets').click(function () {
if ( $(this).is(':checked') ){
       window.open("new-purchasea.php", "_self");
}

});




$('#on_component').click(function () {
if ( $(this).is(':checked') ){
       window.open("new-purchasec.php", "_self");
}

});


</script>


<script type="text/javascript">


$(document).keydown(function(e) {
        if (e.keyCode == 65 && e.altKey) {
           var unit = $("*:focus").attr("id");
           unit = unit.replace(/\D/g, '');

           lol = document.getElementById('u' + unit + '').value;
            alert(lol);
        }
    });



$(function() {
    $('.trdiv').hide(); 
    $('#tr').change(function(){
        if($('#tr').val() == 'y') {
            $('.trdiv').show(); 
        } else {
            $('.trdiv').hide(); 
        } 
    });
});



//Hamza
<?php if($info2000['search_multibarcode']==1){?>
    $("#search4").on('change keyup',function(e) {
        var len = $("#search4").val().length;
        if (len >= <?php echo $info2000['barcode_limit']; ?>) {
            var bb =  $("#search4").val();
            $("#search7").val(bb);
            $("#search4").val("");
            var dataString = '&barcodescan5='+ encodeURIComponent(bb) + '&returnPage=1';
            $.ajax({
                type: "POST",
                url: "../ajax/purchase-query.php",
                data: dataString,
                cache: false,
                dataType : 'html',
                success: function(html){
                    let valueToMatch = html.trim();
                    selectPurchaseProductById(valueToMatch);
                    $("#search4").focus();
                } 
            });
        }
    });

//     $("#search4").on('change keyup',function(e) {

//     if(e.keyCode == 13 || e.keyCode == 9){


//         var len = $("#search4").val().length;
//         var bb =  $("#search4").val();

//                  $.ajax
//                  ({
//                          type: "POST",
//                          url: "../ajax/ajax-grid-pos.php",

//                          data: { barcode : bb },
//                          cache: false,
//                          dataType : 'html',
//                          success: function(html)
//                          {
//                              $("#home").html("");
//                            $("#home").html(html);
//                            $("#home").load(location.href + " #home");
                              
                              
//                              if($('#'+ bb).length){
//             if(len><?php //echo $info2000['barcode_limit']; ?>) {
//                 $('#'+ bb).closest('.item-box').trigger('click');
//                 $("#search4").val("");
//             }
//         }else{
//             if(len>1) {  
//                 $(".noitem-alert").show();
//              $('#search4').prop('readonly', true);
//                 $("#search4").val("");
//                 // var x = document.getElementById("myAudio"); 
//                 //  x.play();
//             }
//          $("#search4").val("");
//          $("#search4").focus();
//         }
                              
//                          }
//                  });



// // sleep(4000);
// // console.log('delay 1 second');

      
//     }

    
     
     
// });
<?php }else if($info2000['search_multibarcode']==2) { ?>

let scanTimer;
$("#search4").on('input',function(e) {
      clearTimeout(scanTimer); 
    scanTimer = setTimeout(() => {
    var len = $("#search4").val().length;
    if (len >= <?php echo $info2000['barcode_limit']; ?>) {
    // if(e.keyCode == 13 || e.keyCode == 9){
    var bb =  $("#search4").val();


var dataString = '&barcodescan5='+ encodeURIComponent(bb) + '&returnPage=0';
$.ajax
({
type: "POST",
url: "../ajax/purchase-query.php",

data: dataString,
cache: false,
dataType : 'html',
success: function(html)
{
 selectPurchaseProductById(html);

 $("#search4").val("");
$("#search4").focus();


} 
});



//   }
         
     }
    }, 200); 

     
});
<?php }?>






</script>


<style >
body {
    overflow-x:hidden;}
</style>


<script>
function bmsOpenInlineDirectPopup(url, popupName, modalTitle) {
    var modalEl = document.getElementById('bmsInlineFrameModal');
    var frameEl = document.getElementById('bmsInlineFrame');
    if (!modalEl || !frameEl) {
        window.open(url, popupName || 'bmsInlineDirectPopup', 'width=1180,height=840,scrollbars=yes,resizable=yes');
        return false;
    }
    $('#bmsInlineFrameTitle').text(modalTitle || 'Quick Create');
    frameEl.src = url;
    if (window.bootstrap && typeof window.bootstrap.Modal === 'function') {
        window.bmsInlineFrameModalInstance = window.bootstrap.Modal.getOrCreateInstance(modalEl);
        window.bmsInlineFrameModalInstance.show();
    } else if (window.jQuery && typeof $(modalEl).modal === 'function') {
        $(modalEl).modal('show');
    } else {
        window.open(url, popupName || 'bmsInlineDirectPopup', 'width=1180,height=840,scrollbars=yes,resizable=yes');
    }
    return false;
}
function bmsCloseInlineFrameModal() {
    var modalEl = document.getElementById('bmsInlineFrameModal');
    var frameEl = document.getElementById('bmsInlineFrame');
    try {
        if (window.bmsInlineFrameModalInstance) {
            window.bmsInlineFrameModalInstance.hide();
        } else if (window.jQuery && modalEl && typeof $(modalEl).modal === 'function') {
            $(modalEl).modal('hide');
        }
    } catch (err) {
        console.warn('Inline quick create modal hide fallback triggered.', err);
    }
    if (modalEl) {
        modalEl.classList.remove('show');
        modalEl.style.display = 'none';
        modalEl.setAttribute('aria-hidden', 'true');
        modalEl.removeAttribute('aria-modal');
    }
    document.body.classList.remove('modal-open');
    document.body.style.removeProperty('overflow');
    document.body.style.removeProperty('padding-right');
    document.querySelectorAll('.modal-backdrop').forEach(function (backdrop) {
        backdrop.remove();
    });
    if (window.jQuery && modalEl) {
        $(modalEl).removeClass('show');
    }
    if (frameEl) {
        setTimeout(function () {
            frameEl.src = 'about:blank';
        }, 50);
    }
}
function bmsOpenPurchasePaymentFrame() {
    var vendorSelect = $("select[name='vendor_id']").first();
    var vendor = vendorSelect.val() || $('#vendor_id').val() || '0';
    var vendorLabel = $.trim((vendorSelect.find('option:selected').text() || '').replace(/\s+/g, ' '));
    if (!vendor || vendor === '0') {
        alert('Please select a vendor first.');
        return false;
    }
    var amount = $.trim(String($('#total').val() || '').replace(/,/g, ''));
    if (amount === '' || isNaN(parseFloat(amount)) || parseFloat(amount) <= 0) {
        alert('Please add product lines so the purchase amount is available.');
        return false;
    }
    var purchaseDate = $.trim($("input[name='date']").first().val() || '');
    var invoiceNumber = $.trim($("input[name='number']").first().val() || '');
    var brand = $.trim($('#inv_brand').val() || '');
    var details = invoiceNumber !== '' ? 'Payment against Purchase Invoice #' + invoiceNumber : 'Payment against Purchase Invoice';
    if (vendorLabel !== '') {
        details += ' | Vendor: ' + vendorLabel;
    }
    var query = $.param({
        vendor_id: vendor,
        amount: amount,
        date: purchaseDate,
        details: details,
        brandfilter: brand,
        inline_modal: 1
    });
    return bmsOpenInlineDirectPopup('../treasury/ppayment-voucher.php?' + query, 'purchasePaymentVoucherWindow', 'Create Payment');
}
function bmsInlineDirectSelectOption(selector, payload) {
    var $select = $(selector).first();
    if (!$select.length || !payload || !payload.id) {
        return;
    }
    var value = String(payload.id);
    if ($select.find("option[value='" + value + "']").length === 0) {
        $select.append($('<option>', { value: value, text: payload.label || value }));
    }
    $select.val(value);
    if (typeof reinitPurchaseSelect2 === "function") {
        reinitPurchaseSelect2($select.parent());
        $select = $(selector).first();
        $select.val(value);
    } else if ($.fn.select2 && !$select.hasClass("select2-hidden-accessible") && ($select.hasClass("combobox") || $select.hasClass("reportselect"))) {
        $select.select2();
    }
    $select.trigger('change');
    if ($.fn.select2 && ($select.hasClass("select2-hidden-accessible") || !!$select.data("select2"))) {
        $select.trigger('change.select2');
    }
}
function bmsInlineDirectSelectPurchaseItem(payload) {
    if (!payload || !payload.id) {
        return;
    }
    var $productSelect = $("#product_search");
    if (!$productSelect.length) {
        $productSelect = $("#searchbox");
    }
    if (!$productSelect.length) {
        return;
    }
    var value = String(payload.id);
    var label = payload.label || value;
    if ($productSelect.find("option[value='" + value + "']").length === 0) {
        $productSelect.append(new Option(label, value, true, true));
    } else {
        $productSelect.val(value);
    }
    $productSelect.trigger('change');
    if ($.fn.select2 && ($productSelect.hasClass("select2-hidden-accessible") || !!$productSelect.data("select2"))) {
        $productSelect.trigger('change.select2');
    }
}
window.bmsInlineDirectAddCallback = function (payload) {
    if (!payload || !payload.type) return;
    if (payload.type === 'vendor') {
        bmsInlineDirectSelectOption("select[name='vendor_id']", payload);
        bmsCloseInlineFrameModal();
        return;
    }
    if (payload.type === 'item') {
        bmsInlineDirectSelectPurchaseItem(payload);
        setTimeout(function () {
            bmsCloseInlineFrameModal();
        }, 250);
        return;
    }
    bmsCloseInlineFrameModal();
};
(function () {
    function validateAllInOnePayment() {
        var enabled = <?php echo $inline_form_direct_enabled ? 'true' : 'false'; ?>;
        if (!enabled) return true;
        var amount = parseFloat($('#paid_amount').val() || '0');
        if (!(amount > 0)) return true;
        var bank = $('.allinone-payment-bank').val() || '0';
        var mode = $('.allinone-payment-mode').val() || '0';
        var pdate = $('.allinone-payment-date').val() || '';
        if (bank === '0' || mode === '0' || pdate === '') {
            alert('Amount, cash/bank, payment method, and date are required when amount is entered.');
            return false;
        }
        return true;
    }
    $(document).on('submit', 'form', function (e) {
        if (!validateAllInOnePayment()) {
            e.preventDefault();
            return false;
        }
    });
})();
</script>


<div class="modal fade" id="bmsInlineFrameModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered" style="max-width:95vw;">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="bmsInlineFrameTitle">Quick Create</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body p-0">
        <iframe id="bmsInlineFrame" src="about:blank" style="width:100%; min-height:80vh; border:0;"></iframe>
      </div>
    </div>
  </div>
</div>

<?php include('../layout/footer.php'); ?>
<script type="text/javascript" >

$(document).ready(function() {
    $("#main-content").toggleClass("merge-left");
     $("#sidebar").toggleClass("hide-left-bar");
     
     $(".income_count").trigger("change");
   if (typeof window.bmsReinitPurchaseProductSearch === "function") {
     window.bmsReinitPurchaseProductSearch($(".itemchange"));
     setTimeout(function() {
       window.bmsReinitPurchaseProductSearch($(".itemchange"));
     }, 300);
     setTimeout(function() {
       window.bmsReinitPurchaseProductSearch($(".itemchange"));
     }, 900);
   }
     
     
});

// 

var prid = $("#prid").val();

if (prid != 0) 
{ 
    $.ajax({
        type: "POST",
        url: "../ajax/receipt-query17.php",
        data: { prid: prid },
        cache: false,
        dataType: 'html',
        success: function(html) {
            $(".cartcustom-overlay").html(html);
            $('.income_count').trigger('change');
        }
    });
}

// 

<?php  if($info4000['selectso_onpo']==1) {  ?>

           $('.selectso_onpo').change(function () { 
        
    

 var stock6 = $(this).val();


$.ajax
({
type: "POST",
url: "../ajax/receipt-query17.php",

data: { selectso_onpo : stock6  },
cache: false,
dataType : 'html',
success: function(html)
{
$(".cartcustom-overlay").html(html);

 $('.income_count').trigger('change');
}
});
 
          
    
       });
       
       

<?php } ?>

<?php if($info2000['en_filesystem']==1) { ?>


$('.filesystem').change(function () { 

$('.reportselect').filter('.select2-hidden-accessible').select2('destroy');     
        
var vid = $(".filesystem").val();



$.ajax
({
type: "POST",
url: "../ajax/serial-query2.php",

data: { filesystem : vid },
cache: false,
dataType : 'html',
success: function(html)
{
$(".cid").val(html);
$('.reportselect').select2();
if (typeof window.bmsReinitPurchaseProductSearch === "function") {
  window.bmsReinitPurchaseProductSearch($(".itemchange"));
}
$('.cid').trigger('change');
}
});
 });


<?php } ?>


<?php if($info2000['multiple_batch']==1) { ?>


$(document).on('click', ".tr_clone_add", function() {
    
       var $tr = $('#acart').find('tbody>tr:last');
       $tr.clone(true).insertAfter($tr);
      
       });
       

$(document).on('keydown', ".batch7", function() {
    if (this.value.length >= this.maxLength) {
    $(this).closest('.carttr').next('.carttr').find('.batch7').focus();
    }
});    
       
<?php } ?>

</script>
<!--Hamza-->
<script>
    $(document).on('change','#currency',function(){
        let select_text  = $(this).find('option:selected').text(); 
        $("input[name='currency_rate']").val(1);
        $("input[name='currency_rate']").trigger('change');
    });
    
    $(document).on('change', "input[name='currency_rate']", function () {
        let currency_rate = $(this).val() || 0;
        $("#acart tbody tr.carttr").each(function () {
            let total_usd = $(this).find("input[name='products_total[]']").val() || 0;
            let total = total_usd * currency_rate;
            $(this).find(".total_currency").val(total);
        });
    });
    $(document).ready(function () {
      if ($("#result90").length > 0) {
            $("#result90").css("display", "none");
        }
    });
</script>

<!--Hamza end-->
<script>

  
<?php if($info4000['en_metric_ton_qty']==1 ) { ?> $('.rice_rate option:eq(2)').attr('selected', 'selected'); <?php } ?>


 
$(document).on('change', '.minchange', function(){
    
    var cid = $(".cid").val();
    var reorderfilter = $("#reorderlevel").val();
  var itemlevel = $("#itemlevel").val();
  var reorderwarehouse = $("#reorderwarehouse").val();
  
  var product_ctype = $("#product_ctype").val();
  
  var vendorlimit = $("#vendorlimit").val();
  
  var reorderbrand = ''; 
$('#reorderbrand :selected').each(function(i, selected){ 
  reorderbrand = reorderbrand + $(selected).val() + ', '; 
});

reorderbrand = reorderbrand.replace(/,\s*$/, "");


var reordercategory = ''; 
$('#reordercategory :selected').each(function(i, selected){ 
  reordercategory = reordercategory + $(selected).val() + ', '; 
});

reordercategory = reordercategory.replace(/,\s*$/, "");


$.ajax({
        type: "POST",
        url: "../ajax/receipt-query.php",
        data: { pdemand : reorderfilter, itemlevel : itemlevel, reorderwarehouse : reorderwarehouse, reorderbrand : reorderbrand, reordercategory : reordercategory, vendorlimit : vendorlimit, product_ctype : product_ctype,  vendorid : cid },
        cache: false,
        dataType : 'html',
        success: function(html){
            $(".cartcustom-overlay").html(html);
        }
    });

    
});



<?php if($info3000['en_snd_purchase']==1){ ?>

$(document).on('focusout', '.searchp, .searchqty', function(){
    var that = $(this);
    var prd_id = that.closest('tr').find('.singleitem').val(); 
    var qty = that.closest('tr').find("#t"+prd_id).val();
    
    var dist_id = $("#dist_to_id").val(); 
    var brand_id = $("#inv_brand").val() || "a"; 
    // alert(qty+'   '+$("#product_search").val());
    
    //  exit();
     // $(".reportselect").filter('.select2-hidden-accessible').select2("destroy"); 
     if(qty>0)
     {
          $.ajax({
            type: "POST",
            url: "../ajax/ajax-as.php",
            data: { qty_disc_litmus:1, qty:qty , dist_id,dist_id,brand_id:brand_id,prd_id:prd_id},
            cache: false,
            dataType : 'html',
            success: function(response){
                
                    that.closest('tr').find('[name="products_discount[]"]').val(response);
                    that.closest('tr').find('.income_count').trigger('change');
            }

       });


        $.ajax({
            type: "POST",
            url: "../ajax/ajax-as.php",
            data: { qty_scheme_litmus:1, qty:qty , dist_id,dist_id,brand_id:brand_id,prd_id:prd_id},
            cache: false,
            dataType : 'html',
            success: function(response){
                        that.closest('tr').find('[name="products_scheme[]"]').val(response);
                        that.closest('tr').find('.income_count').trigger('change');
            }

       });

            
        $.ajax({
            type: "POST",
            url: "../ajax/ajax-as.php",
            data: { qty_tax_litmus:1, qty:qty , dist_id,dist_id,brand_id:brand_id,prd_id:prd_id},
            cache: false,
            dataType : 'html',
            success: function(response){


            console.log(response);
                        that.closest('tr').find('[name="products_tax[]"]').val(response);

                        that.closest('tr').find('.income_count').trigger('change');
            }

       });


         $.ajax({
            type: "POST",
            url: "../ajax/ajax-as.php",
            data: { qty_rate_litmus:1, qty:qty , dist_id,dist_id,brand_id:brand_id,prd_id:prd_id},
            cache: false,
            dataType : 'html',
            success: function(response){
                that.closest('tr').find('[name="unitcos[]"]').val(response);
                that.closest('tr').find('.income_count').trigger('change');
            }
       });

     }

                

});



 

<?php } ?>


<?php if($info3000['en_goodluck'] == 1){ ?>

$(document).on('change focusout ', '.income_count', function() {
var a=this.id;

    a = a.replace(/\D/g, '');
    var price= $(this).closest(".carttr").find("#pp" + a).val();
    var qty= $(this).closest(".carttr").find("#ctn" + a).val();
        var custom_field1= $(this).closest(".carttr").find(".custom_field1").val();
    var slc_price = $(this).closest(".carttr").find(".price_slc").val();

    if(slc_price=='') slc_price=0;
    
  var slc_amt2 = qty * price;
  
   var slc_amt = qty * slc_price;
  
  var slc_cal = 0;
  
  if(slc_amt2<slc_amt) slc_cal = slc_amt - slc_amt2;
  
     //  $(this).closest(".carttr").find(".price_slc").val(slc_price.toFixed(2));
        $(this).closest(".carttr").find(".slc_amt").val(slc_cal.toFixed(2));
    // console.log(custom_field1);


             var sum4 = 0;
     var ab = 0;
     var xyz = 0;
     var nn = 0;

  $(".price_slc").each(function(){
    
     ab = $(this).val();
     xyz = $(this).closest(".carttr").find(".packing").val();
     nn = parseFloat(ab) * parseFloat(xyz);
    
    sum4 = parseFloat(sum4) +parseFloat(nn);
    
  });

    $("#total_slc").val(sum4);


    var sum5 = 0;
    $(".price_slc").each(function(){
      sum5 += +$(this).val();
    });
    $("#total_slc_price").val(sum5);

        var sum6 = 0;
    $(".slc_amt").each(function(){
      sum6 += +$(this).val();
    });
    $("#total_slc_amount").val(sum6);


  // console.log(sum4 +" == "+sum5+"  == "+sum6);


});


<?php } ?>
 
 

<?php if($info2000['en_fixed_payment_term'] == 1){ ?>
$(document).on('change', '.cid', function(){
    var cid2 = $(this).val();
    $.ajax({
        type: "POST",
        url: "../ajax/ajax-pk.php",
        data: { get_vend_payment_term : cid2 },
        cache: false,
        dataType : 'html',
        success: function(html){
            $(".payment_terms_div").html(html);
        }
    });
}); 
<?php } ?>

$(document).on('change', '.warehouse', function(){
    var stock6 = $(this).val();
    var stocksingle = $(this).closest('tr').find('.products').val();
    var that = $(this);
    $.ajax({
        type: "POST",
        url: "../ajax/ajax-pk3.php",
        data: { stock6 : stock6, stocksingle : stocksingle },
        cache: false,
        dataType : 'html',
        success: function(html){
            that.closest('tr').find('.triggeravailable').html(html);
        }
    });
});

function syncPurchaseItemCounters() {
    var itemCount = 0;

    $('#acart tbody .products').each(function() {
        if ($.trim($(this).val()) !== '') {
            itemCount++;
        }
    });

    $('#totpc').val(itemCount);
    $('#total_items_count').val(itemCount);
}

$(document).ready(function() {
    syncPurchaseItemCounters();

    var cartBody = document.querySelector('#acart tbody');
    if (cartBody && window.MutationObserver) {
        var observer = new MutationObserver(function() {
            syncPurchaseItemCounters();
        });

        observer.observe(cartBody, {
            childList: true,
            subtree: true
        });
    }
});


$('#service_invoice').trigger('change');

</script>

<script type="text/javascript">
(function($) {
    var tradeOfferCache = {};

    function normalizeTradeOffer(value) {
        var parsed = parseFloat(value);
        return isNaN(parsed) ? 0 : parsed;
    }

    function fetchTradeOffer(itemId, callback) {
        var key = String(itemId || '').trim();
        if (!key) {
            callback(0);
            return;
        }
        if (Object.prototype.hasOwnProperty.call(tradeOfferCache, key)) {
            callback(tradeOfferCache[key]);
            return;
        }

        $.ajax({
            type: "POST",
            url: "../ajax/product-trade-offer-get.php",
            data: { item_id: key },
            cache: false,
            dataType: "json",
            success: function(resp) {
                var value = (resp && resp.success) ? normalizeTradeOffer(resp.tradeoffer) : 0;
                tradeOfferCache[key] = value;
                callback(value);
            },
            error: function() {
                tradeOfferCache[key] = 0;
                callback(0);
            }
        });
    }

    function getRowItemId($row) {
        var itemId = $row.find("input.singleitem, input.products, input[name='products[]']").first().val();
        return String(itemId || '').trim();
    }

    function ensureTradeOfferHidden($row, $input, value) {
        var fieldName = "products_discount3[]";
        var $hidden = $row.find("input[type='hidden'][data-tradeoffer-shadow='1'][name='" + fieldName + "']").first();
        if (!$hidden.length) {
            $hidden = $row.find("input[type='hidden'][name='" + fieldName + "']").first();
        }
        if (!$hidden.length && $input && $input.length) {
            $hidden = $("<input>", {
                type: "hidden",
                name: fieldName,
                "data-tradeoffer-shadow": "1"
            });
            $input.after($hidden);
        }
        if ($hidden.length) {
            $hidden.val(value);
        }
    }

    function lockTradeOfferRow($row) {
        if (!$row || !$row.length) {
            return;
        }

        var $discountField = $row.find("input[name='products_discount3[]']").first();
        if ($discountField.length && String($discountField.attr("type") || "").toLowerCase() === "hidden") {
            return;
        }
        if (!$discountField.length) {
            return;
        }

        var itemId = getRowItemId($row);

        function applyValue(value) {
            ensureTradeOfferHidden($row, $discountField, value);
            $discountField
                .val(value)
                .attr("data-tradeoffer-value", value)
                .prop("readonly", true)
                .prop("disabled", true)
                .addClass("tradeoffer-locked-input");
            $row.attr("data-tradeoffer-locked", "1");
            $row.attr("data-tradeoffer-item", itemId);
            $discountField.trigger("change");
        }

        if (!itemId) {
            return;
        }

        fetchTradeOffer(itemId, applyValue);
    }

    function enforceTradeOfferLock(scope) {
        var $scope = scope ? $(scope) : $(document);
        $scope.find("#acart tbody tr.carttr, #psearch tr.carttr").each(function() {
            lockTradeOfferRow($(this));
        });
    }

    $(document).on("click", ".edit", function() {
        var $row = $(this).closest("tr");
        setTimeout(function() {
            lockTradeOfferRow($row);
        }, 0);
    });
    $(document).on("focus", "input[name='products_discount3[]']", function() {
        lockTradeOfferRow($(this).closest("tr"));
    });

    $(function() {
        enforceTradeOfferLock(document);

        if (window.MutationObserver) {
            var psearchNode = document.getElementById("psearch");
            var acartBodyNode = document.querySelector("#acart tbody");
            [psearchNode, acartBodyNode].forEach(function(targetNode) {
                if (!targetNode) {
                    return;
                }
                new MutationObserver(function() {
                    enforceTradeOfferLock(targetNode);
                }).observe(targetNode, { childList: true, subtree: true });
            });
        }
    });

    window.bmsPurchaseTradeOfferLock = enforceTradeOfferLock;
})(jQuery);
</script>

<?php
 } 
}


else  header("location:../index.php"); ?>








