<?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'];

    $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 SPINV2 from invpara where flag='".$COMPANY."'";
        $result = $conn->query($sql);
        $row = $result->fetch();

        $tmpinvno = "000000" . $row["SPINV2"] ;
        $lenth = strlen($tmpinvno);
        //  . "/" . $_GET["salesrep"]
        $invno = trim("".$COMPANY."/INV/CB/") . substr($tmpinvno, $lenth - 6);

        $sql = "Select SPINV2 from tmpinvpara where flag='".$COMPANY."'";
        $result = $conn->query($sql);
        $row = $result->fetch();

        $tono = $row['SPINV2'];

        $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 from invpara where flag='".$COMPANY."'";
        $result = $conn->query($sql);
        $row = $result->fetch();

        $tmpinvno = "000000" . $row["SPINV"];
        $lenth = strlen($tmpinvno);
        $invno = trim("".$COMPANY."/INV/CRM/") . substr($tmpinvno, $lenth - 6);

        $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' and SCODE='" . $COMPANY . "' ";
        
         $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) {
                
                if($COMPANY == 'MT'){
                    if($row_sto["CODE"] != 01){
                         $ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> ";
                    }
                }else{
                      if($row_sto["CODE"] == 01){
                         $ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> ";
                    }
                }
               
                 
            }

            $ResponseXML .= "]]></select_dep>";
        }else{
            $_SESSION["department"]=$row_sto["CODE"];
            $ResponseXML .= "<select_dep><![CDATA[]]></select_dep>";
        }
        if ($_SESSION["CURRENT_REP"] != "") {
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' and REPCODE='".$_SESSION["CURRENT_REP"]."' order by REPCODE";
        }else{
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' order by REPCODE";
        }

        $result_rep = $conn->query($sql_rep);
        if ($row_rep = $result_rep->fetch()) {

            $ResponseXML .= "<select_rep><![CDATA[";
            foreach ($conn->query($sql_rep) as $row_rep) {
                $ResponseXML .= " <option value='" . $row_rep["REPCODE"] . "'>" . $row_rep["Name"] ."</option> ";

            }

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

        $sql_lab = "select * from s_labour where act='1' and cancel='0' and SCODE='" . $COMPANY . "' order by CODE";
        $result_lab = $conn->query($sql_lab);
        if ($row_lab = $result_lab->fetch()) {

            $ResponseXML .= "<select_lab><![CDATA[";
            foreach ($conn->query($sql_lab) as $row_lab) {
                $ResponseXML .= " <option value='" . $row_lab["CODE"] . "'>" . $row_lab["DESCRIPTION"] ."</option> ";

            }

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

    }else{
        $COMPANY=$row_para['flag1'];

        $sql_sto = "select * from s_stomas where act='1' and SCODE='" . $COMPANY . "' ";
        $result_sto = $conn->query($sql_sto);
        if ($row_sto = $result_sto->fetch()) {

            $_SESSION["department"]=$row_sto["CODE"];

            $ResponseXML .= "<select_dep><![CDATA[";
            foreach ($conn->query($sql_sto) as $row_sto) {
                $ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> ";

            }

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

        if ($_SESSION["CURRENT_REP"] != "") {
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' and REPCODE='".$_SESSION["CURRENT_REP"]."' order by REPCODE";
        }else{
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' order by REPCODE";
        }
        $result_rep = $conn->query($sql_rep);
        if ($row_rep = $result_rep->fetch()) {

            $ResponseXML .= "<select_rep><![CDATA[";
            foreach ($conn->query($sql_rep) as $row_rep) {
                $ResponseXML .= " <option value='" . $row_rep["REPCODE"] . "'>" . $row_rep["Name"] ."</option> ";

            }

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

        $sql_lab = "select * from s_labour where act='1' and cancel='0' and SCODE='" . $COMPANY . "' order by CODE";
        $result_lab = $conn->query($sql_lab);
        if ($row_lab = $result_lab->fetch()) {

            $ResponseXML .= "<select_lab><![CDATA[";
            foreach ($conn->query($sql_lab) as $row_lab) {
                $ResponseXML .= " <option value='" . $row_lab["CODE"] . "'>" . $row_lab["DESCRIPTION"] ."</option> ";

            }

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


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

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

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

    $COMPANY=$_SESSION['company'];
    if ($_GET['paymethod'] == "CA") {
        $sql = "select SPINV2,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/CB/") . 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("".$COMPANY."/INV/CB/") . substr($tmpinvno, $lenth - 6);
        }

    }else{

        $sql = "select SPINV,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/CRM/") . substr($tmpinvno, $lenth - 6);
        }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/CRM/") . substr($tmpinvno, $lenth - 6);
        }
    }


    $COMPANY=$_SESSION['company'];
    $sql_para = "select flag1 from invpara where flag='".$COMPANY."'";
    $result_para = $conn->query($sql_para);
    $row_para = $result_para->fetch();

    if($_GET['type2']=="NORMAL"){

        $sql_sto = "select * from s_stomas where act='1' and SCODE='" . $COMPANY . "' ";
        $result_sto = $conn->query($sql_sto);
        if ($row_sto = $result_sto->fetch()) {

            $_SESSION["department"]=$row_sto["CODE"];

            $ResponseXML .= "<select_dep><![CDATA[";
            foreach ($conn->query($sql_sto) as $row_sto) {
                $ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> ";

            }

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


        if ($_SESSION["CURRENT_REP"] != "") {
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' and REPCODE='".$_SESSION["CURRENT_REP"]."' order by REPCODE";
        }else{
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' order by REPCODE";
        }
        $result_rep = $conn->query($sql_rep);
        if ($row_rep = $result_rep->fetch()) {

            $ResponseXML .= "<select_rep><![CDATA[";
            foreach ($conn->query($sql_rep) as $row_rep) {
                $ResponseXML .= " <option value='" . $row_rep["REPCODE"] . "'>" . $row_rep["Name"] ."</option> ";

            }

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

        $sql_lab = "select * from s_labour where act='1' and cancel='0' and SCODE='" . $COMPANY . "' order by CODE";
        $result_lab = $conn->query($sql_lab);
        if ($row_lab = $result_lab->fetch()) {

            $ResponseXML .= "<select_lab><![CDATA[";
            foreach ($conn->query($sql_lab) as $row_lab) {
                $ResponseXML .= " <option value='" . $row_lab["CODE"] . "'>" . $row_lab["DESCRIPTION"] ."</option> ";

            }

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

    }else{
        $COMPANY=$row_para['flag1'];

        $sql_sto = "select * from s_stomas where act='1' and SCODE='" . $COMPANY . "' ";
        $result_sto = $conn->query($sql_sto);
        if ($row_sto = $result_sto->fetch()) {

            $_SESSION["department"]=$row_sto["CODE"];

            $ResponseXML .= "<select_dep><![CDATA[";
            foreach ($conn->query($sql_sto) as $row_sto) {
                $ResponseXML .= " <option value='" . $row_sto["CODE"] . "'>" . $row_sto["DESCRIPTION"] ."</option> ";

            }

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

        if ($_SESSION["CURRENT_REP"] != "") {
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' and REPCODE='".$_SESSION["CURRENT_REP"]."' order by REPCODE";
        }else{
            $sql_rep = "select * from s_salrep where pactive='1' and SCODE='" . $COMPANY . "' order by REPCODE";
        }
        $result_rep = $conn->query($sql_rep);
        if ($row_rep = $result_rep->fetch()) {

            $ResponseXML .= "<select_rep><![CDATA[";
            foreach ($conn->query($sql_rep) as $row_rep) {
                $ResponseXML .= " <option value='" . $row_rep["REPCODE"] . "'>" . $row_rep["Name"] ."</option> ";

            }

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

        $sql_lab = "select * from s_labour where act='1' and cancel='0' and SCODE='" . $COMPANY . "' order by CODE";
        $result_lab = $conn->query($sql_lab);
        if ($row_lab = $result_lab->fetch()) {

            $ResponseXML .= "<select_lab><![CDATA[";
            foreach ($conn->query($sql_lab) as $row_lab) {
                $ResponseXML .= " <option value='" . $row_lab["CODE"] . "'>" . $row_lab["DESCRIPTION"] ."</option> ";

            }

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


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

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


    $sql = "select last_update from invpara where flag='".$_SESSION['company']."'";
    $result = $conn->query($sql);
    $row = $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 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);

                $sqlbr_trn = "update s_cusordmas set INVNO= '0' where  INVNO='" . $_GET["invno"] . "'";
                $resultbr_trn = $conn->query($sqlbr_trn);


                $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 = '" . $row['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 = '" . $row['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 = '" . $row['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) values ('" . $_GET['invno'] . "', '" . $_SESSION["CURRENT_USER"] . "', 'Invoice', 'Cancel', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
                $result2 = $conn->query($sql2);
                echo "Cancelled";
                $conn->commit();
            } else {
                echo "Already Paid";
                exit();
            }
        } else {
            echo "Can't Cancel";
            exit();
        }
    } catch (Exception $e) {
        $conn->rollBack();
        echo $e;
    }
}


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

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

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

        if(($_GET["subtotal"]/$_GET["qty"]) <$rowmas['acc_cost']){
            // exit('Under Cost');
        }
              

        if(($rowmas['Cat1'] =='TO BE EDIT ITEM RATE MINUS') ){
            $rate = str_replace(",", "", ($_GET["rate"]*-1));
        }else{
            $rate = str_replace(",", "", $_GET["rate"]);
        }


        $actual_selling = str_replace(",", "", $_GET["rate"]);
        $qty = str_replace(",", "", $_GET["qty"]);
        $subtotal = str_replace(",", "", $_GET["subtotal"]);
        $subtotal1 = str_replace(",", "", $_GET["subtotal"]);
        $cardfee = str_replace(",", "", $_GET["cardfee"]);

        $disper=0;
        $disper1=0;

        if (($_GET["discountper"] != '') && ($_GET["discountper"] != "0") && ($_GET["discountper"] != "0.00")) {
            $disper = $_GET["discountper"];
            $disper1 = $_GET["discountper"];
        }

        if (($_GET["discountper1"] != '') && ($_GET["discountper1"] != "0") && ($_GET["discountper1"] != "0.00")) {
            $disper2 = (100 - $_GET["discountper"]) * ($_GET["discountper1"]) / 100;
            $disper = $disper1 +$disper2;
        }

        $subtotal2 = ($rate - ($rate * $disper / 100))*$qty;

        if ($subtotal1 != $subtotal2) {
            if (($subtotal1 != 1) && ($subtotal2 != 0)) {
                //echo $subtotal1;
                exit('Error');
            }
        }





        $sql = "select QTYINHAND from s_submas where STK_NO='" . $_GET['itemcode']  . "' AND STO_CODE='" . $_GET["department"] . "'";
        $result = $conn->query($sql);
        if ($row = $result->fetch()) {
            if ($row["QTYINHAND"] >= $qty) {
                $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)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"] . "') ";

                $result = $conn->query($sql);
            }else{
                // if($rowmas['CAT'] =='None Stock Item'){
                    $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)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"] . "') ";

                    $result = $conn->query($sql);
                // }else{
                //     // exit('Under  Stock In Your Department!!!!');
                // }

            }
        }else{
            exit('please insert  stock');
        }




    }

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



        $rate = str_replace(",", "", $_GET["dag_selling"]);
        $actual_selling = str_replace(",", "", $_GET["dag_selling"]);
        $qty = 1;
        $subtotal = str_replace(",", "", $_GET["dag_subtotal"]);
        $subtotal1 = str_replace(",", "", $_GET["dag_subtotal"]);

        $subtotal2 = $rate - ($rate * $_GET["dag_dis"] / 100);

        if ($subtotal1 = !$subtotal2) {
            if (($subtotal1 != 1) && ($subtotal2 != 0)) {
                //echo $subtotal1;
                exit('Error');
            }
        }


        $sql = "select * from dag_item where jobno='" . $_GET['dag_jobno']  . "' AND company='" . $_SESSION['company']. "' and invno IS NULL ";
        $result = $conn->query($sql);
        if ($row = $result->fetch()) {

            $sql = "Insert into 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'] . "', 'IT/0727','" . $_GET['dag_jobno'] . "', '" . $_GET['dag_make'] . "', '" . $_GET['dag_design'] . "', '" . $_GET['dag_size'] . "', '" . $actual_selling . "', '".$qty."', " . $_GET["dag_dis"] . ", '" . $subtotal . "',  '" . $_GET['tmpno'] . "','" . $actual_selling . "', '" . $_GET['dag_serialno'] . "', '" . $_GET['Command1'] . "', '" . $_GET['dag_cost'] . "', '" . $_SESSION["CURRENT_USER"] . "') ";
            $result = $conn->query($sql);

        }else{
            exit('Cannot Add.Already Invoiced Or Canceled!!!!');
        }

    }

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

        $sql = "delete from tmp_inv_data where id='" . $_GET['id'] . "'";
        $result = $conn->query($sql);
    }

    if ($_GET['Command1'] == "editrate") {
        $actual_selling = str_replace(",", "", $_GET["rate"]);
        $qty = str_replace(",", "", $_GET["qty"]);
        $subtotal = str_replace(",", "", $_GET["subtotal"]);
        $subtotal1 = str_replace(",", "", $_GET["subtotal"]);


        $disper=0;
        $disper1=0;
        if (($_GET["discount1per"] != '') && ($_GET["discount1per"] != "0") && ($_GET["discount1per"] != "0.00")) {
            $disper = $_GET["discount1per"];
            $disper1 = $_GET["discount1per"];
        }

        if (($_GET["discount2per"] != '') && ($_GET["discount2per"] != "0") && ($_GET["discount2per"] != "0.00")) {
            $disper2 = (100 - $_GET["discount1per"]) * ($_GET["discount2per"]) / 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["discount1per"]."',dis_per1='".$_GET["discount2per"]."',cur_discount='".$disper."',cur_subtot='".$subtotal."' where id='" . $_GET['id'] . "'" ;
        $result = $conn->query($sql);
    }




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

    $i = 1;
    $mtot = 0;
    $mtot2 = 0;
    $mtot1 = 0;
    $sql = "Select * from 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;
        $discount1per = "discount1per" . $i;
        $discount2per = "discount2per" . $i;
        $subtotal = "subtotal" . $i;
        $discount = "discount" . $i;

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

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

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

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

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

        $bgcolour = "";

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

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

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


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




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


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



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


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



    $sql = "Select * from 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 .= "<item_count><![CDATA[" . $i . "]]></item_count>";
    $ResponseXML .= "<Command1><![CDATA[" . $_GET['Command1'] . "]]></Command1>";

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

    $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 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["SPINV2"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$COMPANY."/INV/CB/") . 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/CB/") . substr($tmpinvno, $lenth - 6);
        }


    }else{

        $sql = "select SPINV,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/CRM/") . substr($tmpinvno, $lenth - 6);
        }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/CRM/") . substr($tmpinvno, $lenth - 6);
        }



    }




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



    $ResponseXML .= " </salesdetails>";


    echo $ResponseXML;
}


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



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

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

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


        $SELLING = $row['SELLING'];

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

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

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


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

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

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




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

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

    try {


        $insuf_qty = "";
        $sql = "select * from 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'];
                    }
                }

            }else{
                exit('please insert  stock');
            }
            $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("Error1111");
        }

        $sql_payment_status   = "SELECT * from s_payment_tmp where  UNIQ='" . $_GET["tmpno"] ."'  and  CANCELL='0' AND STATUS='0' ";
        $result_payment_status = $conn->query($sql_payment_status);
        if ($row_payment_status = $result_payment_status->fetch()) {
            exit("Some Payment Card Is Not Saved Please Check Paymet Cards...!!!");
        }

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

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

        $totdiscount = str_replace(",", "", $_GET["totdiscount"]);
        $subtot = str_replace(",", "", $_GET["subtot"]);
        $invtot = str_replace(",", "", $_GET["invtot"]);
        $tax = str_replace(",", "", $_GET["tax"]);
        $cardfee = str_replace(",", "", $_GET["cardfee"]);
        $vat = "";


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

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






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


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

        $sql_get_payment =  "Select sum(TOTAL) AS PAYTOTAL from s_payment_tmp where CANCELL='0' AND UNIQ='" . $_GET["tmpno"] ."' AND  USER='" . $_SESSION['CURRENT_USER'] . "'";
        $result_get_payment = $conn->query($sql_get_payment);
        $row_get_payment = $result_get_payment->fetch();

        $COMPANY=$_SESSION['company'];
        if ($invtot == $row_get_payment['PAYTOTAL']) {

            $sql = "select SPINV2,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["SPINV2"];
                $lenth = strlen($tmpinvno);
                $invno = trim("".$COMPANY."/INV/CB/") . substr($tmpinvno, $lenth - 6);

                $sql = "update invpara set SPINV2 = SPINV2 +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/CB/") . substr($tmpinvno, $lenth - 6);

                $sql = "update invpara set SPINV2 = SPINV2 +1 where flag='".$COMPANY."'";
                $res_inv = $conn->query($sql);


            }

        }else{

            $sql = "select SPINV,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/CRM/") . substr($tmpinvno, $lenth - 6);

                $sql = "update invpara set SPINV = SPINV +1 where flag='".$COMPANY."'";
                $res_inv = $conn->query($sql);

            }else{
                $COMPANY=$row['flag1'];

                $sql2 = "select SPINV,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/CRM/") . substr($tmpinvno, $lenth - 6);

                $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();
  
                            if(($rowtmp["cur_subtot"]/$rowtmp["cur_qty"]) <$rowmas['acc_cost']){

                                                    // exit('Under Cost');
                                                }
                                           


                $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) values "
                    . "('" . $invno . "', '" . $_GET["invdate"] . "', '" . trim($rowtmp["str_code"]) . "', '" . trim($rowtmp["str_description"]) . "', '" . $rowmas["PART_NO"] . "', " . $rowmas["acc_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"] . "','0', '" . $rowtmp["ad"] . "','" . $_GET["invdate"] . "' , '" . $rowtmp["serialno"] . "','PRODUCT')";
                $result_invo = $conn->query($sql_invo);
