<?php

session_start();

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

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

date_default_timezone_set('Asia/Colombo');

// Initialize ResponseXML for all cases
$ResponseXML = "";

/////////////////////////////////////// GetValue //////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Registration /////////////////////////////////////////////////////////////////////////

// Check if Command is set
$command = isset($_GET["Command"]) ? $_GET["Command"] : (isset($_POST["Command"]) ? $_POST["Command"] : '');

if ($command == "new_inv") {

    $_SESSION["print"] = 0;

    $sql = "Select ARN from invpara where flag='".$_SESSION['company']."'"; 

    $result = mysqli_query($GLOBALS['dbinv'], $sql);
    if ($result) {
        $row = mysqli_fetch_array($result);
        if ($row && isset($row["ARN"])) {
            $tmpinvno = "000000" . $row["ARN"];
            $lenth = strlen($tmpinvno);
            $invno = trim("".$_SESSION['company']."/ARN/ ") . substr($tmpinvno, $lenth - 6);
            $_SESSION["invno"] = $invno;
        } else {
            $invno = trim("".$_SESSION['company']."/ARN/ ") . "000001";
            $_SESSION["invno"] = $invno;
        }
    } else {
        $invno = trim("".$_SESSION['company']."/ARN/ ") . "000001";
        $_SESSION["invno"] = $invno;
    }

    $sql = "Select ARN from tmpinvpara where flag='".$_SESSION['company']."'"; 
    $result = mysqli_query($GLOBALS['dbinv'], $sql);
    if ($result) {
        $row = mysqli_fetch_array($result);
        if ($row && isset($row["ARN"])) {
            $_SESSION["tmp_no_arn"] = "".$_SESSION['company']."/ARN/" . $row["ARN"];
        } else {
            $_SESSION["tmp_no_arn"] = "".$_SESSION['company']."/ARN/1";
        }
    } else {
        $_SESSION["tmp_no_arn"] = "".$_SESSION['company']."/ARN/1";
    }

    if (isset($_SESSION["tmp_no_arn"])) {
        $sql1 = "delete from tmp_purord_data where tmp_no='" . $_SESSION["tmp_no_arn"] . "'";
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
    }

    $sql1 = "update tmpinvpara set ARN=ARN+1 where flag='".$_SESSION['company']."'"; 
    $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);

    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    $ResponseXML .= "<invno><![CDATA[" . $invno . "]]></invno>";
    $ResponseXML .= "<invdate><![CDATA[" . date('Y-m-d') . "]]></invdate>";
    $ResponseXML .= " </salesdetails>";
    echo $ResponseXML;
}

if ($command == "add_tmp") {

    $department = isset($_GET["department"]) ? $_GET["department"] : '';

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

    if (isset($_GET['itemcode']) && isset($_GET['invno'])) {
        $sql = "delete from tmp_purord_data where str_code='" . $_GET['itemcode'] . "' and str_invno='" . $_GET['invno'] . "' ";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
    }

    if (isset($_GET['qty'])) {
        $qty = str_replace(",", "", $_GET["qty"]);
    } else {
        $qty = 0;
    }

    if (isset($_GET['invno']) && isset($_GET['itemcode']) && isset($_GET['item']) && isset($_GET["partno"])) {
        $sql = "Insert into tmp_purord_data (str_invno, str_code, str_description, partno, qty)values 
                ('" . $_GET['invno'] . "', '" . $_GET['itemcode'] . "', '" . $_GET['item'] . "', '" . $_GET["partno"] . "', " . $qty . ") ";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
    }

    $ResponseXML .= "<sales_table><![CDATA[ <table><tr>
                              <td width=\"100\"  background=\"\" ><font color=\"#FFFFFF\">Code</font></td>
                              <td width=\"300\"  background=\"\"><font color=\"#FFFFFF\">Description</font></td>
                              <td width=\"100\"  background=\"\"><font color=\"#FFFFFF\">Part No</font></td>
                              <td width=\"100\"  background=\"\"><font color=\"#FFFFFF\">Qty</font></td>
                             
                            </tr>";

    if (isset($_GET['invno'])) {
        $sql = "Select * from tmp_purord_data where str_invno='" . $_GET['invno'] . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result) {
            while ($row = mysqli_fetch_array($result)) {
                $ResponseXML .= "<tr>                              
                                 <td  >" . $row['str_code'] . "</a></td>
                                 <td  >" . $row['str_description'] . "</a></td>
                                 <td  >" . $row['partno'] . "</a></td>
                                 <td  >" . number_format($row['qty'], 2, ".", ",") . "</a></td>
                                 <td  ><img src=\"images/delete_01.png\" width=\"20\" height=\"20\" id=" . $row['str_code'] . "  name=" . $row['str_code'] . " onClick=\"del_item('" . $row['str_code'] . "');\"></td></tr>";
            }
        }
    }

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

    echo $ResponseXML;
}

