<?php

session_start();

////////////////////////////////////////////// Database Connector ///////////////////////////////////////////////////////////
require_once ("connection_sql.php");

////////////////////////////////////////////// Write XML ////////////////////////////////////////////////////////////////////
header('Content-Type: text/xml');

date_default_timezone_set('Asia/Colombo');


if ($_GET["Command"] == "brandsession") {
 
    $_SESSION["brand"]=$_GET["brand"];
    $_SESSION["brand"]="";
 
} 

if ($_GET["Command"] == "new_inv") {
    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    
    $_SESSION["department"]="";
    
    $COMPANY=$_SESSION['company']; 
    
    $sql = "select ORDNO,VATTYPE,PAYTYPE from invpara where flag='".$COMPANY."'"; 
    $result = $conn->query($sql);
    $row = $result->fetch();
    
    $vattype=$row['VATTYPE'];
    $paytype=$row['PAYTYPE'];
    
    $sql = "delete from s_cusordtrn_tmp where user= '" . $_SESSION["CURRENT_USER"] . "' ";
    $result = $conn->query($sql);
    
    $sql = "delete from s_cusordtrn_tmp where user= '' ";
    $result = $conn->query($sql);
    
    
    if($row['PAYTYPE']=='CA'){ 
        $sql = "select ORDNO from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
         
        $tmpinvno = "000000" . $row["ORDNO"] ;
        $lenth = strlen($tmpinvno);
        $invno = trim("".$COMPANY."/SO/CB/") . substr($tmpinvno, $lenth - 6);
        
        $tono = $row['ORDNO'];
         
    }else{
        $sql = "select ORDNO from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
         
        $tmpinvno = "000000" . $row["ORDNO"];
        $lenth = strlen($tmpinvno);
        $invno = trim("".$COMPANY."/SO/CRM/") . substr($tmpinvno, $lenth - 6);
        
        $tono = $row['ORDNO'];
    }
    
    $_SESSION["brand"]="";
    
    

    
    $ResponseXML .= "<vattype><![CDATA[" . $vattype . "]]></vattype>";
    $ResponseXML .= "<paytype><![CDATA[" . $paytype . "]]></paytype>";
    $ResponseXML .= "<invno><![CDATA[" . $invno . "]]></invno>";
    $ResponseXML .= "<tmpno><![CDATA[" . $tono . "]]></tmpno>";
    $ResponseXML .= "<sdate><![CDATA[" . date("Y-m-d") . "]]></sdate>";
    
    
    $COMPANY=$_SESSION['company']; 
    $sql_para = "select flag1 from invpara where flag='".$COMPANY."'"; 
    $result_para = $conn->query($sql_para);
    $row_para = $result_para->fetch();
    
    if($_GET['type2']=="NORMAL"){
        
        $sql_sto = "select * from s_stomas where act='1' and SCODE='" . $COMPANY . "' "; 
        $result_sto = $conn->query($sql_sto);
        if ($row_sto = $result_sto->fetch()) {
            
            $_SESSION["department"]=$row_sto["CODE"];
            
            $ResponseXML .= "<select_dep><![CDATA[";  
        	foreach ($conn->query($sql_sto) as $row_sto) { 
        		$ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_dep>";
        }else{
            $_SESSION["department"]=$row_sto["CODE"];
             $ResponseXML .= "<select_dep><![CDATA[]]></select_dep>";
        }
        if ($_SESSION["CURRENT_REP"] != "") {
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' and REPCODE='".$_SESSION["CURRENT_REP"]."' order by REPCODE"; 
        }else{
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' order by REPCODE"; 
        }
        
        $result_rep = $conn->query($sql_rep);
        if ($row_rep = $result_rep->fetch()) {
            
            $ResponseXML .= "<select_rep><![CDATA[";  
        	foreach ($conn->query($sql_rep) as $row_rep) { 
        		$ResponseXML .= " <option value='" . $row_rep["REPCODE"] . "'>" . $row_rep["Name"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_rep>";
        }else{
             $ResponseXML .= "<select_rep><![CDATA[]]></select_rep>";
        }
        
         $sql_lab = "select * from s_labour where act='1' and cancel='0' and SCODE='" . $COMPANY . "' order by CODE"; 
        $result_lab = $conn->query($sql_lab);
        if ($row_lab = $result_lab->fetch()) {
            
            $ResponseXML .= "<select_lab><![CDATA[";  
        	foreach ($conn->query($sql_lab) as $row_lab) { 
        		$ResponseXML .= " <option value='" . $row_lab["CODE"] . "'>" . $row_lab["DESCRIPTION"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_lab>";
        }else{
             $ResponseXML .= "<select_lab><![CDATA[]]></select_lab>";
        }
        
	}else{
	    $COMPANY=$row_para['flag1'];
	    
	    $sql_sto = "select * from s_stomas where act='1' and SCODE='" . $COMPANY . "' ";
        $result_sto = $conn->query($sql_sto);
        if ($row_sto = $result_sto->fetch()) {
            
            $_SESSION["department"]=$row_sto["CODE"];
            
            $ResponseXML .= "<select_dep><![CDATA[";  
        	foreach ($conn->query($sql_sto) as $row_sto) { 
        		$ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_dep>";
        }else{
             $ResponseXML .= "<select_dep><![CDATA[]]></select_dep>";
        } 
        
        if ($_SESSION["CURRENT_REP"] != "") {
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' and REPCODE='".$_SESSION["CURRENT_REP"]."' order by REPCODE"; 
        }else{
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' order by REPCODE"; 
        }
        $result_rep = $conn->query($sql_rep);
        if ($row_rep = $result_rep->fetch()) {
            
            $ResponseXML .= "<select_rep><![CDATA[";  
        	foreach ($conn->query($sql_rep) as $row_rep) { 
        		$ResponseXML .= " <option value='" . $row_rep["REPCODE"] . "'>" . $row_rep["Name"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_rep>";
        }else{
             $ResponseXML .= "<select_rep><![CDATA[]]></select_rep>";
        }
        
        $sql_lab = "select * from s_labour where act='1' and cancel='0' and SCODE='" . $COMPANY . "' order by CODE"; 
        $result_lab = $conn->query($sql_lab);
        if ($row_lab = $result_lab->fetch()) {
            
            $ResponseXML .= "<select_lab><![CDATA[";  
        	foreach ($conn->query($sql_lab) as $row_lab) { 
        		$ResponseXML .= " <option value='" . $row_lab["CODE"] . "'>" . $row_lab["DESCRIPTION"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_lab>";
        }else{
             $ResponseXML .= "<select_lab><![CDATA[]]></select_lab>";
        }
	}
	
	
    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;
}

if ($_GET["Command"] == "paytype") {
    
    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    
    $COMPANY=$_SESSION['company'];
    if ($_GET['paymethod'] == "CA") {
        $sql = "select ORDNO,flag1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
        if($_GET['type2']=="NORMAL"){
            $tmpinvno = "000000" .$row["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CB/") . substr($tmpinvno, $lenth - 6);
        }else{
            $COMPANY=$row['flag1'];
            
            $sql2 = "select ORDNO,flag1 from invpara where flag='".$COMPANY."'"; 
            $result2 = $conn->query($sql2);
            $row2 = $result2->fetch();
            
            $tmpinvno = "000000" .$row2["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CB/") . substr($tmpinvno, $lenth - 6);
        }
      
    }else{
        
        $sql = "select ORDNO,flag1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
         
        if($_GET['type2']=="NORMAL"){
            $tmpinvno = "000000" .$row["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CRM/") . substr($tmpinvno, $lenth - 6);
        }else{
            $COMPANY=$row['flag1'];
            
            $sql2 = "select ORDNO,flag1 from invpara where flag='".$COMPANY."'"; 
            $result2 = $conn->query($sql2);
            $row2 = $result2->fetch();
            
            $tmpinvno = "000000" .$row2["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CRM/") . substr($tmpinvno, $lenth - 6);
        }  
    }
    
    
    $COMPANY=$_SESSION['company']; 
    $sql_para = "select flag1 from invpara where flag='".$COMPANY."'"; 
    $result_para = $conn->query($sql_para);
    $row_para = $result_para->fetch();
    
    if($_GET['type2']=="NORMAL"){
        
        $sql_sto = "select * from s_stomas where act='1' and SCODE='" . $COMPANY . "' ";
        $result_sto = $conn->query($sql_sto);
        if ($row_sto = $result_sto->fetch()) {
            
            $_SESSION["department"]=$row_sto["CODE"];
            
            $ResponseXML .= "<select_dep><![CDATA[";  
        	foreach ($conn->query($sql_sto) as $row_sto) { 
        		$ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_dep>";
        }else{
             $ResponseXML .= "<select_dep><![CDATA[]]></select_dep>";
        }
        
        
        if ($_SESSION["CURRENT_REP"] != "") {
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' and REPCODE='".$_SESSION["CURRENT_REP"]."' order by REPCODE"; 
        }else{
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' order by REPCODE"; 
        }
        $result_rep = $conn->query($sql_rep);
        if ($row_rep = $result_rep->fetch()) {
            
            $ResponseXML .= "<select_rep><![CDATA[";  
        	foreach ($conn->query($sql_rep) as $row_rep) { 
        		$ResponseXML .= " <option value='" . $row_rep["REPCODE"] . "'>" . $row_rep["Name"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_rep>";
        }else{
             $ResponseXML .= "<select_rep><![CDATA[]]></select_rep>";
        }
        
        $sql_lab = "select * from s_labour where act='1' and cancel='0' and SCODE='" . $COMPANY . "' order by CODE"; 
        $result_lab = $conn->query($sql_lab);
        if ($row_lab = $result_lab->fetch()) {
            
            $ResponseXML .= "<select_lab><![CDATA[";  
        	foreach ($conn->query($sql_lab) as $row_lab) { 
        		$ResponseXML .= " <option value='" . $row_lab["CODE"] . "'>" . $row_lab["DESCRIPTION"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_lab>";
        }else{
             $ResponseXML .= "<select_lab><![CDATA[]]></select_lab>";
        }
        
	}else{
	    $COMPANY=$row_para['flag1'];
	    
	    $sql_sto = "select * from s_stomas where act='1' and SCODE='" . $COMPANY . "' ";
        $result_sto = $conn->query($sql_sto);
        if ($row_sto = $result_sto->fetch()) {
            
            $_SESSION["department"]=$row_sto["CODE"];
            
            $ResponseXML .= "<select_dep><![CDATA[";   
        	foreach ($conn->query($sql_sto) as $row_sto) { 
        		$ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_dep>";
        }else{
             $ResponseXML .= "<select_dep><![CDATA[]]></select_dep>";
        } 
        
        if ($_SESSION["CURRENT_REP"] != "") {
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' and REPCODE='".$_SESSION["CURRENT_REP"]."' order by REPCODE"; 
        }else{
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' order by REPCODE"; 
        }
        $result_rep = $conn->query($sql_rep);
        if ($row_rep = $result_rep->fetch()) {
            
            $ResponseXML .= "<select_rep><![CDATA[";  
        	foreach ($conn->query($sql_rep) as $row_rep) { 
        		$ResponseXML .= " <option value='" . $row_rep["REPCODE"] . "'>" . $row_rep["Name"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_rep>";
        }else{
             $ResponseXML .= "<select_rep><![CDATA[]]></select_rep>";
        }
        
        $sql_lab = "select * from s_labour where act='1' and cancel='0' and SCODE='" . $COMPANY . "' order by CODE"; 
        $result_lab = $conn->query($sql_lab);
        if ($row_lab = $result_lab->fetch()) {
            
            $ResponseXML .= "<select_lab><![CDATA[";  
        	foreach ($conn->query($sql_lab) as $row_lab) { 
        		$ResponseXML .= " <option value='" . $row_lab["CODE"] . "'>" . $row_lab["DESCRIPTION"] ."</option> "; 
        
        	}
        
        	$ResponseXML .= "]]></select_lab>";
        }else{
             $ResponseXML .= "<select_lab><![CDATA[]]></select_lab>";
        }
	}
    

    $ResponseXML .= "<paytype><![CDATA[" . $_GET["paymethod"] . "]]></paytype>";
    $ResponseXML .= "<invno><![CDATA[" . $invno . "]]></invno>"; 
    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;
}

if ($_GET["Command"] == "cancel_inv") {


    $sql = "select last_update from invpara where flag='".$_SESSION['company']."'"; 
    $result = $conn->query($sql);
    $row = mysqli_fetch_array($result);

    try {
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->beginTransaction();

        $sqlinv = "select * from s_cusordmas where REF_NO='" . $_GET["invno"] . "' ";
        $resultinv = $conn->query($sqlinv);
        if ($rowinv = $resultinv->fetch()) {
            if ($rowinv['CANCELL'] == "1") {
                exit("Already Canceled..");
            }
            // if (date("Y-m") != date("Y-m", strtotime($rowinv["sdate1"]))) {
            //     //if (date("Y-m") == date("Y-m", strtotime($rowinv["SDATE"]))) {
            //     echo 'Not in Current Month Can not Cancel';
            //     exit();
            // }
            // if (($rowinv["TOTPAY"] == 0) and ( $rowinv["SDATE"] > $row["last_update"])) {

                $sql2 = "update s_cusordmas set CANCELL='1',note='".$_GET["remarks"]."' where REF_NO='" . $_GET["invno"] . "'";
                $result2 = $conn->query($sql2);

                $sqltmp = "select * from s_cusordtrn where REF_NO='" . $_GET['invno'] . "' ";
                $resulttmp = $conn->query($sqltmp);
                while ($rowtmp = $resulttmp->fetch()) {
                    
                    $sql2 = "update s_cusordtrn set CANCELL='1' where REF_NO='" . $_GET['invno'] . "'";
                    $resul2 = $conn->query($sql2);
                }

                $sql2 = "insert into entry_log(refno, username, docname, trnType, stime, sdate,company) values 
                ('" . $_GET['invno'] . "', '" . $_SESSION["CURRENT_USER"] . "', 'Sales Order', 'Cancel', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "' ,'".$_SESSION['company']."')"; 
                $result2 = $conn->query($sql2);
                
                echo "Cancelled";
                $conn->commit();
            // } else {
            //     echo "Already Paid";
            //     exit();
            // }
        } else {
            echo "Can't Cancel";
            exit();
        }
    } catch (Exception $e) {
        $conn->rollBack();
        echo $e;
    }
}


if ($_GET["Command"] == "add_tmp") {

    if ($_GET['Command1'] == "add"){
        
        
       
        $sql_mas = "Select * from s_mas where STK_NO='" .$_GET['itemcode'] . "' ";
        $resultmas = $conn->query($sql_mas);
        $rowmas = $resultmas->fetch();
        
        if(($rowmas['Cat1'] =='TO BE EDIT ITEM RATE MINUS') ){
             $rate = str_replace(",", "", ($_GET["rate"]*-1)); 
        }else{
            $rate = str_replace(",", "", $_GET["rate"]);
        }
    

        $actual_selling = str_replace(",", "", $_GET["rate"]);
        $qty = str_replace(",", "", $_GET["qty"]);
        $subtotal = str_replace(",", "", $_GET["subtotal"]);
        $subtotal1 = str_replace(",", "", $_GET["subtotal"]);
        $cardfee = str_replace(",", "", $_GET["cardfee"]);
        
        $disper=0;
        $disper1=0;
        
        if (($_GET["discountper"] != '') && ($_GET["discountper"] != "0") && ($_GET["discountper"] != "0.00")) {
            $disper = $_GET["discountper"];
            $disper1 = $_GET["discountper"];
        }
    
        if (($_GET["discountper1"] != '') && ($_GET["discountper1"] != "0") && ($_GET["discountper1"] != "0.00")) {
            $disper2 = (100 - $_GET["discountper"]) * ($_GET["discountper1"]) / 100;
            $disper = $disper1 +$disper2;
        }
    
        $subtotal2 = ($rate - ($rate * $disper / 100))*$qty;
 
        if ($subtotal1 != $subtotal2) {
            if (($subtotal1 != 1) && ($subtotal2 != 0)) {
                //echo $subtotal1; 
                exit('Error');
            }
        }
    

        // $sql = "select QTYINHAND from s_submas where STK_NO='" . $_GET['itemcode']  . "' AND STO_CODE='" . $_GET["department"] . "'";
        // $result = $conn->query($sql);
        // if ($row = $result->fetch()) {
                
                 $sql = "Insert into s_cusordtrn_tmp (str_invno, str_code, str_description, cur_rate, cur_qty,dis_per,dis_per1,cur_discount,  cur_subtot, brand, tmp_no,actual_selling,serialno,type,user)values 
                ('" . $_GET['invno'] . "', '" . $_GET['itemcode'] . "', '" . $_GET['item'] . "', '" . $rate . "', '" . $qty . "', '" . $_GET["discountper"] . "', '" . $_GET["discountper1"] . "', '" . $disper . "', '" . $subtotal . "', '" . $_GET['brand'] . "', '" . $_GET['tmpno'] . "','" . $rate . "', '" . $_GET['serialno'] . "', '" . $_GET['Command1'] . "', '" . $_SESSION["CURRENT_USER"] . "') ";
                // echo $sql;
                $result = $conn->query($sql);
            
        // }
        
      
    }
    
    if  ($_GET['Command1'] == "dag") {
        
        
        $rate = str_replace(",", "", $_GET["dag_selling"]); 
        $actual_selling = str_replace(",", "", $_GET["dag_selling"]);
        $qty = 1;
        $subtotal = str_replace(",", "", $_GET["dag_subtotal"]);
        $subtotal1 = str_replace(",", "", $_GET["dag_subtotal"]);
 
        $subtotal2 = $rate - ($rate * $_GET["dag_dis"] / 100);

        if ($subtotal1 = !$subtotal2) {
            if (($subtotal1 != 1) && ($subtotal2 != 0)) {
                //echo $subtotal1; 
                exit('Error');
            }
        }
        
        
         $sql = "select * from dag_item where jobno='" . $_GET['dag_jobno']  . "' AND company='" . $_SESSION['company']. "' and invno IS NULL ";
        $result = $conn->query($sql);
        if ($row = $result->fetch()) {
             
                 $sql = "Insert into s_cusordtrn_tmp (str_invno, str_code,jobno,  make,design,size, cur_rate, cur_qty, dis_per,  cur_subtot,   tmp_no,actual_selling,serialno,type,cost,user)values 
                ('" . $_GET['invno'] . "', 'IT/0727','" . $_GET['dag_jobno'] . "', '" . $_GET['dag_make'] . "', '" . $_GET['dag_design'] . "', '" . $_GET['dag_size'] . "', '" . $actual_selling . "', '".$qty."', " . $_GET["dag_dis"] . ", '" . $subtotal . "',  '" . $_GET['tmpno'] . "','" . $actual_selling . "', '" . $_GET['dag_serialno'] . "', '" . $_GET['Command1'] . "', '" . $_GET['dag_cost'] . "', '" . $_SESSION["CURRENT_USER"] . "') ";
                $result = $conn->query($sql);
             
        }else{
             exit('Cannot Add.Already Invoiced Or Canceled!!!!');
        }
        
    }

    if ($_GET['Command1'] == "del") {

        $sql = "delete from s_cusordtrn_tmp where id='" . $_GET['id'] . "'";
        $result = $conn->query($sql);
    }
    
    if ($_GET['Command1'] == "editrate") {
        $actual_selling = str_replace(",", "", $_GET["rate"]);
        $qty = str_replace(",", "", $_GET["qty"]);
        $subtotal = str_replace(",", "", $_GET["subtotal"]);
        $subtotal1 = str_replace(",", "", $_GET["subtotal"]);


        $disper=0;
        $disper1=0;
        if (($_GET["discountper"] != '') && ($_GET["discountper"] != "0") && ($_GET["discountper"] != "0.00")) {
            $disper = $_GET["discountper"];
            $disper1 = $_GET["discountper"];
        }
    
        if (($_GET["discountper1"] != '') && ($_GET["discountper1"] != "0") && ($_GET["discountper1"] != "0.00")) {
            $disper2 = (100 - $_GET["discountper"]) * ($_GET["discountper1"]) / 100;
            $disper = $disper1 +$disper2;
        }
 
        $subtotal2 = ($rate - ($rate * $disper / 100))*$qty;
        if ($subtotal1 != $subtotal2) {
            if (($subtotal1 != 1) && ($subtotal2 != 0)) { 
                exit('Error');
            }
        }

        $sql = "update s_cusordtrn_tmp set cur_rate='".$actual_selling."',actual_selling='".$actual_selling."',cur_qty='".$qty."',dis_per='".$_GET["discountper"]."',dis_per1='".$_GET["discountper1"]."',cur_discount='".$disper."',cur_subtot='".$subtotal."' where id='" . $_GET['id'] . "'" ;  
        $result = $conn->query($sql);
    }



    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    $ResponseXML .= "<sql><![CDATA[" . $sql . "]]></sql>";
    $ResponseXML .= "<sales_table><![CDATA[ <table class=\"table table-bordered\">     
    <tr>
    <th  class='col-md-1'>Item Code</th>
    <th  size='15'>&nbsp;</th>
    <th  class='col-md-3'>Description</th>
    <th  class='col-md-1'>Serial No</th>
    <th  class='col-md-2'>Price</th>
    <th  class='col-md-1'>Qty</th>
    <th class='col-md-1'>Dis1 (%)</th>
    <th class='col-md-1'>Dis2 (%)</th>
    <th class='col-md-2'>Unit Total</th>
    <th  size='15'>#</th>
    <th  size='15'></th>
                
                
    </tr>";

    $i = 1;
    $mtot = 0;
    $mtot2 = 0;
    $mtot1 = 0;
    $sql = "Select * from s_cusordtrn_tmp where tmp_no='" . $_GET['tmpno'] . "'  and type='add'";
    foreach ($conn->query($sql) as $row) {

        $id = "id" . $i;
        $code = "code" . $i;
        $itemd = "itemd" . $i;
        $serialno = "serialno" . $i;
        $rate = "rate" . $i;

        $qty = "qty" . $i;
        $discountper = "discountper" . $i;
        $discountper1 = "discountper1" . $i;
        $subtotal = "subtotal" . $i;
        $discount = "discount" . $i;

        $sql_mas = "Select * from s_mas where STK_NO='" . $row['str_code'] . "' and BRAND_NAME='" . $_GET['brand'] . "'";
        $resultmas = $conn->query($sql_mas);
        $rowmas = $resultmas->fetch();

        $dt = date('Y-m-d', strtotime(date('Y-m-d') . ' - 90 days'));

        $sql1 = "Select sum(REC_QTY) as stk from s_purtrn where STK_NO='" . $row['str_code'] . "' and CANCEL='0' and SDATE>'" . $dt . "' ";
        $result1 = $conn->query($sql1);
        $row1 = $result1->fetch();

        $mnewstk = 0;
        $unsold = 0;
        if (is_null($row1["stk"]) == false) {
            $mnewstk = $row1["stk"];
        }

        if ($rowmas["QTYINHAND"] > $row1["stk"]) {
            $unsold = $rowmas["QTYINHAND"] - $mnewstk;
        }

        $bgcolour = "";

        if ($unsold > 0) {
            $bgcolour = "green";
        }

        $ResponseXML .= "<tr>                              
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\" class='hidden' ><div id='" . $id . "'  >" . $row['id'] . "</div></td>
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $code . "'>" . $row['str_code'] . "</div></td>
        <td size='15'>&nbsp;</td>";
        if ($bgcolour == "") {
            $ResponseXML .= "<td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $itemd . "'>" . $row['str_description'] . "</div></td>";
        } else {
            $ResponseXML .= "<td bgcolor=\" . $bgcolour . \" onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $itemd . "'>" . $row['str_description'] . "</div></td>";
        }
        $ResponseXML .= "
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $serialno . "'>" . $row['serialno'] . "</div></td>
        <td align=right onClick=\"disp_qty('" . $row['str_code'] . "');\">
        <input type='number' placeholder='Rate'  id='" . $rate . "' value=" . $row['cur_rate'] . " disabled onblur=\"calc1_table('".$i."');\"  class='form-control'> </td>
        <td align=right onClick=\"disp_qty('" . $row['str_code'] . "');\">
        <input type='number' placeholder='Qty'  id='" . $qty . "' value=" . $row['cur_qty'] . " disabled onblur=\"calc1_table('".$i."');\"   class='form-control'> </td>
        <td align=right onClick=\"disp_qty('" . $row['str_code'] . "');\">
        <input type='number' placeholder='Qty'  id='" . $discountper . "' disabled value=" . number_format($row['dis_per'], 2, ".", ",")   . " onblur=\"calc1_table('".$i."');\"   class='form-control'>  </td>
        <td align=right onClick=\"disp_qty('" . $row['str_code'] . "');\">
        <input type='number' placeholder='Qty'  id='" . $discountper1 . "' disabled value=" . number_format($row['dis_per1'], 2, ".", ",")   . " onblur=\"calc1_table('".$i."');\"   class='form-control'> <input type=\"hidden\"  name=\"" . $discount . "\" id=\"" . $discount . "\" size=\"15\"  value=\"" . number_format($row['cur_rate'], 2, ".", ",") . "\"    /></td>
        <td align=right onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $subtotal . "'>" . number_format($row['cur_subtot'], 2, ".", ",") . "</div></td>
        <td><a class=\"btn btn-danger btn-xs\"  onClick=\"del_item('" . $row['id'] . "');\"><span class='fa fa-remove'></a></td>";

        $sql = "select QTYINHAND from s_submas where STK_NO='" . $row['str_code'] . "' AND STO_CODE='" . $_GET["department"] . "'";
        $result_q = $conn->query($sql);
        if ($row_q = $result_q->fetch()) {
            $qty = number_format($row_q['QTYINHAND'], 0, ".", ",");
        } else {
            $qty = 0;
        }


        $mtot = $mtot + $row['cur_subtot'];
        $mtot1 = $mtot1 + $row['cur_subtot'];


        $mtot2 = $mtot2 + ($row['cur_rate'] * $row['cur_qty']);


        $ResponseXML .= "<td>" . $qty . "</td>



        </tr>";
        $i = $i + 1;
    }
    $ResponseXML .= "   </table>]]></sales_table>";
    
    
     $ResponseXML .= "<sales_dagtable><![CDATA[ <table class=\"table table-bordered\">     
    <tr>
    <th style=\"width: 100px;\">JOB NO</th>
    <th style=\"width: 10px;\"></th>
    <th style=\"width: 100px;\">MAKE</th> 
    <th style=\"width: 70px;\">SIZE</th>
    <th style=\"width: 70px;\">DESIGN</th>
    <th style=\"width: 100px;\">SERIAL NO</th> 
    <th style=\"width: 90px;\">COST</th>
    <th style=\"width: 120px;\">SELLING</th> 
    <th style=\"width: 60px;\">Dis</th>
    <th style=\"width: 120px;\">SubTotal</th>
    <th style=\"width: 50px;\"></th>
                
      
    </tr>";

     
    $sql = "Select * from s_cusordtrn_tmp where tmp_no='" . $_GET['tmpno'] . "' and type='dag'";
    foreach ($conn->query($sql) as $row) {

        $id = "id" . $i;
        $code = "code" . $i;
        $size = "size" . $i;
         $design = "design" . $i;
        $serialno = "serialno" . $i;
        $cost = "cost" . $i;
        $rate = "rate" . $i;

        $qty = "qty" . $i;
        $discountper = "discountper" . $i;
        $subtotal = "subtotal" . $i;
        $discount = "discount" . $i;

        $ResponseXML .= "<tr>                              
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\" class='hidden' ><div id='" . $id . "'  >" . $row['id'] . "</div></td>
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $code . "'>" . $row['jobno'] . "</div></td>
        <td size='15'>&nbsp;</td> 
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $itemd . "'>" . $row['make'] . "</div></td>  
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $size . "'>" . $row['size'] . "</div></td> 
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $design . "'>" . $row['design'] . "</div></td> 
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $serialno . "'>" . $row['serialno'] . "</div></td>";
        
        if($_SESSION['user_type']=="ADMIN"){
           $ResponseXML .= " <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $cost . "'>" . $row['cost'] . "</div></td>";
        }else{
            $ResponseXML .= "<td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $cost . "'></div></td>";
        }
        
        $ResponseXML .= "<td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $rate . "'>" . $row['cur_rate'] . "</div></td> 
        <td onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $discountper . "'>" . number_format($row['dis_per'], 2, ".", ","). "</div><input type=\"hidden\"  name=\"" . $discount . "\" id=\"" . $discount . "\" size=\"15\"  value=\"" . number_format($row['cur_rate'], 2, ".", ",") . "\"    /></td>
          <td align=right onClick=\"disp_qty('" . $row['str_code'] . "');\"><div id='" . $subtotal . "'>" . number_format($row['cur_subtot'], 2, ".", ",") . "</div></td>
        <td><a class=\"btn btn-danger btn-xs\"  onClick=\"del_item('" . $row['id'] . "');\"><span class='fa fa-remove'></a></td>";

    
        $mtot = $mtot + $row['cur_subtot'];
        $mtot1 = $mtot1 + $row['cur_subtot'];

        $mtot2 = $mtot2 + ($row['cur_rate'] * $row['cur_qty']);


        $ResponseXML .= "  
        </tr>";
        $i = $i + 1;
    }
    $ResponseXML .= "   </table>]]></sales_dagtable>";

    $ResponseXML .= "<item_count><![CDATA[" . $i . "]]></item_count>";
    $ResponseXML .= "<Command1><![CDATA[" . $_GET['Command1'] . "]]></Command1>";

    $sql1 = "select vatrate from invpara  where flag='".$_SESSION['company']."'"; 
    $result1 = $conn->query($sql1);
    $row1 = $result1->fetch();

     $mtot=$mtot+$mtot* $_GET['cardfee']/100;
    $mtot1=$mtot1+$mtot1* $_GET['cardfee']/100;
    $mtot2=$mtot2+$mtot2* $_GET['cardfee']/100;

    if ($_GET['vatmethod'] != "non") {
        $mtot1 = $mtot1 / ( 1 + ($row1['vatrate'] / 100));
        //  $mtot1 = $mtot;
        //  $mtax = $mtot1*$row1['vatrate'] / 100;
    } else {
        $mtot1 = $mtot;
        $mtax = 0;
    }
    
    $mtax = $mtot - $mtot1;
    
    $mdis = $mtot2 - $mtot;
    
    
    
    $ResponseXML .= "<subtot><![CDATA[" . number_format($mtot1, 2, ".", "") . "]]></subtot>";
 

    $ResponseXML .= "<totdiscount><![CDATA[" . number_format($mdis, 2, ".", "") . "]]></totdiscount>";
    $ResponseXML .= "<tax><![CDATA[" . number_format($mtax, 2, ".", "") . "]]></tax>";
    $ResponseXML .= "<invtot><![CDATA[" . number_format($mtot, 2, ".", "") . "]]></invtot>";
    
    
    $COMPANY=$_SESSION['company'];
    if ($_GET['paymethod'] == "CA") {
        
        $sql = "select ORDNO,flag1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
        $sql1 = "select * from s_stomas where CODE='".$_GET['department']."'"; 
        $result1 = $conn->query($sql1);
        $row1 = $result1->fetch();
        
        if($_GET['type2']=="NORMAL"){
            $tmpinvno = "000000" .$row["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CB/") . substr($tmpinvno, $lenth - 6);
        }else{
            $COMPANY=$row['flag1'];
            $sql2 = "select ORDNO,flag1 from invpara where flag='".$COMPANY."'"; 
            $result2 = $conn->query($sql2);
            $row2 = $result2->fetch();
            
            $tmpinvno = "000000" .$row2["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$row['flag1']."/SO/CB/") . substr($tmpinvno, $lenth - 6);
        }
         
     
    }else{
        
        $sql = "select ORDNO,flag1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
        $sql1 = "select * from s_stomas where CODE='".$_GET['department']."'"; 
        $result1 = $conn->query($sql1);
        $row1 = $result1->fetch();
        
        if($_GET['type2']=="NORMAL"){
            $tmpinvno = "000000" .$row["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CRM/") . substr($tmpinvno, $lenth - 6);
        }else{
            $COMPANY=$row['flag1'];
            
            $sql2 = "select ORDNO,flag1 from invpara where flag='".$COMPANY."'"; 
            $result2 = $conn->query($sql2);
            $row2 = $result2->fetch();
            
            $tmpinvno = "000000" .$row2["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CRM/") . substr($tmpinvno, $lenth - 6);
        }
      
    }
    
    $ResponseXML .= "<invno><![CDATA[" . $invno . "]]></invno>";



    $ResponseXML .= " </salesdetails>";


    echo $ResponseXML;
}


if ($_GET["Command"] == "pass_itno") {
    header('Content-Type: text/xml');
    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";



    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";

    if (trim($_GET["brand"]) != "") {
        $sql = "Select * from s_mas where STK_NO='" . $_GET['itno'] . "' and BRAND_NAME='" . $_GET["brand"] . "'";
    } else {
        $sql = "Select * from s_mas where STK_NO='" . $_GET['itno'] . "'";
    }
    $result_q = $conn->query($sql);
    if ($row = $result_q->fetch()) {

        $ResponseXML .= "<str_code><![CDATA[" . $row['STK_NO'] . "]]></str_code>";
        $ResponseXML .= "<str_description><![CDATA[" . $row['DESCRIPT'] . "]]></str_description>";
        $ResponseXML .= "<actual_selling><![CDATA[" . $row['SELLING'] . "]]></actual_selling>";


        $SELLING = $row['SELLING'];

        $ResponseXML .= "<str_selpri><![CDATA[" . number_format($SELLING, 2, ".", "") . "]]></str_selpri>";

        $ResponseXML .= "<str_partno><![CDATA[" . $row["PART_NO"] . "]]></str_partno>";
        $ResponseXML .= "<costcenter><![CDATA[" . $row["costcenter"] . "]]></costcenter>";

        $department = trim(substr($_GET["department"], 0, 2));


        $sql = "select QTYINHAND from s_submas where STK_NO='" . $_GET['itno'] . "' AND STO_CODE='" . $department . "'";
        $result_q = $conn->query($sql);
        if ($row_q = $result_q->fetch()) {
            $qty = number_format($row_q['QTYINHAND'], 0, ".", "");
        } else {
            $qty = 0;
        }

        $ResponseXML .= "<qtyinhand><![CDATA[" . $qty . "]]></qtyinhand>";

        $ResponseXML .= "<str_status><![CDATA[yes]]></str_status>";
    } else {
        $ResponseXML .= "<str_status><![CDATA[no]]></str_status>";
    }




    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;
}

if ($_GET["Command"] == "save_inv") {

    try {


        $insuf_qty = "";
        $sql = "select * from s_cusordtrn_tmp where tmp_no='" . $_GET["tmpno"] . "'";
        $i = 0;
        foreach ($conn->query($sql) as $rowtmp1) {
            $sql = "select QTYINHAND from s_submas where STK_NO='" . $rowtmp1['str_code'] . "' AND STO_CODE='" . $_GET["department"] . "'";
            $result = $conn->query($sql);
            if ($row = $result->fetch()) {
                 $sql_mas = "Select * from s_mas where STK_NO='" .$rowtmp1['str_code'] . "' ";
                    $resultmas = $conn->query($sql_mas);
                    $rowmas = $resultmas->fetch(); 
                    if($rowmas['CAT'] =='Stock Item'){
                        if ($row["QTYINHAND"] < $rowtmp1["cur_qty"]) {
                            $insuf_qty = $rowtmp1['str_code'];
                        }
                    }
                    
            }
            $i = $i + 1;
        }

        if ($_SESSION['UserName'] == "") {
            exit("Invalid Session");
        }

        if ($insuf_qty != "") {
            // exit("Under Stock");
        }

        if ($i == 0) {
            exit("Items Not Found");
        }

        $i = 0;
        $sqltmp1 = "select dis_per from s_cusordtrn_tmp where tmp_no='" . $_GET["tmpno"] . "' group by dis_per";
        foreach ($conn->query($sql) as $rowtmp1) {
            $i = $i + 1;
        }


        if ($i > 1) {
            exit("Error");
        }
        
        // $sql_sto = "select * from s_stomas where CODE='" . $_GET['department'] . " and SCOM='".$_SESSION['company']."'";
        // $result_sto = $conn->query($sql_sto);
        // if (!$row_sto = $result_sto->fetch()) { 
        //      exit("Please Login Again.You Login Anothor Department...!!!"); 
        //  }

        // $sqlcumas = "select * from s_cusordmas where REF_NO='" . trim($_GET["ordno"]) . "' and INVNO !='0'";
        // $resultcumas = $conn->query($sqlcumas);
        // if ($rowsumas = $resultcumas->fetch()) { 
        //     exit("Already Invoiced Order No...."); 
        // }

     $totdiscount = str_replace(",", "", $_GET["totdiscount"]);
     $subtot = str_replace(",", "", $_GET["subtot"]);
     $invtot = str_replace(",", "", $_GET["invtot"]);
     $tax = str_replace(",", "", $_GET["tax"]);
     $cardfee = str_replace(",", "", $_GET["cardfee"]);
     $vat = "";
        
    
    $sql = "select ORDNO,vatrate from invpara where flag='".$_SESSION['company']."'"; 
    $result = $conn->query($sql);
    $row = $result->fetch();

     if (($_GET["vatmethod"] == "vat") or ( $_GET["vatmethod"] == "svat") or ( $_GET["vatmethod"] == "evat")) {
        $vat = "1";
        if($row['VATTYPE']=='0'){
            exit("This Is Non vat Company .Can't Save Vat Invoice...."); 
        }
    } else {
        $vat = "0";
    }
    $svat = 0;
    if ($_GET["vatmethod"] == "svat") {
        $svat = str_replace(",", "", $_GET["tax"]);
    }



     


    if ($vat != "1") {
        if ($tax > 0) {
            exit('Error In Tax');
        }
    }


    $sqltmp1 = "select sum(cur_subtot) as cur_subtot from s_cusordtrn_tmp where tmp_no='" . $_GET["tmpno"] . "'";
    $result = $conn->query($sqltmp1);
    if ($rowclass = $result->fetch()) {
        // if (number_format($rowclass['cur_subtot'], 2, ".", "") != ($invtot-$tax)) {
        //     exit('Error In Total');
        // }

        if ($vat == "1") {
            $mtot = number_format($rowclass['cur_subtot'] / (1 + $row['vatrate'] / 100), 2, ".", "");
            if ($mtot != $subtot) {
//                    exit("Error In Sub Total");
            }
            $mtot = $rowclass['cur_subtot'] - $mtot;
            if ($mtot = !$tax) {
                exit("Error in Tax");
            }
        }
    } else {
        exit("Error");
    }


    $sql = "select * from vendor where CODE = '" . trim($_GET["customercode"]) . "'";
    $result = $conn->query($sql);
    if ($row = $result->fetch()) {
        if ($row["blacklist"] == "1") {
//                $sqlapp = "select * from s_cusordmas where ref_no='" . trim($_GET["salesord1"]) . "'";
//                $resultapp = $conn->query($sqlapp);
//                if ($rowapp = $resultapp->fetch()) {
//                    if ($rowapp["approveby"] == "0") {
//                        exit("Invoice Facilitey Stoped for This Customer,Please Invoice For Approved Sales Order");
//                    } else {
//                        exit("Invoice Facilitey Stoped for This Customer,Please Invoice For Approved Sales Order");
//                    }
//                    $_SESSION["print"] = 0;
//                }
            exit("Invoice Facilitey Stoped for This Customer..!!!");
        }
    }



    $InvClass = "";
    $sqlclass = "select class from brand_mas where barnd_name='" . trim($_GET["brand"]) . "'";
    $result = $conn->query($sqlclass);
    if ($rowclass = $result->fetch()) {
        if (is_null($rowclass["class"]) == false) {
            $InvClass = $rowclass["class"];
        }
    }


    // $d1 = str_replace(",", "", $_GET["discount_org1"]);
    // $d2 = str_replace(",", "", $_GET["discount_org2"]);
    // $d3 = str_replace(",", "", $_GET["discount_org3"]);

    // if ($d1 == "") {
    //     $d1 = 0;
    // }
    // if ($d2 == "") {
    //     $d2 = 0;
    // }
    // if ($d3 == "") {
    //     $d3 = 0;
    // }


    // $d = 100 - (100 - $d3) * (100 - $d2) * (100 - $d1) / 100;
        //===============================================

    $cre_balance = str_replace(",", "", $_GET["balance"]);



    $customername = str_replace("~", "&", $_GET["customername"]);
    $cus_address = str_replace("~", "&", $_GET["cus_address"]);

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->beginTransaction();
    
    $COMPANY=$_SESSION['company'];
    if ($_GET['pay_type'] == "CREDIT") {
       
                  $sql = "select ORDNO,vatrate,flag1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
        $sql1 = "select * from s_stomas where CODE='".$_GET['department']."'"; 
        $result1 = $conn->query($sql1);
        $row1 = $result1->fetch();
        
        if($_GET['type2']=="NORMAL"){
            $tmpinvno = "000000" .$row["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CRM/") . substr($tmpinvno, $lenth - 6);
            
            $sql = "update invpara set ORDNO = ORDNO +1 where flag='".$COMPANY."'"; 
            $res_inv = $conn->query($sql);
            
        }else{
            $COMPANY=$row['flag1'];
            
            $sql2 = "select ORDNO,vatrate,flag1 from invpara where flag='".$COMPANY."'"; 
            $result2 = $conn->query($sql2);
            $row2 = $result2->fetch();
            
            $tmpinvno = "000000" .$row2["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CRM/") . substr($tmpinvno, $lenth - 6);
            
            $sql = "update invpara set ORDNO = ORDNO +1 where flag='".$COMPANY."'"; 
            $res_inv = $conn->query($sql);
            
        }
     
    }else{
         $sql = "select ORDNO,vatrate,flag1 from invpara where flag='".$_SESSION['company']."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
        $sql1 = "select * from s_stomas where CODE='".$_GET['department']."'"; 
        $result1 = $conn->query($sql1);
        $row1 = $result1->fetch();
        
        if($_GET['type2']=="NORMAL"){
            $tmpinvno = "000000" .$row["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CB/") . substr($tmpinvno, $lenth - 6);
            
            $sql = "update invpara set ORDNO = ORDNO +1 where flag='".$COMPANY."'"; 
            $res_inv = $conn->query($sql);
        }else{
            $COMPANY=$row['flag1'];
            
            $sql2 = "select ORDNO,vatrate,flag1 from invpara where flag='".$COMPANY."'"; 
            $result2 = $conn->query($sql2);
            $row2 = $result2->fetch();
            
            $tmpinvno = "000000" .$row2["ORDNO"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/SO/CB/") . substr($tmpinvno, $lenth - 6);
            
            $sql = "update invpara set ORDNO = ORDNO +1 where flag='".$COMPANY."'"; 
            $res_inv = $conn->query($sql);
            
        }
        
    }
    
    

    $sqlisalma_q = "select REF_NO from s_cusordmas where REF_NO='" . $invno . "'";
    $resultsalma_q = $conn->query($sqlisalma_q);
    if ($rowsalma_q = $resultsalma_q->fetch()) {
        $conn->rollBack();
        exit("Invoice No Already Exist !!!");
    }
    // $sqlisalma_q = "select REF_NO from s_cusordmas where tmp_no='" . $_GET["tmpno"] . "'";
    // $resultsalma_q = $conn->query($sqlisalma_q);
    // if ($rowsalma_q = $resultsalma_q->fetch()) {
    //     $conn->rollBack();
    //     exit("Invoice No Already Exist !!!");
    // }
 
        $mvatrate = $row["vatrate"];
 
    $totpay1 = 1;

    $sql = "select * from s_cusordtrn_tmp where tmp_no='" . $_GET["tmpno"] . "'";
    foreach ($conn->query($sql) as $rowtmp) {
        
        if($rowtmp['type']=='add'){
            $dis_per = $rowtmp["cur_rate"] * $rowtmp["cur_qty"] * $rowtmp["cur_discount"] * 0.01;
        
            $d1 = $rowtmp["dis_per"];
            $d2 = $rowtmp["dis_per1"];
            $d3 = 0;
        
            if ($d1 == "") {
                $d1 = 0;
            }
            if ($d2 == "") {
                $d2 = 0;
            }
            if ($d3 == "") {
                $d3 = 0;
            }

            $sqlmas = "select * from s_mas where STK_NO='" . trim($rowtmp["str_code"]) . "'";
            $resultmas = $conn->query($sqlmas);
            $rowmas = $resultmas->fetch();
     
            $sql_invo = "Insert into s_cusordtrn  (REF_NO, SDATE, STK_NO, DESCRIPT, PART_NO, COST, PRICE, QTY, DEPARTMENT, DIS_per, DIS_rs, REP, TAX_PER, BRAND, vatrate, Print_dis1, Print_dis2, Print_dis3, subtot, ret_qty, DEV, CANCELL, c_code, seri_no, ad,sdate1,SERIALNO,TYPE) values "
            . "('" . $invno . "', '" . $_GET["invdate"] . "', '" . trim($rowtmp["str_code"]) . "', '" . trim($rowtmp["str_description"]) . "', '" . $rowmas["PART_NO"] . "', " . $rowmas["COST"] . ", " . $rowtmp["actual_selling"] . ", " . $rowtmp["cur_qty"] . ", '" . trim($_GET["department"]) . "', '" . $rowtmp["cur_discount"] . "', " . $dis_per . ", '" . $_GET["salesrep"] . "', '" . $mvatrate . "', '" . $rowmas["BRAND_NAME"] . "', " . $mvatrate . ", " . $d1 . ", " . $d2 . ", " . $d3 . ", " . $rowtmp["cur_subtot"] . ", '0', '', '0', '" . $_GET["customercode"] . "', '', '" . $rowtmp["ad"] . "','" . $_GET["invdate"] . "' , '" . $rowtmp["serialno"] . "','PRODUCT')";
            $result_invo = $conn->query($sql_invo);
        
            $act_selling=$rowtmp["actual_selling"]-($rowtmp["actual_selling"]*$rowtmp["cur_discount"]/100);
        }
        
        if($rowtmp['type']=='dag'){
            $dis_per = $rowtmp["cur_rate"] * $rowtmp["cur_qty"] * $rowtmp["dis_per"] * 0.01;

            $sqlmas = "select * from s_mas where STK_NO='" . trim($rowtmp["str_code"]) . "'";
            $resultmas = $conn->query($sqlmas);
            $rowmas = $resultmas->fetch();
     
            $sql_invo = "Insert into s_cusordtrn  (REF_NO, SDATE, STK_NO, DESCRIPT, JOBNO,MAKE,DESIGN,SIZE, COST, PRICE, QTY, DEPARTMENT, DIS_per, DIS_rs, REP, TAX_PER, BRAND, vatrate, Print_dis1, Print_dis2, Print_dis3, subtot, ret_qty, DEV, CANCELL, c_code, seri_no, ad,sdate1,SERIALNO,TYPE) values "
            . "('" . $invno . "', '" . $_GET["invdate"] . "', '" . trim($rowtmp["str_code"]) . "', '" . trim($rowtmp["str_description"]) . "', '" . $rowtmp["jobno"] . "', '" . $rowtmp["make"] . "', '" . $rowtmp["design"] . "', '" . $rowtmp["size"] . "', " . $rowtmp["cost"] . ", " . $rowtmp["actual_selling"] . ", " . $rowtmp["cur_qty"] . ", '" . trim($_GET["department"]) . "', '" . $rowtmp["dis_per"] . "', " . $dis_per . ", '" . $_GET["salesrep"] . "', '" . $mvatrate . "', '" . $rowmas["BRAND_NAME"] . "', " . $mvatrate . ", " . $d1 . ", " . $d2 . ", " . $d3 . ", " . $rowtmp["cur_subtot"] . ", '0', '', '0', '" . $_GET["customercode"] . "', '', '" . $rowtmp["ad"] . "','" . $_GET["invdate"] . "' , '" . $rowtmp["serialno"] . "','DAG')";
            $result_invo = $conn->query($sql_invo);
        
            $act_selling=$rowtmp["actual_selling"]-($rowtmp["actual_selling"]*$rowtmp["dis_per"]/100);
           
        }
        
    }
    
    $sqlrep = "select * from s_salrep where REPCODE = '" . trim($_GET["salesrep"]) . "'";
    $resultrep = $conn->query($sqlrep);
    if ($rowrep = $resultrep->fetch()) {
        $maindepart = $rowrep['RGROUP1'];
    } else {
        $maindepart = "";
    }
    
    $cardfee=$invtot-$invtot/(100+$_GET["cardfee"])*100;
    
    if ($balance < $invtot) {
        $ex_lim = $invtot - $balance;
    } else {
        $ex_lim = 0;
    }
    
    if ($ex_lim == 0) {
        $result = "OK";
    } else {
        $result = "P";
    }
    
    $result = "OK";

    $sql = "Insert into s_cusordmas  (REF_NO, TRN_TYPE, SDATE, C_CODE, TEL,Brand, CUS_NAME, VAT, VAT_VAL, TYPE, DISCOU, AMOUNT, GRAND_TOT,  TOTPAY, ORD_NO, ORD_DA,  DEPARTMENT, SAL_EX, BTT, cre_pe, GST, DIS, DIS1, DIS2, SVAT, Account, TOTPAY1, REMARK, REQ_DATE, CANCELL, DEV, tmp_no, DIS_RUP, CASH, SETTLED, DES_CAT, Accname, Costcenter, RET_AMO, Comm, red, seri_no, points, LOCK1, deliin, vat_no, s_vat_no, C_ADD1,c_code1,transp,deli_name,deli_add,maindepartment,sdate1,company,veheno,jobno,millage,note,deli_date,PAY_TYPE,type2,labour,INQUIRY_NO,CARD_FEE,CARD_FEERATE,Result) values "
    . "('" . $invno . "', 'INV', '" . $_GET["invdate"] . "', '" . trim($_GET["customercode"]) . "', '" . $_GET["tel"] . "', '" . trim($_GET["brand"]) . "', '" . trim($customername) . "','" . $vat . "', " . $tax . ", '".$_GET["paymethod"]."'," . $totdiscount . ", " . $subtot . " , " . $invtot . ", 0, '" . trim($_GET["salesord1"]) . "', '" . $_GET["invdate"] . "', '" . trim($_GET["department"]) . "', '" . trim($_GET["salesrep"]) . "', " . $tax . ", " . $_GET["credper"] . " , " . $mvatrate . ", " . $d1 . ", " . $d2 . ", " . $d3 . ", '" . $svat . "', 'NOTAUTH', '" . $totpay1 . "',  '" . $invno . "', '" . $_GET["invdate"] . "', '0', '" . $_SESSION['dev'] . "', '" . $_GET["tmpno"] . "', 0, 0, '0', 'N', 'OFFICE', '" . $_GET['promotion'] . "', 0, 'N', '0', '', '0', '0', '', '" . trim($_GET["vat1"]) . "', '" . trim($_GET["vat2"]) . "', '" . $cus_address . "','" . $_GET['c_subcode'] . "','" . $_GET['delitype'] . "','" . $_GET['deli_name'] . "','" . $_GET['deli_address'] . "','" . $maindepart . "','" . $_GET["invdate"] . "','".$COMPANY."','" . $_GET["vehino"] . "','" . $_GET["jobno"] . "','" . $_GET["millage"] . "', '" . $_GET["remarks"] . "','" . $_GET["invdate"] . "','" . $_GET["pay_type"] . "','" . $_GET["type2"] . "','" . $_GET["labour"] . "','" . $_GET["inquiry"] . "','" . $cardfee . "','" . $_GET["cardfee"] . "','". $result ."')";
    $resultsalma = $conn->query($sql);

    $sql = "delete from s_cusordtrn_tmp where user= '" . $_SESSION["CURRENT_USER"] . "' ";
    $result = $conn->query($sql);
			
    $sqlbrand = "insert into entry_log(refno, username, docname, trnType, stime, sdate) values 
    ('" . trim($invno) . "', '" . $_SESSION["CURRENT_USER"] . "', 'Sales Order', 'Save', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
    $resultbrand = $conn->query($sqlbrand);

    $conn->commit();
    echo $invno . " Saved";
} catch (Exception $e) {
    $conn->rollBack();
    echo $e;
}
}

if ($_GET["Command"] == "deli_update") {

    try {
        $sql = "update s_cusordmas set ORD_NO= '" . $_GET["salesord1"] . "',deli_name= '" . $_GET["deli_name"] . "',veheno= '" . $_GET["vehino"] . "',jobno= '" . $_GET["jobno"] . "',millage= '" . $_GET["millage"] . "',note= '" . $_GET["remarks"] . "', deli_add='" . $_GET["deli_address"] . "' where  REF_NO='" . $_GET["invno"] . "'";
        $result = $conn->query($sql);

        echo "Updated";
    } catch (Exception $e) {
        $conn->rollBack();
        echo $e;
    }
}

if ($_GET["Command"] == "cred_update") {

    try {
        $sql = "update s_cusordmas set cre_pe= '" . $_GET["credper"] . "' where  REF_NO='" . $_GET["invno"] . "'";
        $result = $conn->query($sql);

        $sqlentry = "insert into entry_log(refno, username, docname, trnType, stime, sdate) values ('" . $_GET["invno"] . "', '" . $_SESSION["CURRENT_USER"] . "', 'Sales Order', 'CredDays Update', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
        $resultenrty = $conn->query($sqlentry);

        echo "C.P Updated";
    } catch (Exception $e) {
        $conn->rollBack();
        echo $e;
    }
}  


if ($_GET["Command"] == "vendor_save") {


    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";

    try {
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->beginTransaction();
  
        $sqlinv = "select * from vendor where NAME='" . $_GET["customer_name"] . "' and TELE1='" . $_GET["customer_tel"] . "' ";
        $resultinv = $conn->query($sqlinv);
        if ($rowinv = $resultinv->fetch()) {
            $msg= "Already Found Customer..!!!!";   
            $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
            $ResponseXML .= "</salesdetails>";
            echo $ResponseXML;
            exit(); 
        }
        
       
        
        $sql = "SELECT cus,VATTYPE FROM invpara where flag='".$_SESSION['company']."'";  
        $result = $conn->query($sql);
        $row = $result->fetch();
        
        $vattype=$row['VATTYPE'];
        $no = $row['cus'];
        $tmpinvno = "0000" . $no;
        $lenth = strlen($tmpinvno);
        $refno = trim("V/ ") . substr($tmpinvno, $lenth - 4);
        
        $sql_1 = "select * from vendor where CODE='" . $refno . "'  ";
        $result_1= $conn->query($sql_1);
        if ($row_1 = $result_1->fetch()) {
            $msg= "Error Result..";   
            $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
            $ResponseXML .= "</salesdetails>";
            echo $ResponseXML;
            exit(); 
        }
        
        if($vattype =="1"){
            if(($_GET['customer_vat_no'] == "")){
                $msg= "Please Enter Vat No";   
                $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
                $ResponseXML .= "</salesdetails>";
                echo $ResponseXML;
                exit(); 
            }
            
        }else if($vattype =="0"){
            if(($_GET['customer_vat_no'] != "") && ($_GET['customer_vat_no'] !="")){
                $msg= "Can't Add Vat Customer.Please Clear Vat No & Svat No";   
                $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
                $ResponseXML .= "</salesdetails>";
                echo $ResponseXML;
                exit(); 
            }
        }
        
        
        
 
       
        $txtCNAME = str_replace("~", "&", $_GET['customer_name']);
    
        
        $sql_data = "insert into vendor  (CODE, NAME, ADD1,TELE1,vatno, CAT, svatno,OPDATE) values 
          ('" . $refno . "', '" . $txtCNAME . "', '" . $_GET['customer_address'] . "', '" . $_GET['customer_tel'] . "', '" . $_GET['customer_vat_no'] . "', 'C', '" . $_GET['customer_svat_no'] . "','" . date("Y-m-d") . "')";
        $result_data = $conn->query($sql_data);
        
        $sql = "delete from vender_sub where c_code = '" . $refno . "' and c_main = '" . $refno . "'";
        $result = $conn->query($sql);


        $c_add = $_GET['customer_address'];
        $sql = "insert into vender_sub (c_code,c_name,c_add,c_tele,c_vatno,c_svatno,c_main,type) values
        ('" . $refno . "','" . $txtCNAME . "','" . $c_add . "','" . $_GET['customer_tel'] . "','" . $_GET['customer_vat_no'] . "','" . $_GET['customer_svat_no'] . "','" . $refno . "','M') ";
        $result = $conn->query($sql);
        
         $sql = "update invpara set cus = cus + 1"; 
         $result = $conn->query($sql);
         
         
        $sql2 = "insert into entry_log(refno, username, docname, trnType, stime, sdate) values 
        ('" . $refno . "', '" . $_SESSION["CURRENT_USER"] . "', 'Customer', 'Save', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
        $result2 = $conn->query($sql2);
        
        $msg ="Saved";
                
        $conn->commit();
            
         
    } catch (Exception $e) {
        $conn->rollBack();
        echo $e;
    }
    
    $sql_VEN= "select * from vendor where CODE='" . $refno . "' ";
    $result_VEN = $conn->query($sql_VEN);
    if ($row_VEN = $result_VEN->fetch()) {
        
        $ResponseXML .= "<customer_code><![CDATA[" . $row_VEN['CODE'] . "]]></customer_code>";
        $ResponseXML .= "<customer_name><![CDATA[" . $row_VEN['NAME'] . "]]></customer_name>";
        $ResponseXML .= "<customer_tel><![CDATA[" . $row_VEN['TELE1'] . "]]></customer_tel>";
        $ResponseXML .= "<customer_address><![CDATA[" . $row_VEN['ADD1'] . "]]></customer_address>";
        $ResponseXML .= "<customer_vat_no><![CDATA[" . $row_VEN['vatno'] . "]]></customer_vat_no>";
        $ResponseXML .= "<customer_svat_no><![CDATA[" . $row_VEN['svatno'] . "]]></customer_svat_no>";
    }else{
        $msg="Error Result.."; 
    }
         
    $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
    
 
    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;
}

if ($_GET["Command"] == "find_customer") {

 

    try {
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->beginTransaction();
  
        $sqlinv = "select * from vendor where TELE1='" . $_GET["customer_tel"] . "' "; 
        $resultinv = $conn->query($sqlinv);
        if ($rowinv = $resultinv->fetch()) {
            exit('Telephone No Result Customer Found.Please Check...!!!');
        }else{
            
        }
        
         
    } catch (Exception $e) {
        $conn->rollBack();
        echo $e;
    }
    
    
}

if ($_GET["Command"] == "pass_quot5") { 

    header('Content-Type: text/xml');
    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";

    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";

    $cuscode = $_GET["custno"];

    $sql = "Select * from s_inquiry where   REFNO ='" . $cuscode . "'";
    $result = $conn->query($sql);

    if ($rowM = $result->fetch()) {
        $ResponseXML .= "<id><![CDATA[" . json_encode($rowM) .  "]]></id>";
    }

    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;
}


if ($_GET["Command"] == "pass_dag") {
    $_SESSION["custno"] = $_GET['custno'];

    header('Content-Type: text/xml');
    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";

    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";

    $cuscode = $_GET["custno"];
    
    
      
      
    $sql1 = "SELECT * from  s_cusordtrn_tmp where serialno='" . $_GET['serialno'] . "' and str_code='" . $_GET['jobno'] . "' and type='dag'"; 
    $result1 = $conn->query($sql1);

    if ($row1 = $result1->fetch()) {
         $ResponseXML .= "<val><![CDATA[" . 'yes' . "]]></val>";
    }else{
         $ResponseXML .= "<val><![CDATA[" . 'no' . "]]></val>";
    }
    
    $sql = "SELECT * from dag_item where id='".$cuscode."' and cancel='0'  ";
    $result = $conn->query($sql);

    if ($rowM = $result->fetch()) {
        $ResponseXML .= "<id><![CDATA[" . json_encode($rowM) .  "]]></id>";
    }

    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;
}

if ($_GET["Command"] == "pass_inv") {
    header('Content-Type: text/xml');
   
    $brand = "";
    $salrep = "";
    $cuscode = "";

    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    $inv = $_GET['invno'];
    $_SESSION["invno"] = $_GET['invno'];

    $_SESSION["custno"] = $_GET['custno'];
    $_SESSION["brand"] = $_GET["brand"];
    $_SESSION["department"] = $_GET["department"];
    //$tmpinvno="0000".substr($_GET['invno'], 4, 7) ;
    //$lenth=strlen($tmpinvno);
    //$serial=substr($tmpinvno, $lenth-7);
    //$inv=substr($_GET['invno'], 0, 3).substr("\ ", 0, 1).$serial;
    //$a="Select * from s_cusordmas where REF_NO='".$inv."'";
    //echo $a;
    $sqlxl = "Select * from s_cusordmas where REF_NO='" . $inv . "'";
    $result_xl = $conn->query($sqlxl);
    $row_xl = $result_xl->fetch();

    $sql = "SELECT * from invpara";
    $result = $conn->query($sql);
    $row_invpara = $result->fetch();

    $sql_vat = "SELECT * from vatrate where sdate<='" . $row_xl["SDATE"] . "' order by sdate desc";
    $result_vat = $conn->query($sql_vat);
    $row_vat = $result_vat->fetch();

    $sql = "Select * from s_cusordmas where REF_NO='" . $inv . "'";
    $result = $conn->query($sql);
    if ($row = $result->fetch()) {

        $sdate = $row['SDATE'];
        $ResponseXML .= "<str_invoiceno><![CDATA[" . $row['REF_NO'] . "]]></str_invoiceno>";
        $ResponseXML .= "<inquiry><![CDATA[" . $row['INQUIRY_NO'] . "]]></inquiry>";
        $ResponseXML .= "<cancel><![CDATA[" . $row['CANCELL'] . "]]></cancel>";
        $ResponseXML .= "<SDATE><![CDATA[" . $row['SDATE'] . "]]></SDATE>";
        $ResponseXML .= "<str_crecash><![CDATA[" . $row['TYPE'] . "]]></str_crecash>";
        $ResponseXML .= "<pay_type><![CDATA[" . $row['PAY_TYPE'] . "]]></pay_type>";
        $ResponseXML .= "<type2><![CDATA[" . $row['type2'] . "]]></type2>";
        $ResponseXML .= "<REMARK><![CDATA[" . $row['note'] . "]]></REMARK>";
        $ResponseXML .= "<TYPE><![CDATA[" . $row['TYPE'] . "]]></TYPE>";
        $ResponseXML .= "<TEL><![CDATA[" . $row['TEL'] . "]]></TEL>";
        $ResponseXML .= "<labour><![CDATA[" . $row['labour'] . "]]></labour>";
        $ResponseXML .= "<cardfee><![CDATA[" . $row['CARD_FEERATE'] . "]]></cardfee>";
        $cuscode = $row['C_CODE'];
        $ResponseXML .= "<str_customecode><![CDATA[" . $row['C_CODE'] . "]]></str_customecode>";
        $_SESSION["tmp_no_salinv"] = $row['tmp_no'];

        /* $sqlcustomer = mysqli_query($GLOBALS['dbinv'],"Select * from vendor where CODE='".$row['C_CODE']."'") or die(mysqli_error());
          if($rowcustomer = mysqli_fetch_array($sqlcustomer)){
          $ResponseXML .= "<str_customername><![CDATA[".$rowcustomer['NAME']."]]></str_customername>";
          $ResponseXML .= "<str_address><![CDATA[".$rowcustomer['ADD1']." ".$rowcustomer['ADD2']."]]></str_address>";
          $ResponseXML .= "<str_vatno1><![CDATA[".$rowcustomer['vatno']."]]></str_vatno1>";
          $ResponseXML .= "<str_vatno2><![CDATA[".$rowcustomer['svatno']."]]></str_vatno2>";
          } */

        $ResponseXML .= "<str_customername><![CDATA[" . $row['CUS_NAME'] . "]]></str_customername>";
        $ResponseXML .= "<SVAT><![CDATA[" . $row['SVAT'] . "]]></SVAT>";

        $sql_mas = "Select * from vendor where CODE='" . $row['C_CODE'] . "'";
        $result = $conn->query($sql_mas);
        $row_mas = $result->fetch();
        //$add=$row_mas['ADD1']." ".$row_mas['ADD2'];

        $ResponseXML .= "<str_address><![CDATA[" . $row_mas['ADD1'] . "]]></str_address>";
        $ResponseXML .= "<str_address2><![CDATA[" . $row_mas['ADD2'] . "]]></str_address2>";
        $ResponseXML .= "<str_vatno1><![CDATA[" . $row_mas['vatno'] . "]]></str_vatno1>";
        $ResponseXML .= "<str_vatno2><![CDATA[" . $row_mas['svatno'] . "]]></str_vatno2>";
        $ResponseXML .= "<delitype><![CDATA[" . $row['transp'] . "]]></delitype>";

        //$ResponseXML .= "<str_vatno2><![CDATA[".$row['str_vatno2']."]]></str_vatno2>";
        $ResponseXML .= "<str_salesrep><![CDATA[" . $row['SAL_EX'] . "]]></str_salesrep>";
        $salrep = $row['SAL_EX'];
        //$ResponseXML .= "<str_salesorder1><![CDATA[".$row['str_salesorder1']."]]></str_salesorder1>";
        //$ResponseXML .= "<str_salesorder2><![CDATA[".$row['str_salesorder2']."]]></str_salesorder2>";
        $ResponseXML .= "<dte_deliverdate><![CDATA[" . $row['REQ_DATE'] . "]]></dte_deliverdate>";
        $ResponseXML .= "<str_orderno1><![CDATA[" . $row['ORD_NO'] . "]]></str_orderno1>";
        $ResponseXML .= "<str_orderno2><![CDATA[" . $row['ORD_DA'] . "]]></str_orderno2>";
        //$ResponseXML .= "<cur_credit><![CDATA[".$row['cur_credit']."]]></cur_credit>";
        //$ResponseXML .= "<cur_balance><![CDATA[".$row['cur_balance']."]]></cur_balance>";
        $ResponseXML .= "<promotion><![CDATA[" . $row['Costcenter'] . "]]></promotion>";


        $ResponseXML .= "<str_department><![CDATA[" . $row['DEPARTMENT'] . "]]></str_department>";
        $ResponseXML .= "<str_brand><![CDATA[" . $row['Brand'] . "]]></str_brand>";
        $brand = $row['Brand'];
        $ResponseXML .= "<str_vat><![CDATA[" . $row['VAT'] . "]]></str_vat>";
        $VAT_add = $row['VAT'];
        //$ResponseXML .= "<cur_discount1><![CDATA[".$row['cur_discount1']."]]></cur_discount1>";
        //$ResponseXML .= "<cur_discount2><![CDATA[".$row['cur_discount2']."]]></cur_discount2>";
        
        
        $ResponseXML .= "<vehino><![CDATA[" . $row['veheno'] . "]]></vehino>"; 
        $ResponseXML .= "<jobno><![CDATA[" . $row['jobno'] . "]]></jobno>";
        $ResponseXML .= "<millage><![CDATA[" . $row['millage'] . "]]></millage>";
       
        
        if (($VAT_add == "1") or ( $VAT_add == "2") or ( $VAT_add == "3")) {
            $vat_val = $row['AMOUNT'] * $row_vat["vatrate"] / 100;
        } else {
            $vat_val = 0;
        }

        $ResponseXML .= "<cur_tax><![CDATA[" . number_format($vat_val, 2, ".", ",") . "]]></cur_tax>";
        $grand_tot = $row['AMOUNT'] + $vat_val;

        //$ResponseXML .= "<cur_invoiceval><![CDATA[".number_format($grand_tot, 2, ".", ",")."]]></cur_invoiceval>";
        $ResponseXML .= "<cur_invoiceval><![CDATA[" . number_format($row['GRAND_TOT'], 2, ".", ",") . "]]></cur_invoiceval>";
        if ($row['deli_name'] == "") {
            $ResponseXML .= "<deli_chk1><![CDATA[" . 'N' . "]]></deli_chk1>";
        } else {
            $ResponseXML .= "<deli_chk1><![CDATA[" . 'Y' . "]]></deli_chk1>";
        }


        $ResponseXML .= "<deli_name><![CDATA[" . $row['deli_name'] . "]]></deli_name>";
        $ResponseXML .= "<deli_add><![CDATA[" . $row['deli_add'] . "]]></deli_add>";
        $ResponseXML .= "<cred_per><![CDATA[" . $row['cre_pe'] . "]]></cred_per>";

         
            $ResponseXML .= "<cred_but><![CDATA[" . 'Y' . "]]></cred_but>";
        
    }


    $ResponseXML .= "<sales_table><![CDATA[<table class=\"table\"><tr>
                              <th  class='col-md-1'>Item Code</th>
    <th  size='15'>&nbsp;</th>
    <th  class='col-md-3'>Description</th>
    <th  class='col-md-1'>Serial No</th>
    <th  class='col-md-2'>Price</th>
    <th  class='col-md-1'>Qty</th>
    <th class='col-md-1'>Dis1 (%)</th>
    <th class='col-md-1'>Dis2 (%)</th>
    <th class='col-md-2'>Unit Total</th>
    <th  size='15'>#</th>
    <th  size='15'></th>
                            </tr>";

    $i = 1;
    $sql_data = "delete from s_cusordtrn_tmp where tmp_no='" . $_SESSION["tmp_no_salinv"] . "'";
    $result = $conn->query($sql_data);

    $sql_data = "Select * from s_cusordtrn where REF_NO='" . $inv . "' and TYPE='PRODUCT'";
    foreach ($conn->query($sql_data) as $row) {
        
        if ($VAT_add == "1") {

            // $PRICE = $row['PRICE'] / (1 + ($row["TAX_PER"] / 100));
            $PRICE = $row['PRICE'] ;
        } else {
            $PRICE = $row['PRICE'];
        }

        $subtot_wo_disc = (floatval($PRICE) * floatval($row['QTY']));
        $disco = $subtot_wo_disc * floatval($row['DIS_per']) / 100;
        $subtot = $subtot_wo_disc - $disco;
        //echo $subtot;

        $dis_per1 = $row["Print_dis1"];
        $dis_per2 = $row["Print_dis2"];
        $dis_per3 = $row["Print_dis3"];



      
        $ad = "ad" . $i;


        $ResponseXML .= "<tr>
                           	
						    <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['STK_NO'] . "</a></td>
						    <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\" size='15'>&nbsp;</td>
  							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['DESCRIPT'] . "</a></td>
  							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['SERIALNO'] . "</a></td>
							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . number_format($PRICE, 2, ".", ",") . "</a></td>
							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['QTY'] . "</a></td>
							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['Print_dis1'] . "</td>
							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['Print_dis2'] . "</td>
							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . number_format($subtot, 2, ".", ",") . "</a></td>";

       $subtotal=$subtotal+ ($PRICE*$row['QTY']);
       $totdisco=$totdisco+$disco;
   
        $ResponseXML .= "</tr>";

        $i = $i + 1;
         
    }

    $ResponseXML .= "   </table>]]></sales_table>";
    
    
      $ResponseXML .= "<sales_dagtable><![CDATA[<table class=\"table\"><tr>
                           <th style=\"width: 100px;\">JOB NO</th>
    <th style=\"width: 10px;\"></th>
    <th style=\"width: 100px;\">MAKE</th> 
    <th style=\"width: 70px;\">SIZE</th>
    <th style=\"width: 70px;\">DESIGN</th>
    <th style=\"width: 100px;\">SERIAL NO</th> 
    <th style=\"width: 90px;\">COST</th>
    <th style=\"width: 120px;\">SELLING</th> 
    <th style=\"width: 60px;\">Dis</th>
    <th style=\"width: 120px;\">SubTotal</th>
    <th style=\"width: 50px;\"></th>
                            </tr>";

    $i = 1;
    $sql_data = "delete from s_cusordtrn_tmp where tmp_no='" . $_SESSION["tmp_no_salinv"] . "'";
    $result = $conn->query($sql_data);

    $sql_data = "Select * from s_cusordtrn where REF_NO='" . $inv . "' and TYPE='DAG'";
    foreach ($conn->query($sql_data) as $row) {
         
 
        if ($VAT_add == "1") {

            // $PRICE = $row['PRICE'] / (1 + ($row["TAX_PER"] / 100));
            $PRICE = $row['PRICE'] ;
        } else {
            $PRICE = $row['PRICE'];
        }

        $subtot_wo_disc = (floatval($PRICE) * floatval($row['QTY']));
        $disco = $subtot_wo_disc * floatval($row['DIS_per']) / 100;
        $subtot = $subtot_wo_disc - $disco;
        //echo $subtot;

        $dis_per1 = $row["Print_dis1"];
        $dis_per2 = $row["Print_dis2"];
        $dis_per3 = $row["Print_dis3"];

 
        $ad = "ad" . $i;


        $ResponseXML .= "<tr>
                           	
						    <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['JOBNO'] . "</a></td>
						    <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['MAKE'] . "</a></td>
						    <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['SIZE'] . "</a></td>
						    <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['DESIGN'] . "</a></td>
						    <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['SERIALNO'] . "</a></td>
						    <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . number_format($row['COST'], 2, ".", ",") . "</a></td> 
							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . number_format($PRICE, 2, ".", ",") . "</a></td> 
							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . $row['DIS_per'] . "</td>
							 <td onClick=\"disp_qty('" . $row['STK_NO'] . "');\">" . number_format($subtot, 2, ".", ",") . "</a></td>";

       $subtotal=$subtotal+ ($PRICE*$row['QTY']);
       $totdisco=$totdisco+$disco;
   
        $ResponseXML .= "</tr>";

        $i = $i + 1;
         
    }

    $ResponseXML .= "   </table>]]></sales_dagtable>";
    
    
    
    $ResponseXML .= "<cur_discount><![CDATA[" . number_format($totdisco, 2, ".", ",") . "]]></cur_discount>";
     $ResponseXML .= "<cur_subtotal><![CDATA[" . number_format($subtotal, 2, ".", ",") . "]]></cur_subtotal>";
    $ResponseXML .= "<dis><![CDATA[" . $dis_per1 . "]]></dis>";
    $ResponseXML .= "<dis1><![CDATA[" . $dis_per2 . "]]></dis1>";
    $ResponseXML .= "<dis2><![CDATA[" . $dis_per3 . "]]></dis2>";
    $ResponseXML .= "<cur_discount1><![CDATA[" . number_format($dis_per1, 2, ".", ",") . "]]></cur_discount1>";
    $ResponseXML .= "<cur_discount2><![CDATA[" . number_format($dis_per2, 2, ".", ",") . "]]></cur_discount2>";
    $ResponseXML .= "<cur_discount3><![CDATA[" . number_format($dis_per3, 2, ".", ",") . "]]></cur_discount3>";

 


    $OutpDAMT = 0;
    $OutREtAmt = 0;
    $OutInvAmt = 0;
    $InvClass = "";

    // $sqlclass = mysqli_query($GLOBALS['dbinv'], "select class from brand_mas where barnd_name='" . trim($brand) . "'") or die(mysqli_error());
    // if ($rowclass = mysqli_fetch_array($sqlclass)) {
    //     if (is_null($rowclass["class"]) == false) {
    //         $InvClass = $rowclass["class"];
    //     }
    // }

    $sqloutinv = "select sum(GRAND_TOT-TOTPAY) as totout from s_cusordmas where GRAND_TOT>TOTPAY and CANCELL='0' and C_CODE='" . trim($cuscode) . "' and SAL_EX='" . trim($salrep) . "' ";
    // echo $sqloutinv;
    $result = $conn->query($sqloutinv);
    if ($rowoutinv = $result->fetch()) {
        if (is_null($rowoutinv["totout"]) == false) {
            $OutInvAmt = $rowoutinv["totout"];
        }
    }

    // $sqlinvcheq = mysqli_query($GLOBALS['dbinv'], "SELECT * FROM s_invcheq WHERE che_date>'" . date("Y-m-d") . "' AND cus_code='" . trim($cuscode) . "' and trn_type='REC' and sal_ex='" . trim($salrep) . "'") or die(mysqli_error());
    // while ($rowinvcheq = mysqli_fetch_array($sqlinvcheq)) {

    //     $sqlsttr = mysqli_query($GLOBALS['dbinv'], "select * from s_sttr where ST_REFNO='" . trim($rowinvcheq["refno"]) . "' and ST_CHNO ='" . trim($rowinvcheq["cheque_no"]) . "'") or die(mysqli_error());
    //     while ($rowsttr = mysqli_fetch_array($sqlsttr)) {
    //         $sqlview_s_salma = mysqli_query($GLOBALS['dbinv'], "select class from view_s_salma where REF_NO='" . trim($rowsttr["ST_INVONO"]) . "'") or die(mysqli_error());
    //         if ($rowview_s_salma = mysqli_fetch_array($sqlview_s_salma)) {

    //             if (trim($rowview_s_salma["class"]) == $InvClass) {
    //                 $OutpDAMT = $OutpDAMT + $rowsttr["ST_PAID"];
    //             }
    //         }
    //     }
    // }



    // $pend_ret_set = 0;

    // $sqlinvcheq = mysqli_query($GLOBALS['dbinv'], "SELECT sum(che_amount) as  che_amount FROM s_invcheq WHERE che_date >'" . date("Y-m-d") . "' AND cus_code='" . trim($cuscode) . "' and trn_type='RET'") or die(mysqli_error());
    // if ($rowinvcheq = mysqli_fetch_array($sqlinvcheq)) {
    //     if (is_null($rowinvcheq["che_amount"]) == false) {
    //         $pend_ret_set = $rowinvcheq["che_amount"];
    //     }
    // }


    // $sqlcheq = mysqli_query($GLOBALS['dbinv'], "Select sum(CR_CHEVAL-PAID) as tot from s_cheq where CR_C_CODE='" . trim($cuscode) . "'  and CR_CHEVAL-PAID>0 and CR_FLAG='0' and S_REF='" . trim($salrep) . "'") or die(mysqli_error());
    // if ($rowcheq = mysqli_fetch_array($sqlcheq)) {
    //     if (is_null($rowcheq["tot"]) == false) {
    //         $OutREtAmt = $rowcheq["tot"];
    //     } else {
    //         $OutREtAmt = 0;
    //     }
    // }





    $ResponseXML .= "<sales_table_acc><![CDATA[ <table  border=0  cellspacing=0>
						<tr><td width=\"200\"><input type=\"text\"  class=\"label_purchase\" value=\"Outstanding Invoice Amount\" disabled=\"disabled\"/></td><td><input type=\"text\"  class=\"label_purchase\" value=\"" . number_format($OutInvAmt, 2, ".", ",") . "\" disabled=\"disabled\"/></td></tr>
						 <td><input type=\"text\"  class=\"label_purchase\" value=\"Return Cheque Amount\" disabled=\"disabled\"/></td><td><input type=\"text\"  class=\"label_purchase\" value=\"" . number_format($OutREtAmt, 2, ".", ",") . "\" disabled=\"disabled\"/></td></tr>
						 <td><input type=\"text\"  class=\"label_purchase\" value=\"Pending Cheque Amount\" disabled=\"disabled\"/></td><td><input type=\"text\"  class=\"label_purchase\" value=\"" . number_format($OutpDAMT, 2, ".", ",") . "\" disabled=\"disabled\"/></td></tr>
						 <td><input type=\"text\"  class=\"label_purchase\" value=\"PSD Cheque Settlments\" disabled=\"disabled\"/></td><td><input type=\"text\"  class=\"label_purchase\" value=\"" . number_format($pend_ret_set, 2, ".", ",") . "\" disabled=\"disabled\"/></td></tr>
						 <td><input type=\"text\"  class=\"label_purchase\" value=\"Total\" disabled=\"disabled\"/></td><td><input type=\"text\"  class=\"label_purchase\" value=\"" . number_format($OutInvAmt + $OutREtAmt + $OutpDAMT + $pend_ret_set, 2, ".", ",") . "\" disabled=\"disabled\"/></td></tr>
						 </table></table>]]></sales_table_acc>";



    // $sqlbr_trn = mysqli_query($GLOBALS['dbinv'], "select * from br_trn where Rep='" . trim($salrep) . "' and brand='" . trim($InvClass) . "' and cus_code='" . trim($cuscode) . "'") or die(mysqli_error());
    // if ($rowbr_trn = mysqli_fetch_array($sqlbr_trn)) {
    //     if (is_null($rowbr_trn["credit_lim"]) == false) {
    //         $crLmt = $rowbr_trn["credit_lim"];
    //     } else {
    //         $crLmt = 0;
    //     }


    //     if (is_null($rowbr_trn["tmpLmt"]) == false) {
    //         $tmpLmt = $rowbr_trn["tmpLmt"];
    //     } else {
    //         $tmpLmt = 0;
    //     }

    //     if (is_null($rowbr_trn["CAT"]) == false) {
    //         $cuscat = trim($rowbr_trn["CAT"]);
    //         if ($cuscat == "A") {
    //             $m = 2.5;
    //         }
    //         if ($cuscat == "B") {
    //             $m = 2.5;
    //         }
    //         if ($cuscat == "C") {
    //             $m = 1;
    //         }
    //         if ($cuscat == "D") {
    //             $m = 0;
    //         }
    //         $txt_crelimi = "0";
    //         $txt_crebal = "0";
    //         $txt_crelimi = number_format($crLmt, 2, ".", ",");
    //         $crebal = $crLmt * $m + $tmpLmt - $OutInvAmt - $OutREtAmt - $OutpDAMT - $pend_ret_set;
    //         $txt_crebal = number_format($crebal, "2", ".", ",");
    //     } else {
    //         $txt_crelimi = "0";
    //         $txt_crebal = "0";
    //     }
    //     $creditbalance = $OutInvAmt + $OutREtAmt + $OutpDAMT;
    // }
    $ResponseXML .= "<txt_crelimi><![CDATA[" . $txt_crelimi . "]]></txt_crelimi>";
    $ResponseXML .= "<txt_crebal><![CDATA[" . $txt_crebal . "]]></txt_crebal>";

    $ResponseXML .= "<creditbalance><![CDATA[" . $creditbalance . "]]></creditbalance>";





    $ResponseXML .= "</salesdetails>";


    $_SESSION["print"] = 1;

    echo $ResponseXML;
}