//                 $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
// ) VALUES (
//     '" . $invno . "',
//     '" . $_GET["invdate"] . "',
//     '" . trim($rowtmp["str_code"]) . "',
//     '" . trim(addslashes($rowtmp["str_description"])) . "',
//     '" . $rowmas["PART_NO"] . "',
//     " . (float)$rowmas["acc_cost"] . ",
//     " . (float)$rowtmp["actual_selling"] . ",
//     " . (float)$rowtmp["cur_qty"] . ",
//     '" . trim($_GET["department"]) . "',
//     '" . $rowtmp["cur_discount"] . "',
//     " . (float)$dis_per . ",
//     '" . $_GET["salesrep"] . "',
//     '" . addslashes($mvatrate) . "',
//     '" . addslashes($rowmas["BRAND_NAME"]) . "',
//     " . ((is_numeric($mvatrate) && $mvatrate !== '') ? $mvatrate : 'NULL') . ",
//     " . ((is_numeric($d1) && $d1 !== '') ? $d1 : 'NULL') . ",
//     " . ((is_numeric($d2) && $d2 !== '') ? $d2 : 'NULL') . ",
//     " . ((is_numeric($d3) && $d3 !== '') ? $d3 : 'NULL') . ",
//     " . (float)$rowtmp["cur_subtot"] . ",
//     0,
//     '',
//     '0',
//     '" . $_GET["customercode"] . "',
//     '',
//     '" . $rowtmp["ad"] . "',
//     '" . $_GET["invdate"] . "',
//     '" . $rowtmp["serialno"] . "',
//     'PRODUCT'
// )";

                
                

                $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) values
                ('" . trim($rowtmp["str_code"]) . "','" . $_GET["invdate"] . "','" . trim($invno) . "', " . $rowtmp["cur_qty"] . ", 'GRN', '" . trim($_GET["department"]) . "', '" . $_SESSION['dev'] . "', '', '', '1', 'INV','" . $_GET["invdate"] . "','" . $rowmas["acc_cost"] . "', '" . $rowtmp["serialno"] . "','" . $act_selling . "')";
                    $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);
                }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) values
                ('" . trim($rowtmp["str_code"]) . "','" . $_GET["invdate"] . "','" . trim($invno) . "', " . $rowtmp["cur_qty"] . ", 'INV', '" . trim($_GET["department"]) . "', '" . $_SESSION['dev'] . "', '', '', '1', 'INV','" . $_GET["invdate"] . "','" . $rowmas["acc_cost"] . "', '" . $rowtmp["serialno"] . "','" . $act_selling . "')";
                    $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);
                }
            }

            if($rowtmp['type']=='dag'){
                $dis_per = $rowtmp["cur_rate"] * $rowtmp["cur_qty"] * $rowtmp["dis_per"] * 0.01;

                $sqlmas = "select * from s_mas where STK_NO='" . trim($rowtmp["str_code"]) . "'";
                $resultmas = $conn->query($sqlmas);
                $rowmas = $resultmas->fetch();

                $sql_invo = "Insert into s_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) values "
                    . "('" . $invno . "', '" . $_GET["invdate"] . "', '" . trim($rowtmp["str_code"]) . "', '" . trim($rowtmp["str_description"]) . "', '" . $rowtmp["jobno"] . "', '" . $rowtmp["make"] . "', '" . $rowtmp["design"] . "', '" . $rowtmp["size"] . "', " . $rowtmp["cost"] . ", " . $rowtmp["actual_selling"] . ", " . $rowtmp["cur_qty"] . ", '" . trim($_GET["department"]) . "', '" . $rowtmp["dis_per"] . "', " . $dis_per . ", '" . $_GET["salesrep"] . "', '" . $mvatrate . "', '" . $rowmas["BRAND_NAME"] . "', " . $mvatrate . ", " . $d1 . ", " . $d2 . ", " . $d3 . ", " . $rowtmp["cur_subtot"] . ", '0', '', '0', '" . $_GET["customercode"] . "', '', '" . $rowtmp["ad"] . "','" . $_GET["invdate"] . "' , '" . $rowtmp["serialno"] . "','DAG')";
                $result_invo = $conn->query($sql_invo);

                $act_selling=$rowtmp["actual_selling"]-($rowtmp["actual_selling"]*$rowtmp["dis_per"]/100);


                $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) 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')";
                $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 = '" . $row["jobno"] . "' and serialno = '" . $row["serialno"] . "'";
                $results_submas = $conn->query($sqls_submas);

            }


            // ===================================

            //             $sqlmas_f="select * from s_mas where STK_NO='".trim($rowtmp["str_code"])."'";
            //             $resultmas_f = $conn->query($sqlmas_f);
            //             $rowmas_f = $resultmas_f->fetch();



            //  	if($rowmas_f['BRAND_NAME']=="SERVICE"){
            //     $costitemfinal=$rowtmp["cur_rate"];
            // }else{
            //     $costitemfinal=$rowmas_f["acc_cost"];
            //                 $invqtyfinal=$rowmas_f['QTYINHAND'];
            //                 $totinvqtyfinal=$rowmas_f['QTYINHAND'];

            //                  $recvalfinal=0;

            //                 $sqlpurtrn_f = "select * from s_trn where STK_NO='" . $rowtmp["str_code"] . "'  AND (LEDINDI='ARN' OR LEDINDI='GRN' OR LEDINDI='IIN') ORDER BY ID DESC";
            //                 foreach ($conn->query($sqlpurtrn_f) as $row_purtrn_f) {

            //                     if($row_purtrn_f['QTY']>=$invqtyfinal ){
            //                         $recvalfinal +=$invqtyfinal*$row_purtrn_f['COST'];
            //                         break;
            //                     }else {
            //                         $recvalfinal +=$row_purtrn_f['QTY']*$row_purtrn_f['COST'];
            //                         $invqtyfinal=$invqtyfinal-$row_purtrn_f['QTY'];
            //                     }

            //                 }
            //                 $unitcostfinal=$recvalfinal/$totinvqtyfinal;

            //     $costitemfinal=$unitcostfinal;

            //                 $sqls_mas="update s_mas set acc_cost= '".$costitemfinal."' where STK_NO='".trim($rowtmp["str_code"])."'";
            //               $results_mas = $conn->query($sqls_mas);
            // }


            // =======





        }



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

        $cardfee=$invtot-$invtot/(100+$_GET["cardfee"])*100;

     $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,
    CARD_FEE, CARD_FEERATE
) VALUES (
    '" . $invno . "', 'INV', '" . $_GET["invdate"] . "', '" . trim($_GET["customercode"]) . "', '" . $_GET["tel"] . "', 
    '" . trim($_GET["brand"]) . "', '" . trim($customername) . "', '" . $vat . "', " . (float)$tax . ", '" . $_GET["paymethod"] . "',
    " . (float)$totdiscount . ", " . (float)$subtot . ", " . (float)$invtot . ", 0, 
    '" . trim($_GET["salesord1"]) . "', '" . $_GET["invdate"] . "', '" . trim($_GET["department"]) . "', 
    '" . trim($_GET["salesrep"]) . "', " . (float)$tax . ", " . (float)$_GET["credper"] . ", " . (float)$mvatrate . ",
    " . (float)$d1 . ", " . (float)$d2 . ", " . (float)$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"]) . "', '" . addslashes($cus_address) . "',
    '" . $_GET['c_subcode'] . "', '" . $_GET['delitype'] . "', '" . $_GET['deli_name'] . "', 
    '" . $_GET['deli_address'] . "', '" . $maindepart . "', '" . $_GET["invdate"] . "', 
    '" . $COMPANY . "', '" . $_GET["vehino"] . "', '" . $_GET["jobno"] . "', '" . $_GET["millage"] . "',
    '" . addslashes($_GET["remarks"]) . "', '" . $_GET["invdate"] . "', '" . $_GET["pay_type"] . "',
    '" . $_GET["type2"] . "', '" . $_GET["labour"] . "', '" . $_GET["inquiry"] . "', 
    '" . $cardfee . "', '" . $_GET["cardfee"] . "'
)";

        $resultsalma = $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);

        if($_GET["inquiry"]!=""){
            $sqlbr_trn = "update s_inquiry set STATUS= '1' where  REFNO='" . $_GET["inquiry"] . "'";
            $resultbr_trn = $conn->query($sqlbr_trn);
        }




        $paytype = $_GET['pay_type'];
        $paidtotal=0;
        if($paytype == "CREDIT"){
            $paytype = "CR";
        }else{


            // $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;

            $sql_get_payment =  "Select * from s_payment_tmp where CANCELL='0' AND UNIQ='" . $_GET["tmpno"] ."' AND  USER='" . $_SESSION['CURRENT_USER'] . "'";
            $result_get_payment = $conn->query($sql_get_payment);
            if (!$row_get_payment = $result_get_payment->fetch()) {
                exit("Payment Not found");
            }


            $sql_payment_card =  " SELECT SUM(TOTAL) AS tot FROM s_payment_tmp where CANCELL='0' AND UNIQ='" . $_GET["tmpno"] ."' AND STATUS='1' ";
            $result_payment_card = $conn->query($sql_payment_card);
            if ($row_payment_card = $result_payment_card->fetch()) {

                if($row_payment_card['tot'] < 0){
                    exit("Please Enter Payment Amount & Save The Payment Card ");
                }

                if($row_payment_card['tot'] > $invtot){


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


                    $sql = "insert into c_bal(REFNO, SDATE, trn_type, CUSCODE, AMOUNT, BALANCE, SAL_EX, DEV,maindepartment,sdate1,c_code1,company) values
                	  ('" . $recno . "', '" . $_GET["invdate"] . "', 'REC', '" .$_GET["customercode"] . "',  " . $_GET["model_all_balance"] . ", " . $_GET["model_all_balance"] . ", '" . $_GET["salesrep"] . "', '" . $_SESSION["dev"] . "','" . $maindepart . "','".$_GET["invdate"]."','" . $_GET["cuscode"] . "','".$_SESSION['company']."')";
                    $result_save_payment = $conn->query($sql);
                }
            }


            $paidfulltotal=0;
            foreach ($conn->query($sql_get_payment) as $row_get_payment) {

                $payamount=$row_get_payment["TOTAL"];

                if($row_get_payment['PAY_TYPE'] == "CASH"){
                    $paytypeold='CAS';
                    $paytype1='Cash';
                    $st_chbank='';
                    $ST_CHNO='CASH';
                    $st_chdate=$_GET["invdate"];
                    $note='';

                }else if($row_get_payment['PAY_TYPE'] == "CARD"){
                    $paytypeold='CAS';
                    $paytype1='Card';
                    $st_chbank=$row_get_payment["CARD_NAME"];
                    $ST_CHNO=$row_get_payment["CARD_NO"];
                    $st_chdate=$row_get_payment["CARD_DATE"];
                    $note='';

                }else if($row_get_payment['PAY_TYPE'] == "CHEQUE"){
                    $paytypeold='CHK';
                    $paytype1='Cheque';
                    $ST_CHNO=$row_get_payment["CHEQUE_NO"];
                    $st_chbank=$row_get_payment["CHEQUE_BANK"];
                    $st_chdate=$row_get_payment["CHEQUE_DATE"];
                    $note='';

                }else if($row_get_payment['PAY_TYPE'] == "GIFT CARD"){
                    $paytypeold='GC';
                    $paytype1='Gift Card';
                    $ST_CHNO=$row_get_payment["GIFT_CARD_NO"];
                    $st_chbank='';
                    $st_chdate=$_GET["invdate"];
                    $note='';

                }else if($row_get_payment['PAY_TYPE'] == "BANK DEPOSIT"){
                    $paytypeold='Cash TT';
                    $paytype1='Bank Deposit';
                    $ST_CHNO='Cash TT';
                    $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($row_get_payment['PAY_TYPE'] == "ONLINE PAYMENT"){
                    $paytypeold='CAS';
                    $paytype1='Online Payment';
                    $ST_CHNO='Online Payment';
                    $st_chbank=$_GET["online_pay_bank_name"];
                    $st_chdate=$_GET["invdate"];
                    $note=$_GET["online_pay_note"];
                }


                $pay_note="";


                if($row_get_payment["PAY_TYPE"] == "CHEQUE"){


                    $sql2 = "insert into s_invcheq(refno, Sdate, cus_code, CUS_NAME, cheque_no, che_date, bank, che_amount, sal_ex, trn_type, ex_flag, ch_owner, noof, ret_refno, ch_count_ret, department,company) values
                ('" . $recno . "', '" . $_GET["invdate"] . "', '" . $_GET["customercode"] . "', '" . $customername . "', '" . $ST_CHNO . "', '" . $st_chdate . "', '" . $st_chbank . "',  " . $row_get_payment["TOTAL"] . ", '" . $_GET["salesrep"] . "', 'REC', 'N', '" . $_GET["salesrep"] . "', 0, '1', '0', 'O','".$_SESSION['company']."')";
                    $result_save_payment = $conn->query($sql2);
                }


                if($row_get_payment["PAY_TYPE"] == "BANK TRANSFER"){
                    $pay_note = $row_get_payment["BANK_TRAN_NOTE"];
                }
                if($row_get_payment["PAY_TYPE"] == "ONLINE PAYMENT"){
                    $pay_note = $row_get_payment["ONLINE_PAY_NOTE"];
                }


                $diff = abs(strtotime($st_chdate) - strtotime($_GET["invdate"]));
                $days = floor($diff / (60 * 60 * 24));

                $sql_save_paymnet = "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 . "', " . $row_get_payment["TOTAL"] . ", '" . $ST_CHNO . "', '" . $st_chdate . "', '" . $paytypeold . "', '" . $days . "', '" . $days . "', '" . $st_chbank . "', '" . $_GET["customercode"] . "', '" . $_SESSION['dev'] . "', 0, 0, 0, '0', 'O','".$_SESSION['company']."','".$paytype1."','".$pay_note."')";
                $result_save_payment = $conn->query($sql_save_paymnet);



                $paidtotal += $row_get_payment["TOTAL"];


                if ($paytype=="CASH"){
                    $sql2 = "update s_salma set CASH=CASH + " . $payamount . " where REF_NO = '" . $invno . "'";
                    $result = $conn->query($sql2);
                }

            }


            $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"]) . "', '" . $paidtotal . "', '" . $paidtotal . "', 0, 'REC', '".$paytype1."', '" . $_GET["salesrep"] . "', '0', '" . $_GET["tmpno"] . "', 'O', '0', '".$ttdate."', '',  '" . $_SESSION['dev'] . "','".$COMPANY."' )";
            $result = $conn->query($sql);


            $sql2 = "update s_salma set TOTPAY=TOTPAY + '" . $paidtotal . "' where REF_NO = '" . $invno . "'";
            $result = $conn->query($sql2);




        }



        // $sql2 = "update invpara set INV_RECNO=INV_RECNO + 1  where flag='".$COMPANY."'";
        // $result = $conn->query($sql2);


        $sql7 = "delete from s_payment_tmp where   USER='" . $_SESSION["CURRENT_USER"] . "' ";
        $result7 = $conn->query($sql7);



        $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) values 
    ('" . trim($invno) . "', '" . $_SESSION["CURRENT_USER"] . "', 'Invoice', 'Save', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
        $resultbrand = $conn->query($sqlbrand);


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

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

    try {
        $sql = "update s_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);

        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);

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

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


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


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

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

        $sqlinv = "select * from vendor where NAME='" . $_GET["customer_name"] . "' and TELE1='" . $_GET["customer_tel"] . "' ";
        $resultinv = $conn->query($sqlinv);
        if ($rowinv = $resultinv->fetch()) {
            $msg= "Already Found Customer..!!!!";
            $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
            $ResponseXML .= "</salesdetails>";
            echo $ResponseXML;
            exit();
        }



        $sql = "SELECT cus,VATTYPE FROM invpara where flag='".$_SESSION['company']."'";
        $result = $conn->query($sql);
        $row = $result->fetch();

        $vattype=$row['VATTYPE'];
        $no = $row['cus'];
        $tmpinvno = "0000" . $no;
        $lenth = strlen($tmpinvno);
        $refno = trim("V/ ") . substr($tmpinvno, $lenth - 4);

        $sql_1 = "select * from vendor where CODE='" . $refno . "'  ";
        $result_1= $conn->query($sql_1);
        if ($row_1 = $result_1->fetch()) {
            $msg= "Error Result..";
            $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
            $ResponseXML .= "</salesdetails>";
            echo $ResponseXML;
            exit();
        }

        if($vattype =="1"){
            if(($_GET['customer_vat_no'] == "")){
                $msg= "Please Enter Vat No";
                $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
                $ResponseXML .= "</salesdetails>";
                echo $ResponseXML;
                exit();
            }

        }else if($vattype =="0"){
            if(($_GET['customer_vat_no'] != "") && ($_GET['customer_vat_no'] !="")){
                $msg= "Can't Add Vat Customer.Please Clear Vat No & Svat No";
                $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
                $ResponseXML .= "</salesdetails>";
                echo $ResponseXML;
                exit();
            }
        }





        $txtCNAME = str_replace("~", "&", $_GET['customer_name']);


        $sql_data = "insert into vendor  (CODE, NAME, ADD1,TELE1,vatno, CAT, svatno,OPDATE) values 
          ('" . $refno . "', '" . $txtCNAME . "', '" . $_GET['customer_address'] . "', '" . $_GET['customer_tel'] . "', '" . $_GET['customer_vat_no'] . "', 'C', '" . $_GET['customer_svat_no'] . "','" . date("Y-m-d") . "')";
        $result_data = $conn->query($sql_data);

        $sql = "delete from vender_sub where c_code = '" . $refno . "' and c_main = '" . $refno . "'";
        $result = $conn->query($sql);


        $c_add = $_GET['customer_address'];
        $sql = "insert into vender_sub (c_code,c_name,c_add,c_tele,c_vatno,c_svatno,c_main,type) values
        ('" . $refno . "','" . $txtCNAME . "','" . $c_add . "','" . $_GET['customer_tel'] . "','" . $_GET['customer_vat_no'] . "','" . $_GET['customer_svat_no'] . "','" . $refno . "','M') ";
        $result = $conn->query($sql);

        $sql = "update invpara set cus = cus + 1";
        $result = $conn->query($sql);


        $sql2 = "insert into entry_log(refno, username, docname, trnType, stime, sdate) values 
        ('" . $refno . "', '" . $_SESSION["CURRENT_USER"] . "', 'Customer', 'Save', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
        $result2 = $conn->query($sql2);

        $msg ="Saved";

        $conn->commit();


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

    $sql_VEN= "select * from vendor where CODE='" . $refno . "' ";
    $result_VEN = $conn->query($sql_VEN);
    if ($row_VEN = $result_VEN->fetch()) {

        $ResponseXML .= "<customer_code><![CDATA[" . $row_VEN['CODE'] . "]]></customer_code>";
        $ResponseXML .= "<customer_name><![CDATA[" . $row_VEN['NAME'] . "]]></customer_name>";
        $ResponseXML .= "<customer_tel><![CDATA[" . $row_VEN['TELE1'] . "]]></customer_tel>";
        $ResponseXML .= "<customer_address><![CDATA[" . $row_VEN['ADD1'] . "]]></customer_address>";
        $ResponseXML .= "<customer_vat_no><![CDATA[" . $row_VEN['vatno'] . "]]></customer_vat_no>";
        $ResponseXML .= "<customer_svat_no><![CDATA[" . $row_VEN['svatno'] . "]]></customer_svat_no>";
    }else{
        $msg="Error Result..";
    }

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


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


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


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

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

        // $sqlinv = "select * from s_mas where PART_NO='" . $_GET["item_partno"] . "'";
        // $resultinv = $conn->query($sqlinv);
        // if ($rowinv = $resultinv->fetch()) {
        //     $msg= "Already Found Serial No /Part No..!!!!";
        //     $ResponseXML .= "<msg><![CDATA[" . $msg . "]]></msg>";
        //     $ResponseXML .= "</salesdetails>";
        //     echo $ResponseXML;
        //     exit();
        // }



        $sql = "SELECT itemno FROM invpara ";
        $result = $conn->query($sql);
        $row = $result->fetch();
        $no = $row['itemno'];

        $tmpinvno = "0000" . $no;
        $lenth = strlen($tmpinvno);
        $refno = trim("IT/ ") . substr($tmpinvno, $lenth - 4);

        $sql_1 = "select * from s_mas where STK_NO='" . $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();
        }


        $txtCNAME = str_replace("~", "&", $_GET['item_name']);


        $sql_data = "insert into s_mas  (STK_NO, DESCRIPT, BRAND_NAME,  PART_NO, COST,SELLING,CAT,Cat1,type) values 
          ('" . $refno . "', '" . $txtCNAME . "', '" . $_GET['item_brand'] . "', '" . $_GET['item_partno'] . "', '" . $_GET['item_cost'] . "', '" . $_GET['item_selling'] . "','None Stock Item','OTHER','OTHER')";
        $result_data = $conn->query($sql_data);

        $sql_get = "Select * from s_stomas";
        foreach ($conn->query($sql_get) as $row_get) {
            $M_STOCODE = $row_get["CODE"];

            $sql1 = "select * from s_submas where sto_code= '" . trim($M_STOCODE) . "' and stk_no= '" . trim($refno) . "'";
            $result1 = $conn->query($sql1);
            if ($row1 = $result1->fetch()) {
                $sql2 = "update s_submas set STO_CODE='" . trim($M_STOCODE) . "', STK_NO='" . $refno . "', DESCRIPt='" . $txtCNAME . "' where  sto_code= '" . trim($M_STOCODE) . "' and stk_no= '" . trim($refno) . "'";
                $result_data = $conn->query($sql2);
            } else {
                $sql2 = "Insert into s_submas (STO_CODE, STK_NO, DESCRIPt) values
                ('" . trim($M_STOCODE) . "', '" . $refno . "', '" . $txtCNAME . "')";
                $result_data = $conn->query($sql2);
            }
        }

        $sql2 = "update invpara set itemno=itemno+1";
        $result_data = $conn->query($sql2);

        $sql = "insert into entry_log(refno, username, docname, trnType, stime, sdate) values 
            ('" . trim($refno) . "', '" . $_SESSION["CURRENT_USER"] . "', 'Item', 'Save' , '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
        $result_data = $conn->query($sql2);

        $msg ="Saved";

        $conn->commit();


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

    $sql_VEN= "select * from s_mas where STK_NO='" . $refno . "' ";
    $result_VEN = $conn->query($sql_VEN);
    if ($row_VEN = $result_VEN->fetch()) {

        $ResponseXML .= "<item><![CDATA[" . $row_VEN['STK_NO'] . "]]></item>";
        $ResponseXML .= "<name><![CDATA[" . $row_VEN['DESCRIPT'] . "]]></name>";
        $ResponseXML .= "<part_no><![CDATA[" . $row_VEN['PART_NO'] . "]]></part_no>";
        $ResponseXML .= "<rate><![CDATA[" . $row_VEN['SELLING'] . "]]></rate>";
    }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;
}



// =========================pay model==========

if (isset($_POST["Command"]) && $_POST["Command"] == "pay_model") {

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

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

    $sql_table_count =  " SELECT COUNT(ID) AS COUNT FROM tmp_inv_data where  tmp_no='" . $_POST["tmp_uniq"] ."' ";
    $result_table_count = $conn->query($sql_table_count);
    if ($row_table_count = $result_table_count->fetch()) {

        $ResponseXML .= "<row_count><![CDATA[" . $row_table_count['COUNT'] . "]]></row_count>";
    }

    $sql_search =  " SELECT SUM(cur_subtot) AS tot FROM tmp_inv_data where  tmp_no='" . $_POST["tmp_uniq"] ."' ";
    $result_search = $conn->query($sql_search);
    if ($row_search = $result_search->fetch()) {

        $ResponseXML .= "<tot_count><![CDATA[" . number_format($row_search['tot'], 2, '.', '') . "]]></tot_count>";
    }

    $sql_disvalue =  " SELECT SUM(cur_discount) AS dis_tot FROM tmp_inv_data where  tmp_no='" . $_POST["tmp_uniq"] ."' ";
    $result_disvalue = $conn->query($sql_disvalue);
    if ($row_disvalue = $result_disvalue->fetch()) {
        $ResponseXML .= "<all_itemdis><![CDATA[" . number_format($row_disvalue['dis_tot'], 2, '.', '') . "]]></all_itemdis>";
    }


    if($_SESSION['CURRENT_USER']==""){

        exit("Please Login Again...!!!");

    }


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


    // $ResponseXML .= "<itm_count><![CDATA[" . $i . "]]></itm_count>";
    // $ResponseXML .= "<vat_val><![CDATA[" . $value_vat . "]]></vat_val>";
    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;

}



if (isset($_POST["Command"]) && $_POST["Command"] == "new_card") {

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

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

    if($_SESSION['CURRENT_USER']==""){

        exit("Please Login Again...!!!");

    }

    $msg="";

    if ($_POST["delete_card"] == "del_item") {

        $sql_delete = "delete from s_payment_tmp where USER='" . $_SESSION['CURRENT_USER'] . "' and UNIQ ='" . $_POST['tmp_uniq'] . "' AND REFNO = '" . $_POST['refno'] . "'";
        $result = $conn->query($sql_delete);

    }else{


        //   $sql_em_paycard  = "SELECT * from s_payment_tmp where   UNIQ='" . $_POST["tmp_uniq"] ."'   AND (TOTAL='' OR TOTAL='0.00' OR STATUS='0' )";
        //   $result_em_paycard = $conn->query($sql_em_paycard);
        //   if ($row_em_paycard = $result_em_paycard->fetch()) {

        //         $msg= "This Card Paid Amount Is 0.00";
        //         $ResponseXML .= "<msg_ex><![CDATA[" .  $msg . "]]></msg_ex>";
        //         $ResponseXML .= "</salesdetails>";
        //         echo $ResponseXML;
        //         exit();
        //   }
    }
    try {

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

        $sql1 = "SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 's_payment_tmp' and TABLE_SCHEMA  ='".$dbname."'";
        $result2 = $conn->query($sql1);

        if (!$row1 = $result2->fetch()) {
            exit();
        }

        $pay_card = "PCD/" . $row1['auto_increment'];

        if($_POST['payment_type']  != ""){

            $sql_save    = "insert into s_payment_tmp(
            REFNO,PAY_TYPE,USER,USER_DTIME,UNIQ) values (
            '" . $pay_card . "',
            '" . $_POST['payment_type'] . "',
            '" . $_SESSION['CURRENT_USER'] . "',
            '" . date('Y-m-d H:i:s') . "',
            '" . $_POST["tmp_uniq"] . "')";
            $result_save = $conn->query($sql_save);

        }


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



    $sql_get =  "Select * from s_payment_tmp where  UNIQ='" . $_POST["tmp_uniq"] ."' order by ID desc ";
    $result_get = $conn->query($sql_get);



    if ($row_get = $result_get->fetch()) {
        $ResponseXML .= "<pay_card><![CDATA[";

        $i = 0;
        $itemtot =0;
        $distot =0;
        foreach ($conn->query($sql_get) as $row_get) {

            $card_paid_amount = "card_paid_amount" .$i;
            $card_name = "card_name" .$i;
            $card_number = "card_number" .$i;
            $card_expiry_date = "card_expiry_date" .$i;

            $cash_amount = "cash_amount" .$i;

            $cheque_amount = "cheque_amount" .$i;
            $cheque_no = "cheque_no" .$i;
            $cheque_bank_name = "cheque_bank_name" .$i;
            $cheque_date = "cheque_date" .$i;

            $bank_transfer_amount = "bank_transfer_amount" .$i;
            $bank_transfer_bank_name = "bank_transfer_bank_name" .$i;
            $bank_transfer_note = "bank_transfer_note" .$i;
            $bank_transfer_date = "bank_transfer_date" .$i;

            $online_pay_amount = "online_pay_amount" .$i;
            $online_pay_note = "online_pay_note" .$i;

            $gift_card_no_amount = "gift_card_no_amount" .$i;
            $gift_card_no = "gift_card_no" .$i;

            $paytype = "paytype" .$i;
            $pay_card_msg = "pay_card_msg" .$i;
            $status = "status" .$i;
            $boder_coler = "boder_coler" .$i;

            if($row_get['PAY_TYPE'] == "CARD"){

                $boder_coler1="border: solid red;padding: 10px;";
                $msg_save="<span class='alert alert-warning m-0' role='alert' style='padding :0.43rem 1.25rem !important; background-color: rgba(255, 94, 109, 0.2); color: #c24753;'> Payment Not Saved : Please Filing To Data</span>";
                if( $row_get['STATUS'] == 1){
                    $msg_save="";
                    $color="";
                    $msg_save="<span class='alert alert-success' role='alert' style='padding :0.43rem 1.25rem !important;'> Payment Temporary Saved </span>";
                    $boder_coler1="";
                    $boder_coler1="border: solid #49c152; padding: 10px;";
                }

                $ResponseXML .= "<br>";
                $ResponseXML .= "  <div id='$boder_coler' name='$boder_coler' style='$boder_coler1' >";
                $ResponseXML .= " <div>  
                        <a type='button' class='btn btn-danger btn-sm' onclick=\"delete_card('" . $row_get['REFNO'] . "');\">Delete</a> 
                        <span  id='$pay_card_msg' name='$pay_card_msg' >$msg_save </span>
                          <input type='hidden' class='form-control' placeholder='0.00' id='$paytype' name='$paytype'  value='" . $row_get['PAY_TYPE'] . "'> 
                           <input type='hidden' class='form-control' placeholder='0.00' id='$status' name='$status'  value='" . $row_get['STATUS'] . "'>                      
                              <div class='row'>
                            <div class='col-md-3'>  
                           <span class='font-weight-normal card-text' style='line-height: 30px;'>Paid Amount</span>
                          <div class='input'>
                            <input type='number' class='form-control' placeholder='0.00' id='$card_paid_amount' name='$card_paid_amount'  value='" . $row_get['CARD_AMOUNT'] . "' onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\">
                          </div> 
                          </div>
                              <div class='col-md-3'>
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Card Type</span>
                          <div class='input'>


                          <select  class='form-control form-control-sm'  style='width: 100%;' id='$card_name' name='$card_name' onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\">";

                if($row_get['CARD_NAME'] != ""){
                    $ResponseXML .="<option value='" . $row_get['CARD_NAME'] . "'>" . $row_get['CARD_NAME'] . "</option>";
                }else{
                    $ResponseXML .="<option value=''>Select Card Type </option> ";
                }

                $sql = "Select * from s_paycard_type where CANCELL='0' and REFNO !='" . $row_get['CARD_NAME'] . "' ";
                foreach ($conn->query($sql) as $row) {
                    $ResponseXML .="<option value='" . $row['REFNO'] . "'>". $row['NAME'] . "</option>";
                }
                $ResponseXML .=" </select>

                          </div> 
                          </div>
                            <div class='col-md-3'>
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Card Number</span>
                          <div class='input'>
                            <input type='text' class='form-control' placeholder='0000 0000 0000 0000' id='$card_number' name='$card_number'
                            value='" . $row_get['CARD_NO'] . "' onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" >
                          </div> 
                          </div> 
                           <div class='col-md-3'>
                                <span class='font-weight-normal card-text' style='line-height: 30px;'>Expiry Date</span>
                              <div class='input'>
                                <input type='date' class='form-control' placeholder='MM/YY' id='$card_expiry_date' name='$card_expiry_date'  value='" . $row_get['CARD_DATE'] . "' onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" >
                              </div> 
                            </div> 
                            <div class='col-md-6'>
                        </div>
                       </div>
                       </div>
                        </div> ";



            }
            if($row_get['PAY_TYPE'] == "CASH"){
                $boder_coler1="border: solid red;padding: 10px;";
                $msg_save="<span class='alert alert-warning m-0' role='alert' style='padding :0.43rem 1.25rem !important; background-color: rgba(255, 94, 109, 0.2); color: #c24753;'> Payment Not Saved : Please Filing To Data</span>";
                if( $row_get['STATUS'] == 1){
                    $msg_save="";
                    $color="";
                    $msg_save="<span class='alert alert-success' role='alert' style='padding :0.43rem 1.25rem !important;'> Payment Temporary Saved </span>";
                    $boder_coler1="";
                    $boder_coler1="border: solid #49c152; padding: 10px;";
                }
                $ResponseXML .= "<br>";
                $ResponseXML .= "<div id='$boder_coler' name='$boder_coler' style='$boder_coler1' >";
                $ResponseXML .= "<div>
                        <a type='button' class='btn btn-danger btn-sm' onclick=\"delete_card('" . $row_get['REFNO'] . "');\">Delete</a> 
                          <span  id='$pay_card_msg' name='$pay_card_msg' >$msg_save </span>
                         <input type='hidden' class='form-control' placeholder='0.00' id='$paytype' name='$paytype'  value='" . $row_get['PAY_TYPE'] . "'> 
                          <input type='hidden' class='form-control' placeholder='0.00' id='$status' name='$status'  value='" . $row_get['STATUS'] . "'> 
                           <div class='row'>
                            <div class='col-md-3'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Paid Cash Amount</span>
                          <div class='input'>
                            
                            <input type='number' class='form-control' placeholder='0.00' id='$cash_amount' name$cash_amount' onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" value='" . $row_get['CASH_AMOUNT'] . "'>
                            
                          </div> 
                          </div> 

                                
                          </div> 
                       </div>
                        </div> ";

            }

            if($row_get['PAY_TYPE'] == "CHEQUE"){

                $boder_coler1="border: solid red;padding: 10px;";
                $msg_save="<span class='alert alert-warning m-0' role='alert' style='padding :0.43rem 1.25rem !important; background-color: rgba(255, 94, 109, 0.2); color: #c24753;'> Payment Not Saved : Please Filing To Data</span>";
                if( $row_get['STATUS'] == 1){
                    $msg_save="";
                    $color="";
                    $msg_save="<span class='alert alert-success' role='alert' style='padding :0.43rem 1.25rem !important;'> Payment Temporary Saved </span>";
                    $boder_coler1="";
                    $boder_coler1="border: solid #49c152; padding: 10px;";
                }

                $ResponseXML .= "<br>";
                $ResponseXML .= "  <div id='$boder_coler' name='$boder_coler' style='$boder_coler1' >";
                $ResponseXML .= "<div> 
                        <a type='button' class='btn btn-danger btn-sm' onclick=\"delete_card('" . $row_get['REFNO'] . "');\">Delete</a> 
                          <span  id='$pay_card_msg' name='$pay_card_msg' >$msg_save </span>
                         <input type='hidden' class='form-control' placeholder='0.00' id='$paytype' name='$paytype'  value='" . $row_get['PAY_TYPE'] . "' > 
                         <input type='hidden' class='form-control' placeholder='0.00' id='$status' name='$status'  value='" . $row_get['STATUS'] . "'> 
                                   <div class='row'>
                            <div class='col-md-3'>  
                           <span class='font-weight-normal card-text' style='line-height: 30px;'>Cheque Amount</span>
                          <div class='input'>
                            <input type='number' class='form-control' placeholder='0.00' id='$cheque_amount' name='$cheque_amount' value='" . $row_get['CHEQUE_AMOUNT'] . "' onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\">  
                          </div> 
                          </div>
                    <div class='col-md-3'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Cheque No</span>
                          <div class='input'>
                            <input type='text' class='form-control' placeholder='0000 0000 0000 0000' id='$cheque_no' name='$cheque_no' value='" . $row_get['CHEQUE_NO'] . "' onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\"> 
                          </div> 
                          </div> 
                            <div class='col-md-3'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Bank Name</span>
                          <div class='input'> 
                            <select  class='form-control form-control-sm'  style='width: 100%;' id='$cheque_bank_name' name='$cheque_bank_name' onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\">";
                if($row_get['CHEQUE_BANK'] != ""){
                    $ResponseXML .="<option value='" . $row_get['CHEQUE_BANK'] . "'>" . $row_get['CHEQUE_BANK'] . "</option>";
                }else{
                    $ResponseXML .="<option value=''>Select Bank Name</option> ";
                }

                $sql = "Select * from s_bank where CANCELL='0' AND REFNO != '" . $row_get['CHEQUE_BANK'] . "'";
                foreach ($conn->query($sql) as $row) {
                    $ResponseXML .="<option value='" . $row['REFNO'] . "'>". $row['NAME'] . "</option>";
                }
                $ResponseXML .=" </select>
                            
                          </div> 
                          </div> 

                            <div class='col-md-3'>  
                           <span class='font-weight-normal card-text' style='line-height: 30px;'>Cheque Date</span>
                          <div class='input'>
                           
                            <input type='date' class='form-control' placeholder='0.00' id='$cheque_date' name='$cheque_date' value='" . $row_get['CHEQUE_DATE'] . "' onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\">
                            
                          </div> 
                          </div> 
                          </div> 
                       </div>
                        </div> ";

            }

            if($row_get['PAY_TYPE'] == "BANK TRANSFER"){

                $boder_coler1="border: solid red;padding: 10px;";
                $msg_save="<span class='alert alert-warning m-0' role='alert' style='padding :0.43rem 1.25rem !important; background-color: rgba(255, 94, 109, 0.2); color: #c24753;'> Payment Not Saved : Please Filing To Data</span>";
                if( $row_get['STATUS'] == 1){
                    $msg_save="";
                    $color="";
                    $msg_save="<span class='alert alert-success' role='alert' style='padding :0.43rem 1.25rem !important;'> Payment Temporary Saved </span>";
                    $boder_coler1="";
                    $boder_coler1="border: solid #49c152; padding: 10px;";
                }

                $ResponseXML .= "<br>";
                $ResponseXML .= "  <div id='$boder_coler' name='$boder_coler' style='$boder_coler1' >";
                $ResponseXML .= "<div>
                        <a type='button' class='btn btn-danger btn-sm' onclick=\"delete_card('" . $row_get['REFNO'] . "');\">Delete</a> 
                             <span  id='$pay_card_msg' name='$pay_card_msg' >$msg_save </span>
                             <input type='hidden' class='form-control' placeholder='0.00' id='$paytype' name='$paytype'  value='" . $row_get['PAY_TYPE'] . "'> 
                              <input type='hidden' class='form-control' placeholder='0.00' id='$status' name='$status'  value='" . $row_get['STATUS'] . "'> 
                    <div class='row'>
                            <div class='col-md-3'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Bank Transfer Amount</span>
                          <div class='input'>
                            <input type='number' class='form-control' placeholder='0.00' id='$bank_transfer_amount' name='$bank_transfer_amount' onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\"  onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" value='" . $row_get['BANK_TRAN_AMOUNT'] . "'>
                            
                          </div> 
                          </div> 
                    
                          <div class='col-md-3'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Transfer Bank Name</span>
                          <div class='input'>
                            
                            <select  class='form-control form-control-sm'  style='width: 100%;' id='$bank_transfer_bank_name' name='$bank_transfer_bank_name' value='" . $row_get['BANK_TRAN_AMOUNT'] . "' onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\">";
                if($row_get['TRANSFER_BANK'] != ""){
                    $ResponseXML .="<option value='" . $row_get['TRANSFER_BANK'] . "'>" . $row_get['TRANSFER_BANK'] . "</option>";
                }else{
                    $ResponseXML .="<option value=''>Select Bank Name</option> ";
                }


                $sql = "Select * from s_bank where CANCELL='0' AND REFNO !='" . $row_get['TRANSFER_BANK'] . "' ";
                foreach ($conn->query($sql) as $row) {
                    $ResponseXML .="<option value='" . $row['REFNO'] . "'>". $row['NAME'] . "</option>";
                }
                $ResponseXML .=" </select>
                          </div> 
                          </div> 


                              <div class='col-md-3'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Bank Transfer Note</span>
                          <div class='input'>
                            
                            <input type='text' class='form-control'  id='$bank_transfer_note' rows='1' name='$bank_transfer_note' value='" . $row_get['BANK_TRAN_NOTE'] . "' onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\"></input>
                            
                          </div> 
                          </div> 

                           <div class='col-md-3'>  
                           <span class='font-weight-normal card-text' style='line-height: 30px;'>Bank Transfer Date</span>
                          <div class='input'>
                           
                            <input type='datetime-local' class='form-control' placeholder='0.00' id='$bank_transfer_date' name='$bank_transfer_date' value='" . $row_get['BANK_TRAN_DATE'] . "' onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\">
                            
                          </div> 
                          </div> 

                       </div>
                       </div>
                        </div> ";

            }

            if($row_get['PAY_TYPE'] == "ONLINE PAYMENT"){

                $boder_coler1="border: solid red;padding: 10px;";
                $msg_save="<span class='alert alert-warning m-0' role='alert' style='padding :0.43rem 1.25rem !important; background-color: rgba(255, 94, 109, 0.2); color: #c24753;'> Payment Not Saved : Please Filing To Data</span>";
                if( $row_get['STATUS'] == 1){
                    $msg_save="";
                    $color="";
                    $msg_save="<span class='alert alert-success' role='alert' style='padding :0.43rem 1.25rem !important;'> Payment Temporary Saved </span>";
                    $boder_coler1="";
                    $boder_coler1="border: solid #49c152; padding: 10px;";
                }
                $ResponseXML .= "<br>";
                $ResponseXML .= "<div id='$boder_coler' name='$boder_coler' style='$boder_coler1' >";
                $ResponseXML .= "<div>
                        <a type='button' class='btn btn-danger btn-sm' onclick=\"delete_card('" . $row_get['REFNO'] . "');\">Delete</a> 
                          <span  id='$pay_card_msg' name='$pay_card_msg' >$msg_save </span>
                         <input type='hidden' class='form-control' placeholder='0.00' id='$paytype' name='$paytype'  value='" . $row_get['PAY_TYPE'] . "'> 
                          <input type='hidden' class='form-control' placeholder='0.00' id='$status' name='$status'  value='" . $row_get['STATUS'] . "'> 
                           <div class='row'>
                            <div class='col-md-3'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Online Pay Amount</span>
                          <div class='input'>
                            
                            <input type='number' class='form-control' placeholder='0.00' id='$online_pay_amount' name='$online_pay_amount' onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" value='" . $row_get['ONLINE_PAY_AMOUNT'] . "'>
                            
                          </div> 
                          </div> 

                                <div class='col-md-9'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Online Payment Note</span>
                          <div class='input'>
                            
                            <input type='text' class='form-control'  id='$online_pay_note' rows='1' name='$online_pay_note' value='" . $row_get['ONLINE_PAY_NOTE'] . "' onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\"></input>
                            
                          </div> 
                          </div> 
                          </div> 
                       </div>
                        </div> ";

            }

            if($row_get['PAY_TYPE'] == "GIFT CARD"){

                $boder_coler1="border: solid red;padding: 10px;";
                $msg_save="<span class='alert alert-warning m-0' role='alert' style='padding :0.43rem 1.25rem !important; background-color: rgba(255, 94, 109, 0.2); color: #c24753;'> Payment Not Saved : Please Filing To Data</span>";
                if( $row_get['STATUS'] == 1){
                    $msg_save="";
                    $color="";
                    $msg_save="<span class='alert alert-success' role='alert' style='padding :0.43rem 1.25rem !important;'> Payment Temporary Saved </span>";
                    $boder_coler1="";
                    $boder_coler1="border: solid #49c152; padding: 10px;";
                }

                $ResponseXML .= "<br>";
                $ResponseXML .= "<div id='$boder_coler' name='$boder_coler' style='$boder_coler1' >";
                $ResponseXML .= "<div>
                         <a type='button' class='btn btn-danger btn-sm' onclick=\"delete_card('" . $row_get['REFNO'] . "');\">Delete</a> 
                         <span  id='$pay_card_msg' name='$pay_card_msg' >$msg_save </span>
                         <input type='hidden' class='form-control' placeholder='0.00' id='$paytype' name='$paytype'  value='" . $row_get['PAY_TYPE'] . "'> 
                            <input type='hidden' class='form-control' placeholder='0.00' id='$status' name='$status'  value='" . $row_get['STATUS'] . "'> 
                              <div class='row'>
                            <div class='col-md-3'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Gift Card Amount</span>
                          <div class='input'>
                            
                            <input type='number' class='form-control' placeholder='0.00' id='$gift_card_no_amount' name='$gift_card_no_amount' onchange=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" value='" . $row_get['GIFT_CRAD_AMOUNT'] . "'>
                            
                          </div> 
                          </div> 
                           <div class='col-md-4'>  
                          <span class='font-weight-normal card-text' style='line-height: 30px;'>Gift Card No</span>
                          <div class='input'>
                            
                            <input type='text' class='form-control'  id='$gift_card_no' rows='1' name='$gift_card_no'  onkeyup=\"tmp_save_card('".$i."','" . $row_get['REFNO'] . "');\" value='" . $row_get['GIFT_CARD_NO'] . "'>
                            
                          </div> 
                          </div> 
                          </div> 
                       </div>
                        </div> ";

            }

            $i = $i + 1;

        }

        $ResponseXML .= "]]></pay_card>";

    }else{
        // $value_vat ="1";
        $ResponseXML .= "<pay_card><![CDATA[ <br>
                           <div style='border: solid red;padding: 10px;' >
                           <div >
                       <h4 style='color:red'> Please Add The Payment Card</h4 style='clour:red'>
                        </div>
                        </div>
                    ]]></pay_card>";

    }

    $paid_amount_sum= 0.00;
    $paid_grand_total= 0.00;
    $paid_discount_total= 0.00;
    $paid_balance= 0.00;

    $sql_search =  " SELECT SUM(TOTAL) AS tot FROM s_payment_tmp where  UNIQ='" . $_POST["tmp_uniq"] ."' AND STATUS='1' ";
    $result_search = $conn->query($sql_search);
    if ($row_search = $result_search->fetch()) {

        $paid_amount_sum=$row_search['tot'];
    }
    $sql_grand =  " SELECT SUM(cur_subtot) AS tot FROM tmp_inv_data where  tmp_no='" . $_POST["tmp_uniq"] ."' ";
    $result_grand = $conn->query($sql_grand);
    if ($row_grand = $result_grand->fetch()) {

        $paid_grand_total = $row_grand['tot'];
        $paid_grand_total=$paid_grand_total+$paid_grand_total*$_POST['cardfee']/100;

    }

    $sql_disvalue =  " SELECT SUM(cur_discount) AS dis_tot FROM tmp_inv_data where  tmp_no='" . $_POST["tmp_uniq"] ."' ";
    $result_disvalue = $conn->query($sql_disvalue);
    if ($row_disvalue = $result_disvalue->fetch()) {

        $paid_discount_total= $row_disvalue['dis_tot'];;
    }
    $paid_balance =  $paid_amount_sum -$paid_grand_total ;
    if($paid_balance < 0){
        $paid_balance=0;
    }



    $ResponseXML .= "<summary><![CDATA[<table class=\"table table-bordered\">";


    $ResponseXML .= "<tr>
                      <td>Sub Total </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_itemtot'>" . number_format($paid_grand_total,2) . "</td>
                    </tr>
                    <tr>
                      <td>Discount </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_itemdis'>" .  number_format($paid_discount_total,2). "</td>
                    </tr>";

    if ($_POST['regi_vat_type'] != "Non Vat") {
        $ResponseXML .= "<tr>
                           <td>VAT </td>
                       <td style='text-align: right;  font-weight: bold;' id='model_all_itemtot'>0.00</td>
                       </tr>";
    }

    $ResponseXML .= "<tr>
                      <td>Grand Total </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_grand_total'>" . number_format($paid_grand_total,2) . "</td>
                    </tr>
                    <tr>
                     <td>Paid </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_paid'>" . number_format($paid_amount_sum,2) . "</td>
                    </tr>
                    <tr>
                     <td>Balance </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_inv_balance'>" . number_format($paid_grand_total-$paid_amount_sum,2) . "</td>
                    </tr>
                    <tr>
                     <td>Over Payment </td>";
    if ($paid_balance > 0) {
        $ResponseXML .= " <td style='text-align: right;  font-weight: bold;' id='model_all_balance'>" . number_format($paid_balance,2) . "</td>
                        </tr>";
    }else{
        $ResponseXML .= " <td style='text-align: right;  font-weight: bold; color: red; ' id='model_all_balance'>" . number_format($paid_balance,2) . "</td>
                         </tr>";
    }


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


    $ResponseXML .= "<count><![CDATA[" . $i . "]]></count>";
    // $ResponseXML .= "<vat_val><![CDATA[" . $value_vat . "]]></vat_val>";
    $ResponseXML .= "<msg_ex><![CDATA[" .  $msg . "]]></msg_ex>";
    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;

}