if ($command == "arn") {

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

    if (isset($_GET['invno'])) {
        $sql = "select * from s_ordmas where REFNO='" . $_GET['invno'] . "' ";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result && $row = mysqli_fetch_array($result)) {
            $ResponseXML .= "<REFNO><![CDATA[" . (isset($row['REFNO']) ? $row['REFNO'] : '') . "]]></REFNO>";
            $ResponseXML .= "<SDATE><![CDATA[" . (isset($row['SDATE']) ? $row['SDATE'] : '') . "]]></SDATE>";
            $ResponseXML .= "<SUP_CODE><![CDATA[" . (isset($row['SUP_CODE']) ? $row['SUP_CODE'] : '') . "]]></SUP_CODE>";
            $ResponseXML .= "<SUP_NAME><![CDATA[" . (isset($row['SUP_NAME']) ? $row['SUP_NAME'] : '') . "]]></SUP_NAME>";
            $ResponseXML .= "<REMARK><![CDATA[" . (isset($row['REMARK']) ? $row['REMARK'] : '') . "]]></REMARK>";
            $ResponseXML .= "<DEP_CODE><![CDATA[" . (isset($row['DEP_CODE']) ? $row['DEP_CODE'] : '') . "]]></DEP_CODE>";
            $ResponseXML .= "<DEP_NAME><![CDATA[" . (isset($row['DEP_NAME']) ? $row['DEP_NAME'] : '') . "]]></DEP_NAME>";
            $ResponseXML .= "<REP_CODE><![CDATA[" . (isset($row['REP_CODE']) ? $row['REP_CODE'] : '') . "]]></REP_CODE>";
            $ResponseXML .= "<REP_NAME><![CDATA[" . (isset($row['REP_NAME']) ? $row['REP_NAME'] : '') . "]]></REP_NAME>";
            $ResponseXML .= "<S_date><![CDATA[" . (isset($row['S_date']) ? $row['S_date'] : '') . "]]></S_date>";
            $ResponseXML .= "<LC_No><![CDATA[" . (isset($row['LC_No']) ? $row['LC_No'] : '') . "]]></LC_No>";
            $ResponseXML .= "<pi_no><![CDATA[" . (isset($row['pi_no']) ? $row['pi_no'] : '') . "]]></pi_no>";
            $ResponseXML .= "<blno><![CDATA[" . (isset($row['blno']) ? $row['blno'] : '') . "]]></blno>";
            $ResponseXML .= "<invno><![CDATA[" . (isset($row['invno']) ? $row['invno'] : '') . "]]></invno>";
            $ResponseXML .= "<Brand><![CDATA[" . (isset($row['Brand']) ? $row['Brand'] : '') . "]]></Brand>";
            $ResponseXML .= "<COUNTRY><![CDATA[" . (isset($row["COUNTRY"]) ? $row["COUNTRY"] : '') . "]]></COUNTRY>";
        }
    }

    $ResponseXML .= "<sales_table><![CDATA[ <table><tr>
                              <td width=\"200\"  background=\"\" ><font color=\"#FFFFFF\">Item Code</font></td>
                              <td width=\"900\"  background=\"\"><font color=\"#FFFFFF\">Description</font></td>
                              <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Order Qty</font></td>
                              <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Received Qty</font></td>
                              <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">FOB</font></td>
                              <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Actual Cost</font></td>
                               <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">List Price</font></td>
                                <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Margin (%)</font></td>
                                 <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Unit Total</font></td>
                            
                            </tr>";

    $mcou = 0;
    $totordqty = 0;
    $i = 1;
    
    if (isset($_GET['invno'])) {
        $sql = "Select count(*) as mcou from s_ordtrn where REFNO='" . $_GET['invno'] . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result && $row = mysqli_fetch_array($result)) {
            $mcou = isset($row["mcou"]) ? $row["mcou"] + 1 : 1;
        }

        $sql = "Select * from s_ordtrn where REFNO='" . $_GET['invno'] . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result) {
            while ($row = mysqli_fetch_array($result)) {

                $itemcode = "itemcode" . $i;
                $itemname = "itemname" . $i;
                $ord_qty = "ord_qty" . $i;
                $fob = "fob" . $i;
                $qty = "qty" . $i;
                $cost = "cost" . $i;
                $selling = "selling" . $i;
                $margin = "margin" . $i;
                $subtotal = "subtotal" . $i;

                $selling_value = 0;
                if (isset($row['STK_NO'])) {
                    $sql_selling = "select SELLING from s_mas where STK_NO='" . $row['STK_NO'] . "'";
                    $result_selling = mysqli_query($GLOBALS['dbinv'], $sql_selling);
                    if ($result_selling && $row_selling = mysqli_fetch_array($result_selling)) {
                        $selling_value = isset($row_selling['SELLING']) ? $row_selling['SELLING'] : 0;
                    }
                }

                $ResponseXML .= "<tr>                              
                                 <td><input style=\"text-align:center;\" type=\"text\" size=\"15\" name=" . $itemcode . " id=" . $itemcode . "   value=\"" . (isset($row['STK_NO']) ? $row['STK_NO'] : '') . "\" class=\"text_purchase3\" disabled=\"disabled\"/></td>
                                  <td ><input type=\"text\" size=\"15\" name=" . $itemname . " id=" . $itemname . "  value='" . (isset($row['DESCRIPT']) ? $row['DESCRIPT'] : '') . "' class=\"text_purchase3\" disabled=\"disabled\"/></td>
                                  <td ><input type=\"text\" style=\"text-align:right;\" size=\"15\" name=" . $ord_qty . " id=" . $ord_qty . "  value=\"" . (isset($row['ORD_QTY']) ? $row['ORD_QTY'] : 0) . "\" class=\"text_purchase3\" disabled=\"disabled\"/></td>
                                <td ><input type=\"text\" style=\"text-align:right;\" size=\"15\" name=" . $qty . " id=" . $qty . "  class=\"text_purchase3\" onBlur=\"cal_subtot('" . $i . "', '" . $mcou . "');\"/></td>
                                 
                                 <td ><input type=\"text\" style=\"text-align:right;\" size=\"15\" name=" . $fob . " id=" . $fob . "  class=\"text_purchase3\"/></td>
                                 <td ><input type=\"text\" style=\"text-align:right;\" size=\"15\" name=" . $cost . " id=" . $cost . "  class=\"text_purchase3\" onBlur=\"cal_subtot('" . $i . "', '" . $mcou . "');\"/></td>
                                 <td ><input type=\"text\" style=\"text-align:right;\" size=\"15\" name=" . $selling . " id=" . $selling . " onBlur=\"cal_margine('" . $i . "', '" . $mcou . "');\" value=\"" . $selling_value . "\"  class=\"text_purchase3\"/></td>
                                 <td ><input type=\"text\" style=\"text-align:right;\" size=\"15\" name=" . $margin . " id=" . $margin . "  class=\"text_purchase3\" disabled=\"disabled\"/></td>
                                 <td ><input type=\"text\" style=\"text-align:right;\" size=\"15\" name=" . $subtotal . " id=" . $subtotal . "  class=\"text_purchase3\" disabled=\"disabled\"/></td>
                                </tr>";
                $i = $i + 1;
                if (isset($row['ORD_QTY'])) {
                    $totordqty = $totordqty + $row['ORD_QTY'];
                }
            }
        }
    }

    $ResponseXML .= "   </table>]]></sales_table>";
    $ResponseXML .= "<count><![CDATA[" . $i . "]]></count>";
    $ResponseXML .= "<totordqty><![CDATA[" . $totordqty . "]]></totordqty>";
    $ResponseXML .= " </salesdetails>";

    echo $ResponseXML;
}

