<?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 SPINV2,VATTYPE,PAYTYPE from invpara where flag='".$COMPANY."'";
    $result = $conn->query($sql);
    $row = $result->fetch();
    
    $vattype=$row['VATTYPE'];
    $paytype=$row['PAYTYPE'];
    
    // Reset TEMP_NO for all items in tmp_inv_data before deleting
    $sql_reset = "UPDATE s_purtrn SET TEMP_NO = 0 WHERE STK_NO IN (SELECT str_code FROM tmp_inv_data WHERE user = '" . $_SESSION["CURRENT_USER"] . "')";
    $conn->query($sql_reset);


    $sql = "delete from tmp_inv_data where user= '" . $_SESSION["CURRENT_USER"] . "' ";
    $result = $conn->query($sql);
    
    // $sql = "delete from tmp_inv_data where user= '' ";
    // $result = $conn->query($sql);
    
    
//    if($row['PAYTYPE']=='CA'){ 
        $sql = "select INVC,INVCM,SPINV1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
         
        $tmpinvno="000000".($row["SPINV1"]);
        $lenth=strlen($tmpinvno);
        
        $invno=$row["INVC"].$row["INVCM"].substr($tmpinvno, $lenth-6);
     
        $sql = "Select SPINV2 from tmpinvpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
    
        $tono = $row['SPINV2'];
        
        // Reset TEMP_NO for all items in tmp_inv_data before deleting for this tmp_no
        $sql_reset = "UPDATE s_purtrn SET TEMP_NO = 0 WHERE STK_NO IN (SELECT str_code FROM tmp_inv_data WHERE tmp_no = '" . $tono . "')";
        $conn->query($sql_reset);
    
        $sql = "delete from tmp_inv_data where tmp_no='" . $tono . "'";
        $result = $conn->query($sql);
    
        $sql = "update tmpinvpara set SPINV2=SPINV2+1 where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $_SESSION["brand"]=$_GET["brand"];
         
    // }else{

    //     $sql = "select SPINV,SPINV3 from invpara where flag='".$COMPANY."'"; 
    //     $result = $conn->query($sql);
    //     $row = $result->fetch();
         
    //     $tmpinvno = "000000" . $row["SPINV"];
    //     $lenth = strlen($tmpinvno);
    //     $invno = trim("".$COMPANY."/INV/".$row["SPINV3"]."/") . substr($tmpinvno, $lenth - 7);
        
    //     $sql = "Select SPINV from tmpinvpara where flag='".$COMPANY."'"; 
    //     $result = $conn->query($sql);
    //     $row = $result->fetch();
    
    //     $tono = $row['SPINV'];
    
    //     $sql = "delete from tmp_inv_data where tmp_no='" . $tono . "'";
    //     $result = $conn->query($sql);
    
    //     $sql = "update tmpinvpara set SPINV=SPINV+1 where flag='".$COMPANY."'"; 
    //     $result = $conn->query($sql);
    //     $_SESSION["brand"]=$_GET["brand"];
        
    // }
    
    $_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'  "; 
        // echo $sql_sto; 
        $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>";
        }
        
        $sql_rep = "select * from s_salrep where pactive='1'  order by REPCODE";
        // echo $sql_rep;
        $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 type='Labour' "; 
        $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'  ";
        $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>";
        } 
        
        $sql_rep = "select * from s_salrep where pactive='1'  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 type='Labour' "; 
        $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"] == "paytype11") {
    
    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    
    $COMPANY=$_SESSION['company'];
    if ($_GET['paymethod'] == "CA") {
        $sql = "select SPINV2,SPINV4,flag1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
        if($_GET['type2']=="NORMAL"){
            $tmpinvno = "000000" .$row["SPINV2"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/INV/".$row["SPINV4"]."/") . substr($tmpinvno, $lenth - 7);
        }else{
            $COMPANY=$row['flag1'];
            
            $sql2 = "select SPINV2,SPINV4,flag1 from invpara where flag='".$COMPANY."'"; 
            $result2 = $conn->query($sql2);
            $row2 = $result2->fetch();
            
            $tmpinvno = "000000" .$row2["SPINV2"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/INV/".$row["SPINV4"]."/") . substr($tmpinvno, $lenth - 7);
        }
      
    }else{
        
        $sql = "select SPINV,SPINV3,flag1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
         
        if($_GET['type2']=="NORMAL"){
            $tmpinvno = "000000" .$row["SPINV"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/INV/".$row["SPINV3"]."/") . substr($tmpinvno, $lenth - 7);
        }else{
            $COMPANY=$row['flag1'];
            
            $sql2 = "select SPINV,SPINV3,flag1 from invpara where flag='".$COMPANY."'"; 
            $result2 = $conn->query($sql2);
            $row2 = $result2->fetch();
            
            $tmpinvno = "000000" .$row2["SPINV"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/INV/".$row["SPINV3"]."/") . substr($tmpinvno, $lenth - 7);
        }  
    }
    
    
    $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'  ";
        $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>";
        }
        
        
        $sql_rep = "select * from s_salrep where pactive='1'  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 type='Labour'"; 
        $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'  ";
        $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>";
        } 
        
        $sql_rep = "select * from s_salrep where pactive='1'  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 type='Labour'"; 
        $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 = $result->fetch();

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

        $sqlinv = "select * from s_salma 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_salma set CANCELL='1',note='".$_GET["remarks"]."' where REF_NO='" . $_GET["invno"] . "'";
                $result2 = $conn->query($sql2);
                
                $sql2 = "update s_salesmain set CANCELL='1',note='".$_GET["remarks"]."' where REF_NO='" . $_GET["invno"] . "'";
                $result2 = $conn->query($sql2);

                $sql2 = "update vendor set CUR_BAL=CUR_BAL-" . $rowinv["GRAND_TOT"] . " where CODE='" . $_GET["customer_code"] . "'";
                $result2 = $conn->query($sql2);


                $sql2 = "update br_trn set credit=credit-" . $rowinv["GRAND_TOT"] . " where cus_code='" . $_GET["customer_code"] . "' and Rep='" . $_GET["salesrep"] . "'";
                $result2 = $conn->query($sql2);
                
                $sql2="delete from a_ledger WHERE l_refno='" . $_GET["invno"] . "'";
                $resul2 = $conn->query($sql2);


                $sqltmp = "select * from s_invo where REF_NO='" . $_GET['invno'] . "' ";
                $resulttmp = $conn->query($sqltmp);
                while ($rowtmp = $resulttmp->fetch()) {
                    
                    $sqlmas = "select * from s_mas where STK_NO='" . trim($rowtmp["STK_NO"]) . "'";
                    $resultmas = $conn->query($sqlmas);
                    $rowmas = $resultmas->fetch();
 
                    if($rowmas['CAT'] =='Tmp Stock Item'){
                        $sql2 = "update s_mas set QTYINHAND=QTYINHAND-" . $rowtmp["QTY"] . " where STK_NO='" . $rowtmp['STK_NO'] . "'";
                        $resul2 = $conn->query($sql2);
    
                        $sql2 = "update s_submas set QTYINHAND=QTYINHAND-" . $rowtmp["QTY"] . " where STO_CODE='" . $rowinv["DEPARTMENT"] . "' and STK_NO='" . $rowtmp['STK_NO'] . "'";
                        $resul2 = $conn->query($sql2);
                    }else{
                        $sql2 = "update s_mas set QTYINHAND=QTYINHAND+" . $rowtmp["QTY"] . " where STK_NO='" . $rowtmp['STK_NO'] . "'";
                        $resul2 = $conn->query($sql2);
    
                        $sql2 = "update s_submas set QTYINHAND=QTYINHAND+" . $rowtmp["QTY"] . " where STO_CODE='" . $rowinv["DEPARTMENT"] . "' and STK_NO='" . $rowtmp['STK_NO'] . "'";
                        $resul2 = $conn->query($sql2);
                    }
                    
                    
                    $sql6 = "select * from dag_item where invno = '" . $rowtmp['REF_NO'] . "'";
                    $result6 = $conn->query($sql6);
                    if ($row6 = $result6->fetch()) {
                         if($row6['TYPE']=='SENDOTHER'){
                             $sql = "update dag_item set flag='5',inv_date=  '',invno=  null,amount1 = '0.00',repair1 = '0.00',total1 = '0.00',dis1 = '0.00' where invno = '" . $rowtmp['REF_NO'] . "'";
                            $result = $conn->query($sql);
                         }else{
                             $sql = "update dag_item set flag='2',inv_date=  '',invno=  null,amount1 = '0.00',repair1 = '0.00',total1 = '0.00',dis1 = '0.00' where invno = '" . $rowtmp['REF_NO'] . "'";
                            $result = $conn->query($sql);
                         }
                         
                    }
                    
                    $sql2 = "update s_invo set CANCELL='1' where REF_NO='" . $_GET['invno'] . "'";
                    $resul2 = $conn->query($sql2);

                    

                    $sql2 = "delete from s_trn where REFNO='" . $_GET['invno'] . "'";
                    $resul2 = $conn->query($sql2);

                    $sql2 = "delete from s_trn_all where REFNO='" . $_GET['invno'] . "'";
                    $resul2 = $conn->query($sql2);

                    $sql2 = "delete from s_trn_stores where REFNO='" . $_GET['invno'] . "'";
                    $resul2 = $conn->query($sql2);


                    $sql2 = "delete from s_led 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"] . "', 'Invoice', '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") {
    
    $msg="ok";
    
    $ResponseXML .= "<msg><![CDATA[".$msg."]]></msg>";

    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"]);
        
        $disper=0;
        $disper1=0;
        
        $sql_ven = "SELECT * from vendor where CODE='".$_GET['firstname_hidden']."' ";
        $result_ven = $conn->query($sql_ven);
        $row_ven = $result_ven->fetch();
        

        if ($row_ven["CAT"]== 'DE') {
            $smas_selling = $rowmas["DE_SELLING"];
    	}elseif ($row_ven["CAT"]== 'DI') {
            $smas_selling = $rowmas["DI_SELLING"];
        }else{
            
            if(($rowmas['Cat1'] !='SERVICE') && ($rowmas["MIN_SELLING"]<1)){
            
                $msg="Cannot Add. Please Update Selling Price";
                $ResponseXML .= "<msg><![CDATA[".$msg."]]></msg>"; 
                
            }else{ 
                $smas_selling = $rowmas["MIN_SELLING"];
            }
        }
        
        if(($subtotal/$qty)<$smas_selling){
            
            $msg="Cannot Add. Price is Less than the Selling";
            $ResponseXML .= "<msg><![CDATA[".$msg."]]></msg>"; 
            // exit('Cannot Add. Price is minimum than Cost!!!!');
        }
        
        
        if($msg=='ok'){
        
            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()) {
                if ($row["QTYINHAND"] >= $qty) {
                     // Get REFNO and SDATE from s_purtrn
                     $sql_purtrn = "SELECT REFNO, SDATE FROM s_purtrn WHERE STK_NO='" . $_GET['itemcode'] . "' AND SOLD_QTY < REC_QTY AND TEMP_NO = 0 AND CANCEL='0' ORDER BY SDATE DESC LIMIT 1";
                     $result_purtrn = $conn->query($sql_purtrn);
                     $ar_no = '';
                     $ar_date = '';
                     if ($row_purtrn = $result_purtrn->fetch()) {
                         $ar_no = $row_purtrn['REFNO'];
                         $ar_date = $row_purtrn['SDATE'];
                     }
                     
                     $sql = "Insert into tmp_inv_data (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,ar_no,ar_date)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"] . "','" . $ar_no . "','" . $ar_date . "') ";
            // echo $sql;
                    $result = $conn->query($sql);
                    
                    // Update s_purtrn TEMP_NO when item is added to temporary invoice
                    $sql_update_purtrn = "UPDATE s_purtrn SET TEMP_NO = '" . $_GET['tmpno'] . "' WHERE STK_NO = '" . $_GET['itemcode'] . "' AND TEMP_NO = 0 LIMIT 1";
                    $conn->query($sql_update_purtrn);
                }else{
                    if($rowmas['CAT'] =='None Stock Item'){
                         // Get REFNO and SDATE from s_purtrn
                         $sql_purtrn = "SELECT REFNO, SDATE FROM s_purtrn WHERE STK_NO='" . $_GET['itemcode'] . "' AND SOLD_QTY < REC_QTY AND TEMP_NO = 0 AND CANCEL='0' ORDER BY SDATE DESC LIMIT 1";
                         $result_purtrn = $conn->query($sql_purtrn);
                         $ar_no = '';
                         $ar_date = '';
                         if ($row_purtrn = $result_purtrn->fetch()) {
                             $ar_no = $row_purtrn['REFNO'];
                             $ar_date = $row_purtrn['SDATE'];
                         }
                         
                         $sql = "Insert into tmp_inv_data (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,ar_no,ar_date)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"] . "','" . $ar_no . "','" . $ar_date . "') ";
                        $result = $conn->query($sql);
                        
                        // Update s_purtrn TEMP_NO when none stock item is added to temporary invoice
                        $sql_update_purtrn = "UPDATE s_purtrn SET TEMP_NO = '" . $_GET['tmpno'] . "' WHERE STK_NO = '" . $_GET['itemcode'] . "' AND TEMP_NO = 0 LIMIT 1";
                        $conn->query($sql_update_purtrn);
                    }else{
                        $msg="Under Stock In Your Department!!!!";
                        // exit('Under Stock In Your Department!!!!');
                    }
                     
                }
            }
            
        }
        
    }
    
    if($msg=='ok'){
    
        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 invno IS NULL ";
            $result = $conn->query($sql);
            if ($row = $result->fetch()) {
                 
                     $sql = "Insert into tmp_inv_data (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'] . "', '". $row['STK_NO'] ."','" . $_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 tmp_inv_data where id='" . $_GET['id'] . "'";
            //$result = $conn->query($sql);
            
            // Get item code before deleting to reset TEMP_NO
            $sql_get_item = "SELECT str_code FROM tmp_inv_data WHERE id='" . $_GET['id'] . "'";
            $result_get_item = $conn->query($sql_get_item);
            if ($row_item = $result_get_item->fetch()) {
                $item_code = $row_item['str_code'];
                
                // Delete from tmp_inv_data
                $sql = "delete from tmp_inv_data where id='" . $_GET['id'] . "'";
                $result = $conn->query($sql);
                
                // Reset TEMP_NO in s_purtrn back to 0
                $sql_reset_purtrn = "UPDATE s_purtrn SET TEMP_NO = 0 WHERE STK_NO = '" . $item_code . "' AND TEMP_NO = '" . $_GET['tmpno'] . "' LIMIT 1";
                $conn->query($sql_reset_purtrn);
            }
        }
        
        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 tmp_inv_data 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  style='width: 5%;'>Item Code</th>
    <th  style='width: 1%;'>&nbsp;</th>
    <th  style='width: 25%;'>Description</th>
    <th  style='width: 5%;'>Serial No</th>
    <th  style='width: 8%;'>Price</th>
    <th  style='width: 5%;'>Qty</th>
    <th style='width: 5%;'>Dis1 (%)</th>
    <th style='width: 5%;'>Dis2 (%)</th>
    <th style='width: 10%;'>Unit Total</th>
    <th  style='width: 1%;'>#</th>
    <th  style='width: 1%;'></th>
                
                
    </tr>";

    $i = 1;
    $mtot = 0;
    $mtot2 = 0;
    $mtot1 = 0;
    $sql = "Select * from tmp_inv_data 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'] . "'";
     
        $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>
    
                
      
    </tr>";

     
    
    $sql = "Select * from tmp_inv_data 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 .= "<msg><![CDATA[".$msg."]]></msg>"; 
    $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();

    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 INVC,INVCM,SPINV1 from invpara where flag='".$COMPANY."'"; 
        $result = $conn->query($sql);
        $row = $result->fetch();
        
        
        // $sql = "select SPINV2,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["SPINV1"]);
        $lenth=strlen($tmpinvno);
        
        $invno=$row["INVC"].$row["INVCM"].substr($tmpinvno, $lenth-6);
        // }else{
        //     $COMPANY=$row['flag1'];
        //     $sql2 = "select SPINV2,flag1 from invpara where flag='".$COMPANY."'"; 
        //     $result2 = $conn->query($sql2);
        //     $row2 = $result2->fetch();
            
        //     $tmpinvno = "000000" .$row2["SPINV2"];
        //     $lenth = strlen($tmpinvno);
        //     $invno = trim("".$row['flag1']."/INV/".$row["SPINV2"]."/"). substr($tmpinvno, $lenth - 7);
        // }
         
     
    // }else{
        
    //     $sql = "select SPINV,SPINV3,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["SPINV"];
    //         $lenth = strlen($tmpinvno);
    //         $invno = trim("".$COMPANY."/INV/".$row["SPINV3"]."/") . substr($tmpinvno, $lenth - 7);
    //     }else{
    //         $COMPANY=$row['flag1'];
            
    //         $sql2 = "select SPINV,flag1 from invpara where flag='".$COMPANY."'"; 
    //         $result2 = $conn->query($sql2);
    //         $row2 = $result2->fetch();
            
    //         $tmpinvno = "000000" .$row2["SPINV"];
    //         $lenth = strlen($tmpinvno);
    //         $invno = trim("".$COMPANY."/INV/".$row["SPINV3"]."/") . substr($tmpinvno, $lenth - 7);
    //     }
        
         
      
    // }
    
    
    
    
    $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 {
        
        // line 1228 $invnoo eka $invno karanna ethakota hari
        // $invno=$_GET["invno"];

        if ($_GET["paymethod"]=="CA"){
            $sql = "select * from invpara where cash_update >= '".$_GET["invdate"]."'";
            $result = $conn->query($sql);
            $rowcount = $result->fetch();
            if($rowcount>0){
                exit("Cash Book already updated! Cannot Save!");
            }
            
            $sql = "SELECT * from cash_book_summery where CANCELL='0' and trn_date >='".$_GET["invdate"]."'";
            $result = $conn->query($sql);
            if ($row = $result->fetch()) {
                exit("Cash Book Updated.Can't Save...!!!");
            }
        }
        
        
        
        $insuf_qty = "";
        $sql = "select * from tmp_inv_data 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 tmp_inv_data 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"]);
     $vat = "";
        
    
    $sql = "select SPINV,vatrate,VATTYPE from invpara where flag='".$_SESSION['company']."'"; 
    $result = $conn->query($sql);
    $row = $result->fetch();
    
    $companyvattype=$row['VATTYPE'];

     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 1');
        }
    }


    $sqltmp1 = "select sum(cur_subtot) as cur_subtot from tmp_inv_data 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"];
        }
    }

    $sql_brtrn = "select * from br_trn where Rep='" . trim($_GET["salesrep"]) . "' and brand='" . trim($InvClass) . "' and cus_code='" . trim($_GET["customercode"]) . "'";
    $result_brtrn = $conn->query($sql_brtrn);
    $row_brtrn = $result_brtrn->fetch();
    $cuscat = trim($row_brtrn["CAT"]);

    // $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['paymethod'] == "CA") {
        $sql = "select INVC,INVCM,SPINV1,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["SPINV1"]);
        $lenth=strlen($tmpinvno);
        
        $invno=$row["INVC"].$row["INVCM"].substr($tmpinvno, $lenth-6);
        
        $sql = "update invpara set SPINV1 = SPINV1 +1 where flag='".$COMPANY."'"; 
        $res_inv = $conn->query($sql);
        
        // }else{
        //     $COMPANY=$row['flag1'];
            
        //     $sql2 = "select SPINV2,vatrate,flag1 from invpara where flag='".$COMPANY."'"; 
        //     $result2 = $conn->query($sql2);
        //     $row2 = $result2->fetch();
            
        //     $tmpinvno = "000000" .$row2["SPINV2"];
        //     $lenth = strlen($tmpinvno);
        //     $invno = trim("".$COMPANY."/INV/".$row["SPINV2"]."/") . substr($tmpinvno, $lenth - 7);
            
        //     $sql = "update invpara set SPINV2 = SPINV2 +1 where flag='".$COMPANY."'"; 
        //     $res_inv = $conn->query($sql);
            
            
        // }
          
     
    // }else{
    //     $sql = "select SPINV,SPINV3,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["SPINV"];
    //         $lenth = strlen($tmpinvno);
    //         $invno = trim("".$COMPANY."/INV/".$row["SPINV3"]."/") . substr($tmpinvno, $lenth - 7);
            
    //         $sql = "update invpara set SPINV = SPINV +1 where flag='".$COMPANY."'"; 
    //         $res_inv = $conn->query($sql);
            
    //     }else{
    //         $COMPANY=$row['flag1'];
            
    //         $sql2 = "select SPINV,SPINV3,vatrate,flag1 from invpara where flag='".$COMPANY."'"; 
    //         $result2 = $conn->query($sql2);
    //         $row2 = $result2->fetch();
            
    //         $tmpinvno = "000000" .$row2["SPINV"];
    //         $lenth = strlen($tmpinvno);
    //         $invno = trim("".$COMPANY."/INV/".$row["SPINV3"]."/") . substr($tmpinvno, $lenth - 7);
            
    //         $sql = "update invpara set SPINV = SPINV +1 where flag='".$COMPANY."'"; 
    //         $res_inv = $conn->query($sql);
            
            
    //     }
      
    // }
    
    

    $sqlisalma_q = "select REF_NO from s_salma 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_salma 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 tmp_inv_data 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_invo  (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,company) 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','".$COMPANY."')";
            $result_invo = $conn->query($sql_invo);
        
            $act_selling=$rowtmp["actual_selling"]-($rowtmp["actual_selling"]*$rowtmp["cur_discount"]/100);
            
            if($rowmas['CAT'] =='Tmp Stock Item'){
                $sqls_trn = "Insert into s_trn (STK_NO, SDATE, REFNO, QTY, LEDINDI, DEPARTMENT, Dev, seri_no, SAL_EX, ACTIVE, DONO,sdate1,cost,SERIALNO,selling,company,cus_code,arn_no,arn_date) values
                ('" . trim($rowtmp["str_code"]) . "','" . $_GET["invdate"] . "','" . trim($invno) . "', '" . $rowtmp["cur_qty"] . "', 'GRN', '" . trim($_GET["department"]) . "', '" . $_SESSION['dev'] . "', '" . $rowtmp["SERIALNO"] . "', '', '1', 'INV','" . $_GET["invdate"] . "','" . $rowmas["COST"] . "', '" . $rowtmp["serialno"] . "','" . $act_selling . "','".$COMPANY."','" . trim($_GET["customercode"]) . "','" . $rowtmp["ar_no"] . "','" . $rowtmp["ar_date"] . "')";
                $results_trn = $conn->query($sqls_trn);
                
                // Update SOLD_QTY in s_purtrn
                if (!empty($rowtmp["ar_no"])) {
                    $sql_update_sold = "UPDATE s_purtrn SET SOLD_QTY = SOLD_QTY + " . $rowtmp["cur_qty"] . " WHERE REFNO = '" . $rowtmp["ar_no"] . "' AND STK_NO = '" . trim($rowtmp["str_code"]) . "'";
                    $conn->query($sql_update_sold);
                }
                
                $sqls_mas = "update s_mas set QTYINHAND= QTYINHAND+" . $rowtmp["cur_qty"] . " where STK_NO='" . trim($rowtmp["str_code"]) . "'";
                $results_mas = $conn->query($sqls_mas);
                
                $sqls_submas = "update s_submas set QTYINHAND=QTYINHAND+ " . $rowtmp["cur_qty"] . " where STK_NO= '" . trim($rowtmp["str_code"]) . "' and STO_CODE= '" . trim($_GET["department"]) . "'";
                $results_submas = $conn->query($sqls_submas);
            }else{
                $sqls_trn = "Insert into s_trn (STK_NO, SDATE, REFNO, QTY, LEDINDI, DEPARTMENT, Dev, seri_no, SAL_EX, ACTIVE, DONO,sdate1,cost,SERIALNO,selling,company,cus_code,arn_no,arn_date) values
                ('" . trim($rowtmp["str_code"]) . "','" . $_GET["invdate"] . "','" . trim($invno) . "', '" . $rowtmp["cur_qty"] . "', 'INV', '" . trim($_GET["department"]) . "', '" . $_SESSION['dev'] . "', '" . $rowtmp["SERIALNO"] . "', '', '1', 'INV','" . $_GET["invdate"] . "','" . $rowmas["COST"] . "', '" . $rowtmp["serialno"] . "','" . $act_selling . "','".$COMPANY."','" . trim($_GET["customercode"]) . "','" . $rowtmp["ar_no"] . "','" . $rowtmp["ar_date"] . "')";
                $results_trn = $conn->query($sqls_trn);
                
                // Update SOLD_QTY in s_purtrn
                if (!empty($rowtmp["ar_no"])) {
                    $sql_update_sold = "UPDATE s_purtrn SET SOLD_QTY = SOLD_QTY + " . $rowtmp["cur_qty"] . " WHERE REFNO = '" . $rowtmp["ar_no"] . "' AND STK_NO = '" . trim($rowtmp["str_code"]) . "'";
                    $conn->query($sql_update_sold);
                }
                
                $sqls_mas = "update s_mas set QTYINHAND= QTYINHAND-" . $rowtmp["cur_qty"] . " where STK_NO='" . trim($rowtmp["str_code"]) . "'";
                $results_mas = $conn->query($sqls_mas);
                
                $sqls_submas = "update s_submas set QTYINHAND=QTYINHAND- " . $rowtmp["cur_qty"] . " where STK_NO= '" . trim($rowtmp["str_code"]) . "' and STO_CODE= '" . trim($_GET["department"]) . "'";
                $results_submas = $conn->query($sqls_submas);
            }
        }
        
        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();
            
            $d1 = $rowtmp["dis_per"];
            $d2 = $rowtmp["dis_per1"];
            $d3 = 0;
        
            
            if ($d1 == "") {
                $d1 = 0;
            }
            if ($d2 == "") {
                $d2 = 0;
            }
            if ($d3 == "") {
                $d3 = 0;
            }
     
            $sql_invo = "Insert into s_invo  (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,company) 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','".$COMPANY."')";
             $result_invo = $conn->query($sql_invo);
        
            $act_selling=$rowtmp["actual_selling"]-($rowtmp["actual_selling"]*$rowtmp["dis_per"]/100);
            
           
            $sqls_trn = "Insert into s_trn (STK_NO,JOBNO, SDATE, REFNO, QTY, LEDINDI, DEPARTMENT, Dev, seri_no, SAL_EX, ACTIVE, DONO,sdate1,cost,SERIALNO,selling,TYPE,company,cus_code) values
            ('" . trim($rowtmp["str_code"]) . "','" . trim($rowtmp["jobno"]) . "','" . $_GET["invdate"] . "','" . trim($invno) . "', " . $rowtmp["cur_qty"] . ", 'INV', '" . trim($_GET["department"]) . "', '" . $_SESSION['dev'] . "', '', '', '1', 'INV','" . $_GET["invdate"] . "','" . $rowtmp["cost"] . "', '" . $rowtmp["serialno"] . "','" . $act_selling . "','DAGINV','".$COMPANY."','" . trim($_GET["customercode"]) . "')";
            $results_trn = $conn->query($sqls_trn);
            
            $sqls_mas = "update s_mas set QTYINHAND= QTYINHAND-" . $rowtmp["cur_qty"] . " where STK_NO='" . trim($rowtmp["str_code"]) . "'";
            $results_mas = $conn->query($sqls_mas);
            
            $sqls_submas = "update s_submas set QTYINHAND=QTYINHAND- " . $rowtmp["cur_qty"] . " where STK_NO= '" . trim($rowtmp["str_code"]) . "' and STO_CODE= '" . trim($_GET["department"]) . "'";
            $results_submas = $conn->query($sqls_submas);
            
            $sqls_submas = "update dag_item set invno='".$invno."',flag='7',inv_date='" . $_GET['invdate'] . "',amount1 = '" . $rowtmp["actual_selling"] . "',total1 = '" . $rowtmp["cur_subtot"] . "',dis1 = '" . $rowtmp["dis_per"] . "' where jobno = '" . $rowtmp["jobno"] . "' and serialno = '" . $rowtmp["serialno"] . "'";  
            $results_submas = $conn->query($sqls_submas);
           
        }
        
    }
    
 

    $sqlrep = "select * from s_salrep where REPCODE = '" . trim($_GET["salesrep"]) . "'";
    $resultrep = $conn->query($sqlrep);
    if ($rowrep = $resultrep->fetch()) {
        $maindepart = $rowrep['RGROUP1'];
    } else {
        $maindepart = "";
    }

    $sql = "Insert into s_salma  (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,use_name,dele_no) 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["pay_type"] . "','" . $_GET["type2"] . "','" . $_GET["labour"] . "','" . $_GET["inquiry"] . "','" . $_SESSION["CURRENT_USER"] . "','" . $_GET["dano"] . "')";
    $resultsalma = $conn->query($sql);
    
    $sql = "Insert into s_salesmain  (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,use_name,dele_no) 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["pay_type"] . "','" . $_GET["type2"] . "','" . $_GET["labour"] . "','" . $_GET["inquiry"] . "','" . $_SESSION["CURRENT_USER"] . "','" . $_GET["dano"] . "')";
    $resultsalesmain = $conn->query($sql);

    $sqlpara = "update vendor set temp_limit= '0'  where CODE='" . trim($_GET["customercode"]) . "'";
    $resultpara = $conn->query($sqlpara);

    $sqls_submas = "Insert into s_led(REF_NO, SDATE, C_CODE, AMOUNT, FLAG, DEPARTMENT,company) values
    ('" . trim($invno) . "', '" . $_GET["invdate"] . "', '" . trim($_GET["customercode"]) . "', " . $invtot . ", 'INV', '" . $_GET["department"] . "','".$COMPANY."')";
    $results_submas = $conn->query($sqls_submas);

    $sqlbr_trn = "update br_trn set tmplmt= '0'   where cus_code='" . trim($_GET["customercode"]) . "' and brand='" . trim($InvClass) . "' and Rep='" . trim($_GET["salesrep"]) . "'";
    $resultbr_trn = $conn->query($sqlbr_trn);

    $sqlbr_trn = "update s_cusordmas set INVNO= '" . $invno . "' where  REF_NO='" . $_GET["ordno"] . "'";
    $resultbr_trn = $conn->query($sqlbr_trn);
    
    
   function ac_year($date) { 
         $month1 = date("m", strtotime($date));
         $month1_y = date("Y", strtotime($date));
        
         if ($month1<=3) {
             $ac_year = $month1_y -1;
         } else {
             $ac_year = $month1_y;
         } 
         return $ac_year; 
    }
    
    $ayear = ac_year($_GET["invdate"]); 
    
    
    $tax=$invtot/(100+$mvatrate)*$mvatrate;
    
    
    
     if($companyvattype=="0"){
        $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
        ('" . $invno . "', '" . $_GET["invdate"] . "', 'MSAL001' ,'" . $customername . "', '" . $invtot . "', 'INV', 'CRE', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
        $result_ledger = $conn->query($sql_ledger);  
            
        if ($_GET["paymethod"] !="CA"){
            $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
            ('" . $invno . "', '" . $_GET["invdate"] . "', 'MARE001' ,'" . $customername . "', '" . $invtot . "', 'INV', 'DEB', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
            $result_ledger = $conn->query($sql_ledger);   
        }
             
        
    }else{
        $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
        ('" . $invno . "', '" . $_GET["invdate"] . "', 'MVAT001' ,'" . $customername . "', '" . $tax . "', 'INV', 'CRE', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
        $result_ledger = $conn->query($sql_ledger);  
        
        $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
        ('" . $invno . "', '" . $_GET["invdate"] . "', 'MVSA001' ,'" . $customername . "', '" . ($invtot-$tax) . "', 'INV', 'CRE', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
        $result_ledger = $conn->query($sql_ledger);  
        
        if ($_GET["paymethod"] !="CA"){
           $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
            ('" . $invno . "', '" . $_GET["invdate"] . "', 'MARE001' ,'" . $customername . "', '" . $invtot . "', 'INV', 'DEB', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
            $result_ledger = $conn->query($sql_ledger);   
        }
           
    }
    
    if($vat=="0"){
        if ($_GET["paymethod"] !="CA"){
            $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
            ('" . $invno . "', '" . $_GET["invdate"] . "', 'MARE001' ,'" . $customername . "', '" . $invtot . "', 'INV', 'DEB', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
            $result_ledger = $conn->query($sql_ledger);   
        }
             $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
            ('" . $invno . "', '" . $_GET["invdate"] . "', 'MSAL001' ,'" . $customername . "', '" . $invtot . "', 'INV', 'CRE', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
            $result_ledger = $conn->query($sql_ledger);  
        
    }else{
        if ($_GET["paymethod"] !="CA"){
          $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
            ('" . $invno . "', '" . $_GET["invdate"] . "', 'MARE001' ,'" . $customername . "', '" . $invtot . "', 'INV', 'DEB', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
            $result_ledger = $conn->query($sql_ledger);   
        }
         $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
        ('" . $invno . "', '" . $_GET["invdate"] . "', 'MVAT001' ,'" . $customername . "', '" . $tax . "', 'INV', 'CRE', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
        $result_ledger = $conn->query($sql_ledger);  
        
        $sql_ledger = "Insert into a_ledger(L_REFNO, L_DATE, L_CODE, L_LMEM,L_AMOUNT, L_FLAG, L_FLAG1, ACYEAR, COMPANY, C_CODE) Values 
        ('" . $invno . "', '" . $_GET["invdate"] . "', 'MVSA001' ,'" . $customername . "', '" . ($invtot-$tax) . "', 'INV', 'CRE', '".$ayear."', '" . $COMPANY . "', '".$_GET["customercode"]."')";
        $result_ledger = $conn->query($sql_ledger);     
    }
    
    if($_GET["inquiry"]!=""){
        $sqlbr_trn = "update s_inquiry set STATUS= '1' where  REFNO='" . $_GET["inquiry"] . "'";
        $resultbr_trn = $conn->query($sqlbr_trn);
    }
    
    /////////// if cash invoice ////////////////////////
			
			if ($_GET["paymethod"]=="CA"){
				
				$sql = "select INV_RECNO from invpara where flag='".$COMPANY."'"; 
        		 $result = $conn->query($sql);
                $row = $result->fetch();

        		$tmprecno = "000000" . $row["INV_RECNO"];
        		$lenth = strlen($tmprecno); 
        		$recno = trim("".$COMPANY."RN/CR/ ") . substr($tmprecno, $lenth - 5);
        		
        		$recno=$invno;

    
				$sql = "insert into s_crec(CA_REFNO, CA_DATE,INVNO, CA_CODE, CA_CASSH, CA_AMOUNT, overpay, FLAG, pay_type, CA_SALESEX, CANCELL, tmp_no, DEPARTMENT, cus_ref, AC_REFNO, TTDATE, DEV,company) values
	            ('" . $recno . "', '" . $_GET["invdate"] . "', '" . $invno . "', '" . trim($_GET["customercode"]) . "', " . $invtot . ", " . $invtot . ", 0, 'REC', 'Cash', '" . $_GET["salesrep"] . "', '0', '" . $_GET["tmpno"] . "', 'O', '0', '', '',  '" . $_SESSION['dev'] . "','".$COMPANY."' )";
              	$result = $conn->query($sql); 
				
				$sql1 = "insert into s_sttr(ST_REFNO, ST_DATE, ST_INVONO, ST_PAID, ST_CHNO, st_chdate, ST_FLAG, st_days, ap_days, st_chbank, cus_code, DEV, del_days, deliin_days, deliin_amo, deliin_lock, department,company,PAY_TYPE) values
	            ('" . $recno . "', '" . $_GET["invdate"] . "', '" . $invno . "', " . $invtot . ", '', '" . $_GET["invdate"] . "', 'CAS', '', '', '', '" . trim($_GET["customercode"]) . "', '" . $_SESSION['dev'] . "', 0, 0, 0, '0', 'O','".$COMPANY."','".$paytype."')";
                $result = $conn->query($sql1);
				
				$sql2 = "update s_salma set TOTPAY=TOTPAY + " . $invtot . " where REF_NO = '" . $invno . "'";
                $result = $conn->query($sql2);
				
				$sql2 = "update s_salma set CASH=CASH + " . $invtot . " where REF_NO = '" . $invno . "'";
                $result = $conn->query($sql2);
                
                $sql2 = "update s_salesmain set TOTPAY=TOTPAY + " . $invtot . " where REF_NO = '" . $invno . "'";
                $result = $conn->query($sql2);
				
				$sql2 = "update s_salesmain set CASH=CASH + " . $invtot . " where REF_NO = '" . $invno . "'";
                $result = $conn->query($sql2);
				
				// $sql2 = "update invpara set INV_RECNO=INV_RECNO + 1  where flag='".$COMPANY."'"; 
    //         	$result = $conn->query($sql2);
                                
                //-------------cash-gl                
                $fulltot = $invtot;
                
                

                $l_lmem = "Cash recieved from " . trim($customername).'-'.$invno;
                $ldate = $_GET["invdate"]; 
                
                 
                $sql = "insert into a_ledger(l_refno, l_date, l_code, l_amount, l_flag, l_flag1, l_lmem, l_flag2, l_flag3, l_yearfl, comcode, chno, recdate, ACYEAR,company) values 
                    ('" . trim($invno) . "', '" . $ldate . "', '12101', " . $fulltot . ", 'REC', 'CRE', '" . $l_lmem . "', '0', 'R', 0, '" . $COMPANY . "', '', '0', " . date("Y") . ",'".$COMPANY."')";
                $result = $conn->query($sql);    
                
                $sql = "insert into a_ledger(l_refno, l_date, l_code, l_amount, l_flag, l_flag1, l_lmem, l_flag2, l_flag3, l_yearfl, comcode, chno, recdate, ACYEAR,company) values 
                    ('" . trim($invno) . "', '" . $ldate . "', '12501', " . $fulltot . ", 'REC', 'DEB', '" . $l_lmem . "', '0', 'R', 0, '" . $COMPANY . "', '', '0', " . date("Y") . ",'".$COMPANY."')";
                $result = $conn->query($sql); 
                
                
		//-------------cash-gl                                
				
			}
			
			$paytype=$_GET["pay_type"];
        
            if ($paytype !="CREDIT"){
                            
                    $sql = "select INV_RECNO from invpara where flag='".$COMPANY."'"; 
                     $result = $conn->query($sql);
                    $row = $result->fetch();
            
                    $tmprecno = "00000" . $row["INV_RECNO"];
                    $lenth = strlen($tmprecno); 
                    $recno = trim("".$COMPANY."/PR/ ") . substr($tmprecno, $lenth - 5);
                    
                    $recno=$invno;
            
                     
                    $ttdate="";
                    $cash=0;
            
                    if($paytype == "CASH"){
                        $paytypeold='CAS';
                        $st_chbank='';
                        $ST_CHNO='CASH';
                        $st_chdate=$_GET["invdate"];
                        $note='';
                        $cash=$invtot;
                 
                    }else if($paytype == "CARD"){
                        $paytypeold='CARD';
                        $st_chbank=$_GET["card_type"];
                        $ST_CHNO=$_GET["card_number"];
                        $st_chdate=$_GET["card_date"];
                        $note='';
            
                    }else if($paytype == "CHEQUE"){
                        $paytypeold='CHK'; 
                        $ST_CHNO=$_GET["cheque_no"];
                        $st_chbank=$_GET["cheque_bank_name"];
                        $st_chdate=$_GET["cheque_date"];
                        $note='';
            
                    }else if($paytype == "GIFT CARD"){
                        $paytypeold='CAS';
                        $ST_CHNO=$_GET["gift_card_no"];
                        $st_chbank='';
                        $st_chdate=$_GET["invdate"];
                        $note='';
            
                    }else if($paytype == "BANK DEPOSIT"){
                        $paytypeold='Cash TT';
                        $ST_CHNO='';
                        $st_chbank=$_GET["bank_deposit_bank_name"];
                        $st_chdate=$_GET["bank_deposit_date"];
                        $note=$_GET["bank_deposit_note"];
                        $ttdate=$_GET["bank_deposit_date"];
            
                    }else if($paytype == "ONLINE PAYMENT"){ 
                        $paytypeold='CAS';
                        $ST_CHNO='';
                        $st_chbank=$_GET["online_pay_bank_name"];
                        $st_chdate=$_GET["invdate"];
                        $note=$_GET["online_pay_note"];
                    }
                    
                    $sql = "insert into s_crec(CA_REFNO, CA_DATE,INVNO, CA_CODE, CA_CASSH, CA_AMOUNT, overpay, FLAG, pay_type, CA_SALESEX, CANCELL, tmp_no, DEPARTMENT, cus_ref, AC_REFNO, TTDATE, DEV,company) values
                    ('" . $recno . "', '" . $_GET["invdate"] . "', '" . $invno . "', '" . trim($_GET["customercode"]) . "', " . $invtot . ", " . $invtot . ", 0, 'REC', '".$paytype."', '" . $_GET["salesrep"] . "', '0', '" . $_GET["tmpno"] . "', 'O', '0', '".$ttdate."', '',  '" . $_SESSION['dev'] . "','".$COMPANY."' )";
                    $result = $conn->query($sql); 
            
            
                    $sql1 = "insert into s_sttr(ST_REFNO, ST_DATE, ST_INVONO, ST_PAID, ST_CHNO, st_chdate, ST_FLAG, st_days, ap_days, st_chbank, cus_code, DEV, del_days, deliin_days, deliin_amo, deliin_lock, department,company,PAY_TYPE,NOTE) values
            ('" . $recno . "', '" . $_GET["invdate"] . "', '" . $invno . "', " . $invtot . ", '".$ST_CHNO."', '" . $st_chdate . "', '".$paytypeold."', '', '', '".$st_chbank."', '" . trim($_GET["customercode"]) . "', '" . $_SESSION['dev'] . "', 0, 0, 0, '0', 'O','".$COMPANY."','".$paytype."','".$note."')";
                    $result = $conn->query($sql1);
             
                    $sql2 = "update s_salma set TOTPAY=TOTPAY + " . $invtot . " where REF_NO = '" . $invno . "'";
                    $result = $conn->query($sql2);
                    
                    $sql2 = "update s_salma set CASH=CASH + " . $cash . " where REF_NO = '" . $invno . "'";
                    $result = $conn->query($sql2);
                    
                    $sql2 = "update s_salesmain set TOTPAY=TOTPAY + " . $invtot . " where REF_NO = '" . $invno . "'";
                    $result = $conn->query($sql2);
                    
                    $sql2 = "update s_salesmain set CASH=CASH + " . $cash . " where REF_NO = '" . $invno . "'";
                    $result = $conn->query($sql2);
                            
                    // $sql2 = "update invpara set INV_RECNO=INV_RECNO + 1  where flag='".$COMPANY."'"; 
                    // $result = $conn->query($sql2);
                                    
                    //-------------cash-gl    
            
                    $fulltot = $invtot; 
                    $l_lmem = "$paytype - Received from " . trim($customername).'-'.$invno;
                     
                     $sql = "insert into a_ledger(l_refno, l_date, l_code, l_amount, l_flag, l_flag1, l_lmem, l_flag2, l_flag3, l_yearfl, comcode, chno, recdate, l_year) values 
                        ('" . trim($recno) . "', '" . $st_chdate . "', '120100', " . $fulltot . ", 'REC', 'CRE', '" . $l_lmem . "', '0', 'R', 0, '" . $COMPANY . "', '', '0', " . date("Y") . ")";
                    $result = $conn1->query($sql);    
                    
                    $sql = "insert into a_ledger(l_refno, l_date, l_code, l_amount, l_flag, l_flag1, l_lmem, l_flag2, l_flag3, l_yearfl, comcode, chno, recdate, l_year) values 
                        ('" . trim($recno) . "', '" . $st_chdate . "', '220504', " . $fulltot . ", 'REC', 'DEB', '" . $l_lmem . "', '0', 'R', 0, '" . $COMPANY . "', '', '0', " . date("Y") . ")";
                    $result = $conn1->query($sql); 
                                         
                            
            }
    
    $sql_reset = "UPDATE s_purtrn SET TEMP_NO = 0 WHERE STK_NO IN (SELECT str_code FROM tmp_inv_data WHERE user = '" . $_SESSION["CURRENT_USER"] . "')";
    $conn->query($sql_reset);
    

    
    $sql = "delete from tmp_inv_data where user= '" . $_SESSION["CURRENT_USER"] . "' ";
    $result = $conn->query($sql);
			

    $sqlbrand = "insert into entry_log(refno, username, docname, trnType, stime, sdate,COMPANY) values 
    ('" . trim($invno) . "', '" . $_SESSION["CURRENT_USER"] . "', 'Invoice', 'Save', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "','".$COMPANY."')";
    $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_salma 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);
        
        $sql = "update s_salesmain 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_salma set cre_pe= '" . $_GET["credper"] . "' where  REF_NO='" . $_GET["invno"] . "'";
        $result = $conn->query($sql);
        
         $sql = "update s_salesmain 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,COMPANY) values 
        ('" . $_GET["invno"] . "', '" . $_SESSION["CURRENT_USER"] . "', 'Invoice', 'CredDays Update', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "','".$_SESSION['company']."')";
        $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 - 5);
        
        $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,COMPANY) values 
        ('" . $refno . "', '" . $_SESSION["CURRENT_USER"] . "', 'Customer', 'Save', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "','".$_SESSION['company']."')";
        $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  tmp_inv_data 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 ($_POST["Command"] == "search_item_search") {

   $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    
     $ResponseXML .= "<sales_table><![CDATA[<table class=\"table table-bordered\"  style=\"width:100%\"> 
     <tr>
                        <th style='width: 7%;height:0px;'>&nbsp;</th>
                        <th style='width: 20%;'>&nbsp;</th>
                        <th style='width: 10%;'>&nbsp;</th>
                        <th style='width: 10%;'>&nbsp;</th>
                        <th style='width: 5%;height:0px;'>&nbsp;</th>
                        <th style='width: 5%;height:0px;' >&nbsp;</th>
                        <th style='width: 5%;height:0px;'>&nbsp;</th>
                        <th style='width: 10%;height:0px;'>&nbsp;</th>
                        <th style='width: 10%;height:0px;'>&nbsp;</th>
                        </tr>
                        ";

 

    $sql = "SELECT * FROM s_purtrn WHERE SOLD_QTY < REC_QTY AND TEMP_NO = 0  ";  
    
    if ($_POST['s_refno'] != "") {
        $sql .= " and STK_NO like '" . $_POST['s_refno'] . "%'";
    }
    if ($_POST['s_desc'] != "") {
        $sql .= " and DESCRIPT like '%" . $_POST['s_desc'] . "%'";
    }
    if ($_POST['s_brand'] != "") {
        $sql .= " and brand like '%" . $_POST['s_brand'] . "%'";
    }
    if ($_POST['s_department'] != "") {
        $sql .= " AND DEPARTMENT LIKE '%" . $_POST['s_department'] . "%'";
    }
     if ($_POST['s_cash'] != "") {
        $sql .= " and COST like '%" . $_POST['s_cash'] . "%'";
    }
    if ($_POST['s_credit'] != "") {
        	$sql .= " and SELLING ='" . $_POST['s_credit'] . "'";
    }
    
    if ($_POST['s_qty'] != "") {
        $sql .= " and REC_QTY like '%" . $_POST['s_qty'] . "%'";
    }
    if ($_POST['s_sdate'] != "") {
        $sql .= " AND PUR_DATE LIKE '%" . $_POST['s_sdate'] . "%'";
    }
    if ($_POST['s_pur_refno'] != "") {
        $sql .= " AND REF_NO LIKE '%" . $_POST['s_pur_refno'] . "%'";
    }
    
    $sql .=" order by QTYINHAND desc limit 50";
   
    foreach ($conn->query($sql) as $row) {
       
        $refno = $row['STK_NO']; 
       
               
        $text="";
        $color="";
        
        // Calculate available quantity (REC_QTY - SOLD_QTY)
        $available_qty = $row['REC_QTY'] - $row['SOLD_QTY'];
       
                $ResponseXML .= "<tr class='linehover'>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:center;'> " . $row['STK_NO'] . "</a></td>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:left;'>" . $row['DESCRIPT'] . "</a></td>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:left;'>" . $row['BRAND'] . "</a></td>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:left;'>" . $row['DEPARTMENT'] . "</a></td>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:right;'>" . $row['COST'] . "</a></td>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:right;'>" . $row['SELLING'] . "</a></td>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:right;'>" . $available_qty . "</a></td>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:center;'>" . $row['SDATE'] . "</a></td>";
        $ResponseXML .= "<td onclick=\"custno2('$refno','$custcode','$ar_refno','$ar_sdate');\" style='text-align:center;'>" . $row['REFNO'] . "</a></td>";
        $ResponseXML .= "</tr>";
    }

    $ResponseXML .= "   </table>]]></sales_table>"; 

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

if ($_POST["Command"] == "search_customer_search") {

   $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    
     $ResponseXML .= "<sales_table><![CDATA[<table class=\"table table-bordered\"  style=\"width:100%\"> ";

     $sql = "select * from vendor  where CANCELL='0' AND CAT IN ('B', 'C','DE','DI') ";  
    
     
    if ($_POST['c_refno'] != "") {
        $sql .= " and CODE like '" . $_POST['c_refno'] . "%'";
    }
    if ($_POST['c_name'] != "") {
        $sql .= " and NAME like '" . $_POST['c_name'] . "%'";
    }
    if ($_POST['c_add'] != "") {
        $sql .= " and ADD1 like '%" . $_POST['c_add'] . "%'";
    }
    if ($_POST['c_tel'] != "") {
        $sql .= " and TELE1 like '%" . $_POST['c_tel'] . "%'";
    }
    if ($_POST['c_subcus'] != "") {
        $sql .= " and c_code like '%" . $_POST['c_subcus'] . "%'";
    }
    
    $sql .=" order by NAME asc limit 50 ";
   
    foreach ($conn->query($sql) as $row) {
       
        $cuscode = $row['CODE']; 
               
        $text="";
        $color="";
       
        
        $ResponseXML .= "<tr >               
        <td onclick=\"custno3('$cuscode');\" style='text-align:left;width: 12%;'> " . $row['CODE'] . "</a></td>
        <td onclick=\"custno3('$cuscode');\" style='text-align:left;width: 30%;'>" . $row['NAME'] . "</a></td>
        <td onclick=\"custno3('$cuscode');\" style='text-align:left;width: 28%;'>" . $row['ADD1'] . "</a></td>
        <td onclick=\"custno3('$cuscode');\" style='text-align:left;width: 20%;'>" . $row['TELE1'] . "</a></td>
        <td onclick=\"custno3('$cuscode');\" style='text-align:left;width: 10%;'>" . $row['c_code'] . "</a></td>
        </tr>";
                 
    }

    $ResponseXML .= "   </table>]]></sales_table>"; 

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

if ($_POST["Command"] == "search_sales_inv_search") {

   $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    
     $ResponseXML .= "<sales_table><![CDATA[<table class=\"table table-bordered\"  style=\"width:100%\"> ";

    $sql = "select * from s_salma where  TRN_TYPE='INV' AND DEV='" . $_SESSION["dev"] . "' and  company='".$_SESSION["company"]."' ";  
    
     
    if ($_POST['i_refno'] != "") {
        $sql .= " and REF_NO like '%" . $_POST['i_refno'] . "%'";
    }
    if ($_POST['i_date'] != "") {
        $sql .= " and SDATE like '%" . $_POST['i_date'] . "%'";
    }
    if ($_POST['i_cus'] != "") {
        $sql .= " and CUS_NAME like '%" . $_POST['i_cus'] . "%'";
    }
    if ($_POST['i_po'] != "") {
        $sql .= " and ORD_NO like '%" . $_POST['i_po'] . "%'";
    }
    if ($_POST['i_jobno'] != "") {
        $sql .= " and dele_no like '%" . $_POST['i_jobno'] . "%'";
    }
    if ($_POST['i_vehicale'] != "") {
        $sql .= " and veheno like '%" . $_POST['i_vehicale'] . "%'";
    }
    if ($_POST['i_tele'] != "") {
        $sql .= " and TEL like '%" . $_POST['i_tele'] . "%'";
    }
    if ($_POST['i_value'] != "") {
        $sql .= " and GRAND_TOT like '%" . $_POST['i_value'] . "%'";
    } 
    
    $sql .=" order by id desc limit 50";
   
    foreach ($conn->query($sql) as $row) {
       
        $cuscode = $row['REF_NO']; 
               
        $text="";
        $color="";
       
        
        $ResponseXML .= "<tr >               
        <td onclick=\"custno4('$cuscode');\" style='text-align:center;width: 10%;'> " . $row['REF_NO'] . "</a></td>
        <td onclick=\"custno4('$cuscode');\" style='text-align:center;width: 10%;'>" . $row['SDATE'] . "</a></td> 
        <td onclick=\"custno4('$cuscode');\" style='text-align:left;width: 35%;'>" . $row['CUS_NAME'] . "</a></td>
        <td onclick=\"custno4('$cuscode');\" style='text-align:left;width: 8%;'>" . $row['ORD_NO'] . "</a></td>
        <td onclick=\"custno4('$cuscode');\" style='text-align:left;width: 8%;'>" . $row['dele_no'] . "</a></td>
        <td onclick=\"custno4('$cuscode');\" style='text-align:left;width: 8%;'>" . $row['veheno'] . "</a></td>
        <td onclick=\"custno4('$cuscode');\" style='text-align:left;width: 10%;'>" . $row['TEL'] . "</a></td> 
        <td onclick=\"custno4('$cuscode');\" style='text-align:right;width: 10%;'>" . $row['GRAND_TOT'] . "</a></td> 
        </tr>";
                 
    }

    $ResponseXML .= "   </table>]]></sales_table>"; 

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