if (isset($_POST["Command"]) && $_POST["Command"] == "change_status_save") {

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

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

    try {

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

        $msg="";

        if($_SESSION['CURRENT_USER']==""){
            exit("Please Login Again...!!!");
        }



        $sql_4    = "SELECT * from s_payment_tmp where  REFNO='" . $_POST['refno'] . "' and CANCELL='0'";
        $result_4 = $conn->query($sql_4);
        if (!$row_4 = $result_4->fetch()) {
            exit("Already Canceled Payment...!!!");
        }

        $status=1;

        if($_POST['paytype'] == "CARD"){

            if($_POST['card_paid_amount'] == ""){
                $status=0;
            }
            if($_POST['card_paid_amount'] <= 0){
                $status=0;
            }
            if($_POST['card_name'] == ""){
                $status=0;
            }
            if($_POST['card_number'] == ""){
                $status=0;
            }
            if($_POST['card_expiry_date'] == ""){
                $status=0;
            }
        }

        if($_POST['paytype'] == "CASH"){

            if($_POST['cash_amount'] == ""){
                $status=0;
            }
            if($_POST['cash_amount'] <= 0){
                $status=0;
            }

        }


        if($_POST['paytype'] == "CHEQUE"){

            if($_POST['cheque_amount'] == ""){
                $status=0;
            }
            if($_POST['cheque_amount'] <= 0){
                $status=0;
            }
            if($_POST['cheque_no'] == ""){
                $status=0;
            }
            if($_POST['cheque_bank_name'] == ""){
                $status=0;
            }
            if($_POST['cheque_date'] == ""){
                $status=0;
            }
        }

        if($_POST['paytype'] == "BANK TRANSFER"){

            if($_POST['bank_transfer_amount'] == ""){
                $status=0;
            }
            if($_POST['bank_transfer_amount'] <= 0){
                $status=0;
            }
            if($_POST['bank_transfer_bank_name'] == ""){
                $status=0;
            }
            if($_POST['bank_transfer_note'] == ""){
                $status=0;
            }
            if($_POST['bank_transfer_date'] == ""){
                $status=0;
            }
        }

        if($_POST['paytype'] == "ONLINE PAYMENT"){

            if($_POST['online_pay_amount'] == ""){
                $status=0;
            }
            if($_POST['online_pay_amount'] <= 0){
                $status=0;
            }
            if($_POST['online_pay_note'] == ""){
                $status=0;
            }
        }

        if($_POST['paytype'] == "GIFT CARD"){

            if($_POST['gift_card_no_amount'] == ""){
                $status=0;
            }
            if($_POST['gift_card_no_amount'] <= 0){
                $status=0;
            }
            if($_POST['gift_card_no'] == ""){
                $status=0;
            }
        }

        $sql_update  = "update s_payment_tmp set 
        CARD_AMOUNT='" . $_POST['card_paid_amount'] . "',
        CARD_NAME= '" . $_POST['card_name'] . "',
        CARD_NO= '" .$_POST['card_number'] . "',
        CARD_DATE= '" .$_POST['card_expiry_date'] . "',
        CASH_AMOUNT= '" .$_POST['cash_amount'] . "',
        CHEQUE_AMOUNT='" . $_POST['cheque_amount'] . "',
        CHEQUE_NO='" . $_POST['cheque_no'] . "',
        CHEQUE_BANK='" . $_POST['cheque_bank_name'] . "',
        CHEQUE_DATE='" . $_POST['cheque_date'] . "',      
        TRANSFER_BANK='" . $_POST['bank_transfer_bank_name'] . "',
        BANK_TRAN_AMOUNT='" . $_POST['bank_transfer_amount'] . "',
        BANK_TRAN_NOTE='" . $_POST['bank_transfer_note'] . "',
        BANK_TRAN_DATE='" . $_POST['bank_transfer_date'] . "',
        ONLINE_PAY_AMOUNT='" . $_POST['online_pay_amount'] . "',
        ONLINE_PAY_NOTE='" . $_POST['online_pay_note'] . "',
        GIFT_CRAD_AMOUNT='" . $_POST['gift_card_no_amount'] . "',
        GIFT_CARD_NO='" . $_POST['gift_card_no'] . "',
        TOTAL='" . $_POST['amount'] . "',
        STATUS='" . $status . "'
        where REFNO='" . $_POST['refno']  . "'";
        $result_update = $conn->query($sql_update);

        $conn->commit();
    }
    catch (Exception $e) {
        $conn->rollBack();
        echo $e;
    }
    $paid_amount_sum= 0.00;
    $paid_grand_total= 0.00;
    $paid_discount_total= 0.00;
    $paid_balance= 0.00;

    $sql_search =  " SELECT SUM(TOTAL) AS tot FROM s_payment_tmp where CANCELL='0' AND UNIQ='" . $_POST["tmp_uniq"] ."' AND STATUS='1' ";
    $result_search = $conn->query($sql_search);
    if ($row_search = $result_search->fetch()) {

        $paid_amount_sum=$row_search['tot'];
    }
    $sql_grand =  " SELECT SUM(cur_subtot) AS tot FROM tmp_inv_data where UNIQ='" . $_POST["tmp_uniq"] ."'   ";
    $result_grand = $conn->query($sql_grand);
    if ($row_grand = $result_grand->fetch()) {

        $paid_grand_total = $row_grand['tot'];
        $paid_grand_total=$paid_grand_total+$paid_grand_total*$_POST['cardfee']/100;

    }

    $sql_disvalue =  " SELECT SUM(cur_discount) AS dis_tot FROM tmp_inv_data where tmp_no='" . $_POST["tmp_uniq"] ."' ";
    $result_disvalue = $conn->query($sql_disvalue);
    if ($row_disvalue = $result_disvalue->fetch()) {

        $paid_discount_total= $row_disvalue['dis_tot'];;
    }

    $paid_balance =  $paid_amount_sum - $paid_grand_total;
    if($paid_balance < 0){
        $paid_balance=0;
    }

    $ResponseXML .= "<summary><![CDATA[<table class=\"table table-bordered\">";


    $ResponseXML .= "<tr>
                      <td>Sub Total </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_itemtot'>" . number_format($paid_grand_total,2) . "</td>
                    </tr>
                    <tr>
                      <td>Discount </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_itemdis'>" .  number_format($paid_discount_total,2). "</td>
                    </tr>";

    if ($_POST['regi_vat_type'] != "Non Vat") {
        $ResponseXML .= "<tr>
                           <td>VAT </td>
                       <td style='text-align: right;  font-weight: bold;' id='model_all_itemtot'>0.00</td>
                       </tr>";
    }

    $ResponseXML .= "<tr>
                      <td>Grand Total </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_grand_total'>" . number_format($paid_grand_total,2) . "</td>
                    </tr>
                    <tr>
                     <td>Paid </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_paid'>" . number_format($paid_amount_sum,2) . "</td>
                    </tr>
                    <tr>
                     <td>Balance </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_inv_balance'>" . number_format($paid_grand_total-$paid_amount_sum,2) . "</td>
                    </tr>
                    <tr>
                     <td>Over Payment</td>";

    if ($paid_balance > 0) {
        $ResponseXML .= " <td style='text-align: right;  font-weight: bold;' id='model_all_balance'>" . number_format($paid_balance,2) . "</td>
                        </tr>";
    }else{
        $ResponseXML .= " <td style='text-align: right;  font-weight: bold; color: red; ' id='model_all_balance'>" . number_format($paid_balance,2) . "</td>
                         </tr>";
    }


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

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

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




}