if ($command == "setord") {

    include_once ("connectioni.php");

    $len = strlen($_GET["salesord1"] ?? '');
    $need = substr(($_GET["salesord1"] ?? ''), $len - 7, $len);
    $salesord1 = trim("ORD/ ") . ($_GET["salesrep"] ?? '') . trim(" / ") . $need;

    $_SESSION["custno"] = $_GET['custno'] ?? '';
    $_SESSION["brand"] = $_GET["brand"] ?? '';
    $_SESSION["department"] = $_GET["department"] ?? '';

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

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

    $cuscode = $_GET["custno"] ?? '';
    $salesrep = $_GET["salesrep"] ?? '';
    $brand = $_GET["brand"] ?? '';

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

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

    if (!empty($cuscode) && !empty($salesrep) && !empty($InvClass)) {
        $sqloutinv = mysqli_query($GLOBALS['dbinv'], "select sum(GRAND_TOT-TOTPAY) as totout from view_s_salma where GRAND_TOT>TOTPAY and CANCELL='0' and C_CODE='" . trim($cuscode) . "' and SAL_EX='" . trim($salesrep) . "' and class='" . $InvClass . "'") or die(mysqli_error());
        if ($rowoutinv = mysqli_fetch_array($sqloutinv)) {
            if (isset($rowoutinv["totout"]) && !is_null($rowoutinv["totout"])) {
                $OutInvAmt = $rowoutinv["totout"];
            }
        }

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

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

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

        $pend_ret_set = 0;

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

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

        $ResponseXML .= "<sales_table_acc><![CDATA[ <table  bgcolor=\"#0000FF\" border=1  cellspacing=0>
                            <tr><td>Outstanding Invoice Amount</td><td>" . number_format($OutInvAmt, 2, ".", ",") . "</td></tr>
                             <td>Return Cheque Amount</td><td>" . number_format($OutREtAmt, 2, ".", ",") . "</td></tr>
                             <td>Pending Cheque Amount</td><td>" . number_format($OutpDAMT, 2, ".", ",") . "</td></tr>
                             <td>PSD Cheque Settlments</td><td>" . number_format($pend_ret_set, 2, ".", ",") . "</td></tr>
                             <td>Total</td><td>" . number_format($OutInvAmt + $OutREtAmt + $OutpDAMT + $pend_ret_set, 2, ".", ",") . "</td></tr>
                             </table></table>]]></sales_table_acc>";

        $sqlbr_trn = mysqli_query($GLOBALS['dbinv'], "select * from br_trn where Rep='" . trim($salesrep) . "' and brand='" . trim($InvClass) . "' and cus_code='" . trim($cuscode) . "'") or die(mysqli_error());
        if ($rowbr_trn = mysqli_fetch_array($sqlbr_trn)) {
            $crLmt = (isset($rowbr_trn["credit_lim"]) && !is_null($rowbr_trn["credit_lim"])) ? $rowbr_trn["credit_lim"] : 0;
            $tmpLmt = (isset($rowbr_trn["tmpLmt"]) && !is_null($rowbr_trn["tmpLmt"])) ? $rowbr_trn["tmpLmt"] : 0;

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

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

if ($command == "del_item") {

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

    if (isset($_GET['code']) && isset($_GET['invno'])) {
        $sql = "delete from tmp_purord_data where str_code='" . $_GET['code'] . "' and str_invno='" . $_GET['invno'] . "' ";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
    }

    $ResponseXML .= "<sales_table><![CDATA[ <table><tr>
                              <td width=\"100\"  background=\"\" ><font color=\"#FFFFFF\">Item Code</font></td>
                              <td width=\"300\"  background=\"\"><font color=\"#FFFFFF\">Description</font></td>
                              <td width=\"100\"  background=\"\"><font color=\"#FFFFFF\">Part No</font></td>
                              <td width=\"100\"  background=\"\"><font color=\"#FFFFFF\">Qty</font></td>
                            </tr>";

    if (isset($_GET['invno'])) {
        $sql = "Select * from tmp_purord_data where str_invno='" . $_GET['invno'] . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result) {
            while ($row = mysqli_fetch_array($result)) {
                $ResponseXML .= "<tr>                              
                                 <td  >" . (isset($row['str_code']) ? $row['str_code'] : '') . "</a></td>
                                 <td  >" . (isset($row['str_description']) ? $row['str_description'] : '') . "</a></td>
                                 <td  >" . (isset($row['partno']) ? $row['partno'] : '') . "</a></td>
                                 <td  >" . (isset($row['qty']) ? $row['qty'] : '') . "</a></td>
                                 <td  ><img src=\"images/delete_01.png\" width=\"20\" height=\"20\" id=" . (isset($row['str_code']) ? $row['str_code'] : '') . "  name=" . (isset($row['str_code']) ? $row['str_code'] : '') . " onClick=\"del_item('" . (isset($row['str_code']) ? $row['str_code'] : '') . "');\"></td></tr>";
            }
        }
    }

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

    echo $ResponseXML;
}

if ($command == "update_arstat") {

    if (isset($_GET['arpend']) && isset($_GET['refno'])) {
        $sql = "update s_trn set seri_no='" . $_GET['arpend'] . "' where refno = '" . $_GET['refno'] . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        echo "Updated";
    } else {
        echo "Error: Missing parameters";
    }
}

// FIXED: Check if POST Command exists before accessing
if (isset($_POST["Command"]) && $_POST["Command"] == "save_item") {
    if (!isset($_SESSION['dev']) || $_SESSION['dev'] == "") {
        exit("logout");
    }

    if (isset($_POST["count"]) && $_POST["count"] > 0) {

        $sql_invpara = "SELECT * from invpara where flag='".$_SESSION['company']."'"; 
        $result_invpara = mysqli_query($GLOBALS['dbinv'], $sql_invpara);
        $row_invpara = mysqli_fetch_array($result_invpara);
        
        $sql_vat = "SELECT * from vatrate where sdate<='" . $_POST["invdate"] . "' order by sdate desc";
        $result_vat = mysqli_query($GLOBALS['dbinv'], $sql_vat);
        $row_vat = mysqli_fetch_array($result_vat);

        $vatrate = isset($row_vat["vatrate"]) ? $row_vat["vatrate"] : 0;

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

        $_SESSION["CURRENT_DOC"] = 1;
        $_SESSION["VIEW_DOC"] = false;
        $_SESSION["FEED_DOC"] = true;
        $_GET["MOD_DOC"] = false;
        $_GET["PRINT_DOC"] = false;
        $_GET["PRICE_EDIT"] = false;
        $_GET["CHECK_USER"] = false;

        $sql = "select * from s_purmas where REFNO='" . $_POST["invno"] . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result && $row = mysqli_fetch_array($result)) {
            exit("AR Number Already Exists");
        } else {

            mysqli_query($GLOBALS['dbinv'], "SET AUTOCOMMIT=0");
            mysqli_query($GLOBALS['dbinv'], "START TRANSACTION");
            
            $sqlrep = "select * from s_salrep where REPCODE = '" . $_POST["salesrep"] . "'";
            $resultrep = mysqli_query($GLOBALS['dbinv'], $sqlrep);
            if ($resultrep && $rowrep = mysqli_fetch_array($resultrep)) {
                $maindepart = isset($rowrep['RGROUP1']) ? $rowrep['RGROUP1'] : "";
            } else {
                $maindepart = "";
            }

            $sql_status = 0;

            $sql1 = "insert into c_bal(REFNO, SDATE, CUSCODE, AMOUNT, BALANCE, DEP, SAL_EX, Cancell, brand, DEV, trn_type, vatrate, old, flag1, active, totpay,maindepartment,sdate1,c_code1,company) values ('" . $_POST["invno"] . "', '" . $_POST["invdate"] . "', '" . $_POST["supplier_code"] . "', '" . $_POST["total_value"] . "', '" . $_POST["total_value"] . "', '" . $_POST["department"] . "', '" . $_POST["salesrep"] . "', '0', '" . $_POST["brand"] . "', '" . $_SESSION['dev'] . "', 'ARN', '" . $vatrate . "', '0', 0, 1, 0,'".$maindepart."','" . $_POST["invdate"] . "','" . $_POST["supplier_code"] . "','".$_SESSION['company']."')";
            $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
            if ($result1 != 1) {
                $sql_status = 1;
            }

            $sql1 = "insert into s_sttr_all(ST_REFNO, ST_DATE, ST_INVONO, ST_PAID, balance, netamount, cus_code, cusname, DEV, del_days, deliin_days, deliin_amo, deliin_lock, department, form_type, trn_type) values
          ('" . $_POST["invno"] . "', '" . $_POST["invdate"] . "', '" . $_POST["invno"] . "', " . $_POST["total_value"] . ", " . $_POST["total_value"] . ", " . (-1 * $_POST["total_value"]) . ", '" . $_POST["supplier_code"] . "', '" . $_POST["supplier_name"] . "', '" . $_SESSION['dev'] . "', 0, 0, 0, '0', 'O', 'ARN', 'OVER')";
            $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
            if ($result1 != 1) {
                $sql_status = 2;
            }

            $sql1 = "insert into s_purmas(REFNO, SDATE, ORDNO, LCNO, pi_no, COUNTRY, SUP_CODE, SUP_NAME, REMARK, DEPARTMENT, AMOUNT, PUR_DATE, TYPE, brand, book_no, invno, blno, company, VAT, VAT_AMOUNT, SVAT_AMOUNT) values ('" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["invno"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["invdate"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["orderno1"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["lc_no"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["pi_no"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["country"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["supplier_code"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["supplier_name"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["textarea"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["department"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["total_value"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["dte_dor"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["purtype"]) . "', '" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["brand"]) . "','" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST['contsize']) . "','" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST['invno1']) . "','" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST['blno']) . "','" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_SESSION['company']) . "','" . 
                mysqli_real_escape_string($GLOBALS['dbinv'], $_POST['vatmethod']) . "','','')";
            $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
            if ($result1 != 1) {
                $sql_status = 3;
            }
        }

        $i = 1;
        $amou = 0;
        $count = isset($_POST["count"]) ? intval($_POST["count"]) : 0;
        
        while ($i < $count) {
        $itemcode_name = "itemcode" . $i;
        $itemname_name = "itemname" . $i;
        $ord_qty_name = "ord_qty" . $i;
        $fob_name = "fob" . $i;
        $qty_name = "qty" . $i;
        $cost_name = "cost" . $i;
        $selling_name = "selling" . $i;
        $margin_name = "margin" . $i;
        $subtotal_name = "subtotal" . $i;

        $QTYINHAND = 0;
        $cost = 0;
        $acc_cost = 0;
        $acc_cost_c = 0;
        $m_qty = 0;
        $m_totval = 0;
        $COST_mas = 0;

        // Ensure numeric values are properly formatted
        $qty_value = isset($_POST[$qty_name]) ? floatval(str_replace(",", "", $_POST[$qty_name])) : 0;
        $cost_value = isset($_POST[$cost_name]) ? floatval(str_replace(",", "", $_POST[$cost_name])) : 0;
        $ord_qty_value = isset($_POST[$ord_qty_name]) ? floatval(str_replace(",", "", $_POST[$ord_qty_name])) : 0;
        $fob_value = isset($_POST[$fob_name]) ? floatval(str_replace(",", "", $_POST[$fob_name])) : 0;
        $selling_value = isset($_POST[$selling_name]) ? floatval(str_replace(",", "", $_POST[$selling_name])) : 0;
        $margin_value = isset($_POST[$margin_name]) ? floatval(str_replace(",", "", $_POST[$margin_name])) : 0;

        if ($qty_value > 0) {
            $cost = $cost_value;
            $acc_cost = $cost_value;

            if (isset($_POST[$itemcode_name])) {
                $sql = "SELECT * FROM s_mas WHERE STK_NO='" . mysqli_real_escape_string($GLOBALS['dbinv'], $_POST[$itemcode_name]) . "'";
                $result = mysqli_query($GLOBALS['dbinv'], $sql);
                if ($result && $row = mysqli_fetch_array($result)) {
                    $QTYINHAND = isset($row["QTYINHAND"]) ? floatval($row["QTYINHAND"]) : 0;
                    $COST_mas = isset($row["COST"]) ? floatval($row["COST"]) : 0;
                    $acc_cost_c = isset($row["acc_cost"]) ? floatval($row["acc_cost"]) : 0;
                }
            }

            $m_qty = $QTYINHAND + $qty_value;

            if ($QTYINHAND > 0) {
                $m_totval = (($QTYINHAND * $acc_cost_c) + ($qty_value * $cost_value)) / $m_qty;
            } else {
                $m_totval = $cost_value;
            }
            if ($acc_cost_c < 1) {
                $m_totval = $cost_value;
            }

            if (isset($_POST[$itemcode_name]) && isset($_POST[$itemname_name])) {
                // FIXED: Proper INSERT statement with correct number of fields and values
                $sql1 = "INSERT INTO s_purtrn (
                    REFNO, SDATE, STK_NO, DESCRIPT, COST, MARGIN, SELLING, REC_QTY, FOB, DEPARTMENT, 
                    QTYINHAND, O_QTY, Cost_c, acc_cost, acc_cost_c, brand, vatrate, DISCOUNT, ret_qty, 
                    cost_seling, cost_margin, CANCEL, soldqty, days
                ) VALUES (
                    '" . mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["invno"]) . "', 
                    '" . mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["invdate"]) . "', 
                    '" . mysqli_real_escape_string($GLOBALS['dbinv'], $_POST[$itemcode_name]) . "', 
                    '" . mysqli_real_escape_string($GLOBALS['dbinv'], $_POST[$itemname_name]) . "', 
                    " . $cost . ", 
                    " . $margin_value . ", 
                    " . $selling_value . ", 
                    " . $qty_value . ", 
                    " . $fob_value . ", 
                    '" . mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["department"]) . "', 
                    " . $QTYINHAND . ", 
                    " . $ord_qty_value . ", 
                    " . $COST_mas . ", 
                    " . $acc_cost . ", 
                    " . $acc_cost_c . ", 
                    '" . mysqli_real_escape_string($GLOBALS['dbinv'], $_POST["brand"]) . "', 
                    " . $vatrate . ", 
                    0, 0, 0, 0, '0', '', 0
                )";
                $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
                if (!$result1) {
                    $sql_status = 4;
                    error_log("SQL Error in s_purtrn insert: " . mysqli_error($GLOBALS['dbinv']));
                }
            }

                if ($m_totval > 0) {
                    $marg = ((isset($_POST[$selling_name]) ? $_POST[$selling_name] : 0) - $m_totval) / $m_totval * 100;
                } else {
                    $marg = 0;
                }

                if (isset($_POST[$itemcode_name])) {
                    $sql1 = "update s_mas set COST=" . $m_totval . " where  STK_NO='" . $_POST[$itemcode_name] . "'";
                    $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
                    if ($result1 != 1) {
                        $sql_status = 5;
                    }
                }

                if (($m_totval > 0) && trim($m_totval) != "") {
                    $margin = ((isset($_POST[$selling_name]) ? $_POST[$selling_name] : 0) - $m_totval) / $m_totval * 100;
                } else {
                    $margin = 0;
                }
                    
                if (isset($_POST[$itemcode_name])) {
                    $sql22 = "Select sum(COST*REC_QTY) as totcost,STK_NO from s_purtrn where  STK_NO='" . $_POST[$itemcode_name] . "' and CANCEL='0'";   
                    $result22 = mysqli_query($GLOBALS['dbinv'], $sql22);
                    if ($result22 && $row22 = mysqli_fetch_array($result22)) {
                        $sql21 = "Select sum(REC_QTY) as qty from s_purtrn where  STK_NO='" . $_POST[$itemcode_name] . "' and CANCEL='0'";  
                        $result21 = mysqli_query($GLOBALS['dbinv'], $sql21);
                        if ($result21 && $row21 = mysqli_fetch_array($result21)) {
                            if (isset($row21['qty']) && $row21['qty'] > 0) {
                                $amou = (isset($row22['totcost']) ? $row22['totcost'] : 0) / $row21['qty'];
                            } else {
                                $amou = 0;
                            }
                        }
                    }

                    $sql1 = "update s_mas set COST1=" . $amou . ",acc_cost=" . $m_totval . ", SELLING='" . (isset($_POST[$selling_name]) ? $_POST[$selling_name] : 0) . "', AR_selling='" . (isset($_POST[$selling_name]) ? $_POST[$selling_name] : 0) . "', MARGIN ='" . $margin . "', QTYINHAND=QTYINHAND+" . $_POST[$qty_name] . " where  STK_NO='" . $_POST[$itemcode_name] . "'";
                    $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
                    if ($result1 != 1) {
                        $sql_status = 6;
                    }
                }

                if (isset($_POST[$itemcode_name]) && isset($_POST["department"])) {
                    $sql3 = "select * from s_submas where STK_NO='" . $_POST[$itemcode_name] . "' and STO_CODE='" . $_POST["department"] . "'";
                    $result3 = mysqli_query($GLOBALS['dbinv'], $sql3);
                    if ($result3 && $row3 = mysqli_fetch_array($result3)) {
                        $sql1 = "update s_submas set QTYINHAND=QTYINHAND+" . $_POST[$qty_name] . " where STK_NO='" . $_POST[$itemcode_name] . "' and STO_CODE='" . $_POST["department"] . "'";
                        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
                        if ($result1 != 1) {
                            $sql_status = 7;
                        }
                    } else {
                        $sql1 = "insert into s_submas(STO_CODE, STK_NO, DESCRIPt, OPENT_DATE, QTYINHAND) values ('" . $_POST["department"] . "', '" . $_POST[$itemcode_name] . "', '" . $_POST[$itemname_name] . "', '" . $_POST["invdate"] . "', " . $_POST[$qty_name] . " )";
                        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
                        if ($result1 != 1) {
                            $sql_status = 8;
                        }
                    }
                }

                if (isset($_POST["orderno1"])) {
                    $sql1 = "update s_ordmas set cancel='2' where REFNO='" . $_POST["orderno1"] . "'";
                    $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
                    if ($result1 != 1) {
                        $sql_status = 9;
                    }

                    $sql1 = "update s_ordtrn set rec_qty= rec_qty + '" . $_POST[$qty_name] . "',CANCEL='1' where REFNO='" . $_POST["orderno1"] . "'";
                    $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
                    if ($result1 != 1) {
                        $sql_status = 10;
                    }
                }

                if (isset($_POST[$itemcode_name]) && isset($_POST["invno"]) && isset($_POST["department"])) {
                    $sql1 = "insert into s_trn(STK_NO, SDATE, QTY, LEDINDI, REFNO, DEPARTMENT, seri_no, Dev, SAL_EX, ACTIVE, DONO,sdate1,COST,SELLING) values 
                    ('" . $_POST[$itemcode_name] . "', '" . $_POST["invdate"] . "', '" . $_POST[$qty_name] . "', 'ARN', '" . $_POST["invno"] . "', '" . $_POST["department"] . "', '" . (isset($_POST['arpend']) ? $_POST['arpend'] : '') . "', '" . $_SESSION['dev'] . "', '', '1', '','" . $_POST["invdate"] . "','" . $cost . "','" . (isset($_POST[$selling_name]) ? $_POST[$selling_name] : 0) . "')";
                    $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
                    if ($result1 != 1) {
                        $sql_status = 11;
                    }
                }
            }

            $i = $i + 1;
        }

        $sql1 = "update invpara set ARN=ARN+1 where flag='".$_SESSION['company']."'"; 
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
        if ($result1 != 1) {
            $sql_status = 13;
        }

        $sql2 = "insert into entry_log(refno, username, docname, trnType, stime, sdate) values ('" . trim($_POST["invno"]) . "', '" . $_SESSION["CURRENT_USER"] . "', 'ARN', 'Save', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
        $resul2 = mysqli_query($GLOBALS['dbinv'], $sql2);

        if ($sql_status == 0) {
            mysqli_query($GLOBALS['dbinv'], "COMMIT");
            echo "Saved";
        } else {
            mysqli_query($GLOBALS['dbinv'], "ROLLBACK");
            echo "Error -" . $sql_status;
        }
    } else {
        echo "no";
    }
}

if ($command == "pass_arnno") {
    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    
    if (isset($_GET['arnno'])) {
        $sql = "Select * from s_purmas where REFNO='" . $_GET['arnno'] . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result && $row = mysqli_fetch_array($result)) {
            $ResponseXML .= "<REFNO><![CDATA[" . (isset($row["REFNO"]) ? $row["REFNO"] : '') . "]]></REFNO>";
            $ResponseXML .= "<SDATE><![CDATA[" . (isset($row["SDATE"]) ? $row["SDATE"] : '') . "]]></SDATE>";
            $ResponseXML .= "<ORDNO><![CDATA[" . (isset($row["ORDNO"]) ? $row["ORDNO"] : '') . "]]></ORDNO>";
            $ResponseXML .= "<LCNO><![CDATA[" . (isset($row["LCNO"]) ? $row["LCNO"] : '') . "]]></LCNO>";
            $ResponseXML .= "<pi_no><![CDATA[" . (isset($row["pi_no"]) ? $row["pi_no"] : '') . "]]></pi_no>";
            $ResponseXML .= "<COUNTRY><![CDATA[" . (isset($row["COUNTRY"]) ? $row["COUNTRY"] : '') . "]]></COUNTRY>";
            $ResponseXML .= "<SUP_CODE><![CDATA[" . (isset($row["SUP_CODE"]) ? $row["SUP_CODE"] : '') . "]]></SUP_CODE>";
            $ResponseXML .= "<SUP_NAME><![CDATA[" . (isset($row["SUP_NAME"]) ? $row["SUP_NAME"] : '') . "]]></SUP_NAME>";
            $ResponseXML .= "<REMARK><![CDATA[" . (isset($row["REMARK"]) ? $row["REMARK"] : '') . "]]></REMARK>";
            $ResponseXML .= "<DEPARTMENT><![CDATA[" . (isset($row["DEPARTMENT"]) ? $row["DEPARTMENT"] : '') . "]]></DEPARTMENT>";
            $ResponseXML .= "<AMOUNT><![CDATA[" . (isset($row["AMOUNT"]) ? $row["AMOUNT"] : '') . "]]></AMOUNT>";
            $ResponseXML .= "<PUR_DATE><![CDATA[" . (isset($row["PUR_DATE"]) ? $row["PUR_DATE"] : '') . "]]></PUR_DATE>";
            $ResponseXML .= "<brand><![CDATA[" . (isset($row["brand"]) ? $row["brand"] : '') . "]]></brand>";
            $ResponseXML .= "<TYPE><![CDATA[" . (isset($row["TYPE"]) ? $row["TYPE"] : '') . "]]></TYPE>";
            $ResponseXML .= "<contsize><![CDATA[" . (isset($row["book_no"]) ? $row["book_no"] : '') . "]]></contsize>"; 
            $ResponseXML .= "<invno><![CDATA[" . (isset($row["invno"]) ? $row["invno"] : '') . "]]></invno>"; 
            $ResponseXML .= "<blno><![CDATA[" . (isset($row["blno"]) ? $row["blno"] : '') . "]]></blno>";  

            $ResponseXML .= "<sales_table><![CDATA[ <table><tr>
                                  <td width=\"200\"  background=\"\" ><font color=\"#FFFFFF\">Item Code</font></td>
                                  <td width=\"900\"  background=\"\"><font color=\"#FFFFFF\">Description</font></td>
                                  <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Order Qty</font></td>
                                  <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Received Qty</font></td>
                                  <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">FOB</font></td>
                                  <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Actual Cost</font></td>
                                   <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">List Price</font></td>
                                    <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Margin (%)</font></td>
                                     <td width=\"200\"  background=\"\"><font color=\"#FFFFFF\">Unit Total</font></td>
                                
                                </tr>";

            $mcou = 0;
            $sql = "Select count(*) as mcou from s_purtrn where REFNO='" . $_GET['arnno'] . "'";
            $result = mysqli_query($GLOBALS['dbinv'], $sql);
            if ($result && $row = mysqli_fetch_array($result)) {
                $mcou = isset($row["mcou"]) ? $row["mcou"] + 1 : 1;
            }

            $i = 1;
            $tot = 0;
            $totoqty = 0;
            $totrqty = 0;
            $subtot = 0;
            
            $sql = "Select * from s_purtrn where REFNO='" . $_GET['arnno'] . "'";
            $result = mysqli_query($GLOBALS['dbinv'], $sql);
            if ($result) {
                while ($row = mysqli_fetch_array($result)) {

                    $itemcode = "itemcode" . $i;
                    $itemname = "itemname" . $i;
                    $ord_qty = "ord_qty" . $i;
                    $fob = "fob" . $i;
                    $qty = "qty" . $i;
                    $cost = "cost" . $i;
                    $selling = "selling" . $i;
                    $margin = "margin" . $i;
                    $subtotal = "subtotal" . $i;

                    $rec_qty = isset($row['REC_QTY']) ? $row['REC_QTY'] : 0;
                    $cost_val = isset($row['COST']) ? $row['COST'] : 0;
                    $stot = $rec_qty * $cost_val;

                    $ResponseXML .= "<tr>                              
                                     <td   ><input type=\"text\" style=\"text-align:center;\" size=\"15\" name=" . $itemcode . " id=" . $itemcode . "   value='" . (isset($row['STK_NO']) ? $row['STK_NO'] : '') . "' class=\"text_purchase3\" disabled=\"disabled\"/></td>
                                      <td  ><input type=\"text\" disabled size=\"15\" name=" . $itemname . " id=" . $itemname . "  value='" . (isset($row['DESCRIPT']) ? $row['DESCRIPT'] : '') . "' class=\"text_purchase3\" disabled=\"disabled\"/></td>
                                      <td  ><input type=\"text\" disabled size=\"15\" name=" . $ord_qty . " id=" . $ord_qty . "  value='" . (isset($row['O_QTY']) ? $row['O_QTY'] : 0) . "' class=\"text_purchase3_right\" disabled=\"disabled\"/></td>
                                    <td  ><input type=\"text\" disabled size=\"15\" name=" . $qty . " id=" . $qty . " value='" . $rec_qty . "'  class=\"text_purchase3_right\" onBlur=\"cal_subtot('" . $i . "', '" . $mcou . "');\"/></td>
                                     
                                     <td  ><input type=\"text\" disabled size=\"15\" name=" . $fob . " id=" . $fob . " value='" . (isset($row['FOB']) ? $row['FOB'] : 0) . "'  class=\"text_purchase3_right\"/></td>
                                     <td  ><input type=\"text\" disabled size=\"15\" name=" . $cost . " id=" . $cost . " value='" . (isset($row['acc_cost']) ? $row['acc_cost'] : 0) . "'  class=\"text_purchase3_right\" onBlur=\"cal_subtot('" . $i . "', '" . $mcou . "');\"/></td>
                                     <td  ><input type=\"text\" disabled size=\"15\" name=" . $selling . " id=" . $selling . " value='" . (isset($row['SELLING']) ? $row['SELLING'] : 0) . "'  class=\"text_purchase3_right\"/></td>
                                     <td  ><input type=\"text\" disabled size=\"15\" name=" . $margin . " id=" . $margin . " value='" . (isset($margin_val) ? $margin_val : 0) . "'  class=\"text_purchase3_right\" disabled=\"disabled\"/></td>
                                     <td  ><input type=\"text\" disabled size=\"15\" name=" . $subtotal . " id=" . $subtotal . " value='" . $stot . "'  class=\"text_purchase3_right\" disabled=\"disabled\"/></td>
                                    </tr>";
                    $subtot = $subtot + $stot;
                    $i = $i + 1;
                    
                    $totoqty = $totoqty + (isset($row['O_QTY']) ? $row['O_QTY'] : 0);
                    $totrqty = $totrqty + (isset($row['REC_QTY']) ? $row['REC_QTY'] : 0);
                }
            }

            $sql = "select * from s_trn where refno = '" . $_GET['arnno'] . "' limit 1";
            $result = mysqli_query($GLOBALS['dbinv'], $sql);
            if ($result) {
                $row = mysqli_fetch_array($result);
                $ResponseXML .= "</table>]]></sales_table>";
                $ResponseXML .= "<arpend><![CDATA[" . (isset($row['seri_no']) ? $row['seri_no'] : '') . "]]></arpend>";
            } else {
                $ResponseXML .= "</table>]]></sales_table>";
                $ResponseXML .= "<arpend><![CDATA[]]></arpend>";
            }

            $ResponseXML .= "<tot><![CDATA[" . $tot . "]]></tot>";
            $ResponseXML .= "<totoqty><![CDATA[" . $totoqty . "]]></totoqty>";
            $ResponseXML .= "<totrqty><![CDATA[" . $totrqty . "]]></totrqty>";
            $ResponseXML .= "<count><![CDATA[" . $i . "]]></count>";
        }
    }

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

if ($command == "pass_arnno_gin") {
    header('Content-Type: text/xml');
    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    $ResponseXML = "";
    $ResponseXML .= "<salesdetails>";
    
    if (isset($_GET['arnno'])) {
        $sql = "Select * from s_purmas where REFNO='" . $_GET['arnno'] . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result && $row = mysqli_fetch_array($result)) {
            $ResponseXML .= "<REFNO><![CDATA[" . (isset($row["REFNO"]) ? $row["REFNO"] : '') . "]]></REFNO>";
            $ResponseXML .= "<SDATE><![CDATA[" . (isset($row["SDATE"]) ? $row["SDATE"] : '') . "]]></SDATE>";
        }
    }
    $ResponseXML .= "</salesdetails>";
    echo $ResponseXML;
}

if ($command == "cancel_inv") {

    $sql = "select * from s_purmas where CANCEL='0' order by id desc";
    $result = mysqli_query($GLOBALS['dbinv'], $sql);
    if ($result) {
        $row = mysqli_fetch_array($result);
    }

    $sql_status = 0;
    mysqli_query($GLOBALS['dbinv'], "SET AUTOCOMMIT=0");
    mysqli_query($GLOBALS['dbinv'], "START TRANSACTION");

    if (isset($_GET["invno"])) {
        $sql1 = "update s_purmas set CANCEL='1' where REFNO='" . $_GET["invno"] . "'";
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
        if ($result1 != 1) {
            $sql_status = 1;
        }

        $sql1 = "update s_purtrn set CANCEL='1' where REFNO='" . $_GET["invno"] . "'";
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
        if ($result1 != 1) {
            $sql_status = 2;
        }

        if (isset($_GET["orderno1"])) {
            $sql1 = "update s_ordmas set cancel='0' where REFNO='" . $_GET["orderno1"] . "'";
            $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
            if ($result1 != 1) {
                $sql_status = 3;
            }

            $sql1 = "update s_ordtrn set CANCEL='0' where REFNO='" . $_GET["orderno1"] . "'";
            $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
            if ($result1 != 1) {
                $sql_status = 4;
            }
        }

        $sql1 = "delete from s_trn  where REFNO='" . $_GET["invno"] . "'";
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
        if ($result1 != 1) {
            $sql_status = 5;
        }

        $sql1 = "delete from s_trn_all  where REFNO='" . $_GET["invno"] . "'";
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
        if ($result1 != 1) {
            $sql_status = 6;
        }

        $sql1 = "delete from c_bal where REFNO='" . $_GET["invno"] . "'";
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
        if ($result1 != 1) {
            $sql_status = 7;
        }

        $sql1 = "delete from s_sttr_all where ST_REFNO='" . $_GET["invno"] . "'";
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
        if ($result1 != 1) {
            $sql_status = 8;
        }
    }

    if (isset($_GET["invno"])) {
        $sql2 = "insert into entry_log(refno, username, docname, trnType, stime, sdate) values ('" . trim($_GET["invno"]) . "', '" . $_SESSION["CURRENT_USER"] . "', 'ARN', 'Delete', '" . date("Y-m-d H:i:s") . "', '" . date("Y-m-d") . "')";
        $resul2 = mysqli_query($GLOBALS['dbinv'], $sql2);
    }

    if (isset($_GET["invno"]) && isset($_GET["department"])) {
        $sql1 = "select * from s_purtrn where REFNO='" . $_GET["invno"] . "'";
        $result1 = mysqli_query($GLOBALS['dbinv'], $sql1);
        $amou = 0;
        if ($result1) {
            while ($row1 = mysqli_fetch_array($result1)) {
                
                if (isset($row1["STK_NO"])) {
                    $sql22 = "Select sum(COST*REC_QTY) as totcost,STK_NO from s_purtrn where  STK_NO='" . $row1["STK_NO"] . "' and CANCEL='0'";   
                    $result22 = mysqli_query($GLOBALS['dbinv'], $sql22);
                    if ($result22 && $row22 = mysqli_fetch_array($result22)) {
                        $sql21 = "Select sum(REC_QTY) as qty from s_purtrn where  STK_NO='" . $row1["STK_NO"] . "' and CANCEL='0'";  
                        $result21 = mysqli_query($GLOBALS['dbinv'], $sql21);
                        if ($result21 && $row21 = mysqli_fetch_array($result21)) {
                            if (isset($row21['qty']) && $row21['qty'] > 0) {
                                $amou = (isset($row22['totcost']) ? $row22['totcost'] : 0) / $row21['qty'];
                            } else {
                                $amou = 0;
                            }
                        }
                    }

                    $sql2 = "update s_mas set COST=" . (isset($row1["Cost_c"]) ? $row1["Cost_c"] : 0) . ",COST1='" . $amou . "', acc_cost=" . (isset($row1["acc_cost_c"]) ? $row1["acc_cost_c"] : 0) . " where STK_NO='" . $row1["STK_NO"] . "'";
                    $result2 = mysqli_query($GLOBALS['dbinv'], $sql2);
                    if ($result2 != 1) {
                        $sql_status = 9;
                    }

                    if (isset($row1["ORDNO"])) {
                        $sql2 = "update s_ordtrn set rec_qty= rec_qty - '" . (isset($row1["REC_QTY"]) ? $row1["REC_QTY"] : 0) . "' where REFNO='" . $row1["ORDNO"] . "'";
                        $result2 = mysqli_query($GLOBALS['dbinv'], $sql2);
                        if ($result2 != 1) {
                            $sql_status = 10;
                        }
                    }

                    $sql2 = "update s_submas set QTYINHAND=QTYINHAND-" . (isset($row1["REC_QTY"]) ? $row1["REC_QTY"] : 0) . " where STK_NO='" . $row1["STK_NO"] . "' and STO_CODE='" . $_GET["department"] . "'";
                    $result2 = mysqli_query($GLOBALS['dbinv'], $sql2);
                    if ($result2 != 1) {
                        $sql_status = 10;
                    }

                    $sql2 = "update s_mas set QTYINHAND=QTYINHAND-" . (isset($row1["REC_QTY"]) ? $row1["REC_QTY"] : 0) . " where STK_NO='" . $row1["STK_NO"] . "'";
                    $result2 = mysqli_query($GLOBALS['dbinv'], $sql2);
                    if ($result2 != 1) {
                        $sql_status = 11;
                    }
                }
            }
        }
    }

    if ($sql_status == 0) {
        mysqli_query($GLOBALS['dbinv'], "COMMIT");
        echo "Canceled!";
    } else {
        mysqli_query($GLOBALS['dbinv'], "ROLLBACK");
        echo "Error -" . $sql_status;
    }
}

if ($command == "check_print") {
    echo isset($_SESSION["print"]) ? $_SESSION["print"] : 0;
}

if ($command == "tmp_crelimit") {
    echo "abc";
    $crLmt = 0;
    $cat = "";

    $rep = trim(substr(isset($_GET["Com_rep1"]) ? $_GET["Com_rep1"] : '', 0, 5));

    if (isset($_GET["txt_cuscode"]) && isset($_GET["cmbbrand1"])) {
        $sql = "select * from br_trn where rep='" . $rep . "' and cus_code='" . trim($_GET["txt_cuscode"]) . "' and brand='" . trim($_GET["cmbbrand1"]) . "'";
        $result = mysqli_query($GLOBALS['dbinv'], $sql);
        if ($result && $row = mysqli_fetch_array($result)) {
            $crLmt = isset($row["credit_lim"]) ? $row["credit_lim"] : 0;
            if (isset($row["CAT"]) && !is_null($row["CAT"])) {
                $cat = trim($row["CAT"]);
            } else {
                $crLmt = 0;
            }
        }
    }
}
?>