if (isset($_POST["Command"]) && $_POST["Command"] == "tmp_save_card") {

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

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

    try {

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

        $msg="";

        if($_SESSION['CURRENT_USER']==""){
            exit("Please Login Again...!!!");
        }



        $sql_4    = "SELECT * from s_payment_tmp where  REFNO='" . $_POST['refno'] . "' and CANCELL='0'";
        $result_4 = $conn->query($sql_4);
        if (!$row_4 = $result_4->fetch()) {
            exit("Already Canceled User...!!!");
        }

        $sql_payment_card =  " SELECT SUM(TOTAL) AS tot FROM s_payment_tmp where CANCELL='0' AND UNIQ='" . $_POST["tmp_uniq"] ."' AND STATUS='1' ";
        $result_payment_card = $conn->query($sql_payment_card);
        $row_payment_card = $result_payment_card->fetch();

        // $sub_total = $_POST['card_paid_amount']+$_POST['cash_amount']+$_POST['cheque_amount']+$_POST['bank_transfer_amount']+$_POST['online_pay_amount']+$_POST['gift_card_no_amount']+$row_payment_card['tot'];

        // $sql_payment_item =  " SELECT SUM(TOTAL) AS tot FROM tmp_inv_data where CANCELL='0' AND UNIQ='" . $_POST["tmp_uniq"] ."' ";
        // $result_payment_item = $conn->query($sql_payment_item);
        // if ($row_payment_item = $result_payment_item->fetch()) {

        //     if($row_payment_item['tot'] < $sub_total){ // edit now

        //         $msg = "1";
        //         $ResponseXML .= "<error_msg><![CDATA[" . $msg . "]]></error_msg>";
        //         $ResponseXML .= "</salesdetails>";
        //         echo $ResponseXML;
        //         exit();
        // }


        // }

        $status=1;

        $sql_update  = "update s_payment_tmp set 
        CARD_AMOUNT='" . $_POST['card_paid_amount'] . "',
        CARD_NAME= '" . $_POST['card_name'] . "',
        CARD_NO= '" .$_POST['card_number'] . "',
        CARD_DATE= '" .$_POST['card_expiry_date'] . "',
        CASH_AMOUNT= '" .$_POST['cash_amount'] . "',
        CHEQUE_AMOUNT='" . $_POST['cheque_amount'] . "',
        CHEQUE_NO='" . $_POST['cheque_no'] . "',
        CHEQUE_BANK='" . $_POST['cheque_bank_name'] . "',
        CHEQUE_DATE='" . $_POST['cheque_date'] . "',      
        TRANSFER_BANK='" . $_POST['bank_transfer_bank_name'] . "',
        BANK_TRAN_AMOUNT='" . $_POST['bank_transfer_amount'] . "',
        BANK_TRAN_NOTE='" . $_POST['bank_transfer_note'] . "',
        BANK_TRAN_DATE='" . $_POST['bank_transfer_date'] . "',
        ONLINE_PAY_AMOUNT='" . $_POST['online_pay_amount'] . "',
        ONLINE_PAY_NOTE='" . $_POST['online_pay_note'] . "',
        GIFT_CRAD_AMOUNT='" . $_POST['gift_card_no_amount'] . "',
        GIFT_CARD_NO='" . $_POST['gift_card_no'] . "',
        TOTAL='" . $_POST['amount'] . "',
        STATUS='" . $status . "',
        DATE='" . $_POST['regi_date'] . "'
        where REFNO='" . $_POST['refno']  . "'";
        $result_update = $conn->query($sql_update);

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

    $paid_amount_sum= 0.00;
    $paid_grand_total= 0.00;
    $paid_discount_total= 0.00;
    $paid_balance= 0.00;

    $sql_search =  " SELECT SUM(TOTAL) AS tot FROM s_payment_tmp where CANCELL='0' AND UNIQ='" . $_POST["tmp_uniq"] ."' AND STATUS='1' ";
    $result_search = $conn->query($sql_search);
    if ($row_search = $result_search->fetch()) {

        $paid_amount_sum=$row_search['tot'];
    }
    $sql_grand =  " SELECT SUM(cur_subtot) AS tot FROM tmp_inv_data where tmp_no='" . $_POST["tmp_uniq"] ."'   ";
    $result_grand = $conn->query($sql_grand);
    if ($row_grand = $result_grand->fetch()) {

        $paid_grand_total = $row_grand['tot'];
        $paid_grand_total=$paid_grand_total+$paid_grand_total*$_POST['cardfee']/100;

    }

    $sql_disvalue =  " SELECT SUM(cur_discount) AS dis_tot FROM tmp_inv_data where tmp_no='" . $_POST["tmp_uniq"] ."' ";
    $result_disvalue = $conn->query($sql_disvalue);
    if ($row_disvalue = $result_disvalue->fetch()) {

        $paid_discount_total= $row_disvalue['dis_tot'];;
    }

    $paid_balance =  $paid_amount_sum - $paid_grand_total;

    if($paid_balance < 0){
        $paid_balance=0;
    }

    $ResponseXML .= "<summary><![CDATA[<table class=\"table table-bordered\">";


    $ResponseXML .= "<tr>
                      <td>Sub Total </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_itemtot'>" . number_format($paid_grand_total,2) . "</td>
                    </tr>
                    <tr>
                      <td>Discount </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_itemdis'>" .  number_format($paid_discount_total,2). "</td>
                    </tr>";

    if ($_POST['regi_vat_type'] != "Non Vat") {
        $ResponseXML .= "<tr>
                           <td>VAT </td>
                       <td style='text-align: right;  font-weight: bold;' id='model_all_itemtot'>0.00</td>
                       </tr>";
    }

    $ResponseXML .= "<tr>
                      <td>Grand Total </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_grand_total'>" . number_format($paid_grand_total,2) . "</td>
                    </tr>
                    <tr>
                     <td>Paid </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_paid'>" . number_format($paid_amount_sum,2) . "</td>
                    </tr>
                    <tr>
                     <td>Balance </td>
                      <td style='text-align: right;  font-weight: bold;' id='model_all_inv_balance'>" . number_format($paid_grand_total-$paid_amount_sum,2) . "</td>
                    </tr>
                    <tr>
                     <td>Over Payment </td>";

    if ($paid_balance > 0) {
        $ResponseXML .= " <td style='text-align: right;  font-weight: bold;' id='model_all_balance'>" . number_format($paid_balance,2) . "</td>
                        </tr>";
    }else{
        $ResponseXML .= " <td style='text-align: right;  font-weight: bold; color: red; ' id='model_all_balance'>" . number_format($paid_balance,2) . "</td>
                         </tr>";
    }


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

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

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


}

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

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

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

    $sql = "select * from view_vendor  where CAT<>'S' ";


    if ($_POST['c_refno'] != "") {
        $sql .= " and CODE like '%" . $_POST['c_refno'] . "%'";
    }
    if ($_POST['c_name'] != "") {
        $sql .= " and c_name like '%" . $_POST['c_name'] . "%'";
    }
    if ($_POST['c_add'] != "") {
        $sql .= " and c_add like '%" . $_POST['c_add'] . "%'";
    }
    if ($_POST['c_tel'] != "") {
        $sql .= " and c_tele like '%" . $_POST['c_tel'] . "%'";
    }
    if ($_POST['c_subcus'] != "") {
        $sql .= " and c_code like '%" . $_POST['c_subcus'] . "%'";
    }

    $sql .=" order by CODE desc limit 50 ";

    foreach ($conn->query($sql) as $row) {

        $cuscode = $row['c_code'];

        $text="";
        $color="";


        $ResponseXML .= "<tr >               
        <td onclick=\"custno3('$cuscode');\" style='text-align:center;width: 10%;'> " . $row['CODE'] . "</a></td>
        <td onclick=\"custno3('$cuscode');\" style='text-align:left;width: 30%;'>" . $row['c_name'] . "</a></td>
        <td onclick=\"custno3('$cuscode');\" style='text-align:left;width: 20%;'>" . $row['c_add'] . "</a></td>
        <td onclick=\"custno3('$cuscode');\" style='text-align:left;width: 20%;'>" . $row['c_tele'] . "</a></td>
        <td  onclick=\"custno3('$cuscode');\" style='text-align:left;width: 20%;'>" . $row['c_code'] . "</a></td>
        </tr>";

    }

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

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


if (isset($_POST["Command"]) && $_POST["Command"] == "search_item_search") {

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

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

    $sql = "select * from s_mas  where   STK_NO <> ''";


    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_NAME like '%" . $_POST['s_brand'] . "%'";
    }
    if ($_POST['s_partno'] != "") {
        $sql .= " and PART_NO like '%" . $_POST['s_partno'] . "%'";
    }
    if ($_POST['s_cat'] != "") {
        $sql .= " and Cat1 like '%" . $_POST['s_cat'] . "%'";
    }
    if ($_POST['s_list'] != "") {
        $sql .= " and SELLING like '%" . $_POST['s_list'] . "%'";
    }
    if ($_POST['s_cash'] != "") {
        $sql .= " and CA_SELLING like '%" . $_POST['s_cash'] . "%'";
    }
    if ($_POST['s_credit'] != "") {
        $sql .= " and CR_SELLING like '%" . $_POST['s_credit'] . "%'";
    }
    if ($_POST['s_qty'] != "") {
        $sql .= " and QTYINHAND like '%" . $_POST['s_qty'] . "%'";
    }
    if ($_POST['stkonly'] == "0") {
        $sql .= " and QTYINHAND > '0.00' ";
    }

    $sql .=" order by STK_NO desc limit 50";


$storeCodes = [];
$sqlStore = "SELECT CODE FROM s_stomas ORDER BY CODE";
foreach ($conn->query($sqlStore) as $storeRow) {
    $storeCodes[] = $storeRow['CODE'];
}


    foreach ($conn->query($sql) as $row) {

        $cuscode = $row['STK_NO'];

        $text="";
        $color="";
$qtyInHand = [];
    foreach ($storeCodes as $store) {
        $subSql = "SELECT QTYINHAND FROM s_submas WHERE STO_CODE = $store AND STK_NO = '$cuscode'";
        $result = $conn->query($subSql);
        $data = $result->fetch(PDO::FETCH_ASSOC);
         
        $qtyInHand[] = $data['QTYINHAND'];
    }
    


        $ResponseXML .= "<tr class='linehover'>         
        <td onclick=\"custno2('$cuscode');\" style='text-align:left;width: 8%;'> " . $row['STK_NO'] . "</a></td>
        <td onclick=\"custno2('$cuscode');\" style='text-align:left;width: 20%;;'>" . $row['DESCRIPT'] . "</a></td>
        <td onclick=\"custno2('$cuscode');\" style='text-align:left;width: 10%;'>" . $row['BRAND_NAME'] . "</a></td>
        <td onclick=\"custno2('$cuscode');\" style='text-align:left;width: 5%;'>" . $row['PART_NO'] . "</a></td>
        <td onclick=\"custno2('$cuscode');\" style='text-align:left;width: 5%;'>" . $row['Cat1'] . "</a></td>
        <td onclick=\"custno2('$cuscode');\" style='text-align:right;width: 6%;'>" . $row['SELLING'] . "</a></td> 
        <td onclick=\"custno2('$cuscode');\" style='text-align:right;width: 7%;'>" . $row['CA_SELLING'] . "</a></td> 
        <td onclick=\"custno2('$cuscode');\" style='text-align:right;width: 7%;'>" . $row['CR_SELLING'] . "</a></td>";
        
        
         foreach ($qtyInHand as $qty) {
        $ResponseXML .= "<td onclick=\"custno2('$cuscode');\" style='text-align:right; background-color:#e0b3db;width: 7%;'>" . $qty . "</td>";
    }

     $ResponseXML .= "</tr>";
        
         

    }

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

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