<?php
      if($_REQUEST['ajax']) {
        switch($_REQUEST['code']) {
            case "transno":
                if(RetRstField("SELECT fnid FROM txsales_invoice_hdr WHERE ftdo_no='{$_REQUEST['fttrans_no']}'")) {
                ?>
                    alert('No. transaksi sudah dipakai...\n System akan mengenerate No. transaksi kembali ...\n Silahkan ulangi proses penyimpanan...  ');
                    OnChangeDate_fdtrans_date();
                <?php
                }
                else {
                ?>
                    submitbutton('Simpan','','','','');
                <?php
                }
                die("");
                break;

            case "oum":
                $ssql="SELECT ftuom_code,ftstock_category_code FROM tlstock_hdr WHERE ftitem_code='{$_REQUEST['ftitem_code']}'";
                $rs=mysql_query( $ssql);
                $r=mysql_fetch_assoc($rs);
                ?>
                    document.getElementById('<?php echo $_REQUEST['ftuom_code']; ?>').value='<?php echo $r['ftuom_code']; ?>';
                    document.getElementById('<?php echo $_REQUEST['ftstock_category_code']; ?>').value='<?php echo $r['ftstock_category_code']; ?>';

                    var ObjSelect=document.getElementById('<?php echo $_REQUEST['ObjGudang']; ?>');

                    var len = ObjSelect.length;

                    for (var idx=0; idx < len; idx++)
                    {
                            if (ObjSelect.options[idx].value=='<?php echo $_SESSION['ftwarehouse_code']; ?>') {
                                ObjSelect.selectedIndex=idx;
                                break;
                            }
                    }
                <?php
                $ssql="SELECT ftlocation_code,ftlocation_name FROM tllocation WHERE ftwarehouse_code='{$_SESSION['ftwarehouse_code']}'";
                $rs=mysql_query($ssql);
                ?>

                    var ObjSelect=document.getElementById('<?php echo $_REQUEST['ObjLokasi']; ?>');

                    var len = ObjSelect.length;

                    for (var idx=0; idx < len; idx++)
                    {
                            if (ObjSelect.options[ObjSelect.length-1].value!='') {
                                  ObjSelect.remove(ObjSelect.length-1);
                            }
                    }
                <?php
                $i=0;
                while($r=mysql_fetch_assoc($rs)) {
                    $i++;
                    echo " try {
                                ObjSelect.add(new Option('{$r['ftlocation_code']}--{$r['ftlocation_name']}','{$r['ftlocation_code']}'),null,null);
                            } catch(ex) {
                                ObjSelect.add(new Option('{$r['ftlocation_code']}--{$r['ftlocation_name']}','{$r['ftlocation_code']}'),$i,$i);
                            } ";

                }
                ?>
                    var ObjSelect=document.getElementById('<?php echo $_REQUEST['ObjLokasi']; ?>');

                    var len = ObjSelect.length;

                    for (var idx=0; idx < len; idx++)
                    {
                            if (ObjSelect.options[idx].value=='<?php echo $_SESSION['ftlocation_code']; ?>') {
                                ObjSelect.selectedIndex=idx;
                                break;
                            }
                    }

                    var str1='query2.php?code=4&ftwarehouse_code=<?php echo $_SESSION['ftwarehouse_code']; ?>&ftlocation_code=<?php echo $_SESSION['ftlocation_code']; ?>&ftitem_code=<?php echo $_REQUEST['ftitem_code']; ?>&objQty=<?php echo $_REQUEST['objQty']; ?>';
                    ajax_do(str1);
                    <?php
                die("");
                break;

             case "formula":
                $ssql="SELECT IFNULL(SUM(ffformula),1) as ffformula
                        FROM tlstock_multi_det
                        WHERE ftitem_code='{$_REQUEST['ftitem_code']}'
                        and ftuom_code_multi='{$_REQUEST['ftuom_code']}'
                        ";

                $ffformula=RetRstField($ssql);
                if ($ffformula==0) { $ffformula=1; };
                
                $ffQtyMulti=(double)$ffformula*(double)CCur($_REQUEST['fnqty']);
                ?>
                        document.getElementById('ffformulaD0<?php echo $_REQUEST['index']; ?>').value='<?php echo $ffformula; ?>';
                        document.getElementById('fnqty_baseD0<?php echo $_REQUEST['index']; ?>').value='<?php echo $ffQtyMulti; ?>';
                <?php

                die("");
            break;

            case "customer":
                
                $ssql = "SELECT ftso_no, fdtrans_date FROM txsales_order_hdr
                            WHERE fnstatus <> 0 AND fnstatus <> 3 and fnstatus <> 5 and fnstatus <> 9 and fnreceive_status <> 3
                                    AND ftcustomer_code = '{$_REQUEST['ftcustomer_code']}'
                            ORDER BY ftso_no ";
                $rs=mysql_query($ssql);
                ?>

                    var ObjSelect=document.getElementById('<?php echo $_REQUEST['ObjLokasi']; ?>');

                    var len = ObjSelect.length;

                    for (var idx=0; idx < len; idx++)
                    {
                            if (ObjSelect.options[ObjSelect.length-1].value!='') {
                                  ObjSelect.remove(ObjSelect.length-1);
                            }
                    }
                <?php
                $i=0;
                while($r=mysql_fetch_assoc($rs)) {
                    $i++;
                    echo " try {
                                ObjSelect.add(new Option('{$r['ftso_no']}--{$r['fdtrans_date']}','{$r['ftso_no']}'),null,null);
                            } catch(ex) {
                                ObjSelect.add(new Option('{$r['ftso_no']}--{$r['fdtrans_date']}','{$r['ftso_no']}'),$i,$i);
                            } ";
                }

                ?>
                    ajax_do('query2.php?code=611&ftcustomer_code=' + document.getElementById('ftcustomer_code').value + '&ftdo_type=' + document.getElementById('ftdo_type').value + '&objAddress=ftship_address');
                <?php

                die("");
            break;
        }
        
    }

    // Getsecurity('delivery_order_monitor');

    // filter warehouse code based on login user
    $ftwarehouse_code = RetRstField("Select ifnull(ftwarehouse_code,'') FROM tluser WHERE ftusername = '{$_SESSION['username']}' ");
    if ($ftwarehouse_code != "") { 
        $str_warehouse = explode(",", $ftwarehouse_code);
        $sql_where = "''";

        foreach($str_warehouse as $item) {
            $sql_where = $sql_where . ",'{$item}'";
        }
        $sql_where = " AND d.ftwarehouse_code IN ({$sql_where})";
    }
    
    $today_count = RetRstField("SELECT COUNT(DISTINCT a.ftsales_invoice_no) AS counter FROM `txsales_invoice_hdr` `A` INNER JOIN txsales_invoice_det d ON a.ftsales_invoice_no = d.ftsales_invoice_no 
                                WHERE a.fnstatus !=3 AND a.fnstatus != 9  AND DATE_FORMAT(a.fdtrans_date,'%Y%m%d') = DATE_FORMAT(now(), '%Y%m%d')
                                      {$sql_where} GROUP BY a.fdtrans_date ");
    if ($today_count == "") $today_count = 0;                                          
                                        
    $objAxpDB->ViewName("Daftar Sales Invoice Monitor ( Total Transaksi Hari Ini = {$today_count} )");
    //$objAxpDB->ViewTable("vSADo");
    $objAxpDB->ViewSQL("SELECT DISTINCT A.fnid, A.fdtrans_date, A.ftsales_invoice_no, A.ftso_no, CONCAT(A.ftcustomer_code,' - ',e.ftcustomer_name) as ftcustomer_name, 
                            A.fcamount, B.fttrans_status_name
                        FROM txsales_invoice_hdr  A INNER JOIN tstransaction_status B ON a.fnstatus=b.fntrans_status_code AND B.fntrans_group_code=2
                        INNER JOIN tstransaction_status C ON a.fnpayment_status=C.fntrans_status_code AND C.fntrans_group_code=1
                        INNER JOIN txsales_invoice_det d ON a.ftsales_invoice_no = d.ftsales_invoice_no
                        INNER JOIN tlcustomer e ON a.ftcustomer_code = e.ftcustomer_code
                        WHERE  IFNULL(a.ftprint_counter,0) = 0 AND a.fnstatus !=3 AND a.fnstatus != 9 {$sql_where}
                        -- AND (('{$_SESSION['strbranch']}' <> 'PUSAT' AND a.ftbranch_code = '{$_SESSION['strbranch']}') OR '{$_SESSION['strbranch']}' = 'PUSAT')
                        ORDER BY ftsales_invoice_no");
    $objAxpDB->ViewCaption("ID, Tgl. Invoice, No. Invoice, No. Sales Order, Nama Customer, Total Invoice, Status");
    // $objAxpDB->ViewPeriod(TRUE);

    
    $objAxpDB->FormName("Sales Invoice Monitor");
    $objAxpDB->FormSQL("SELECT ftsales_invoice_no,  ftdo_no, ftcustomer_code, ftship_address, ftitem_type, fdtrans_date,  ftterm_payment, fddue_date, ftcurrency_code, fcrate, fntax_code,ftreff_no, fnpayment_status, fdvat_date, ftvat_no,ftnotes, fcpayment_amount, fcoutstanding_amount, fcsub_amount, ffdiscount, fcdiscount, fcother_cost, ffvat, fcvat, fcamount, fnstatus, fcreturn_amount FROM txsales_invoice_hdr");
    $objAxpDB->FormCaption("No. Invoice,  No. DO, Customer, Alamat, Tipe Invoice, Tgl. Invoice,  Syarat Pembayaran, Tgl. Jatuh Tempo, Mata Uang, Kurs, Kode Pajak, Referensi, Status Pembayaran,Tgl. Faktur Pajak, No. Faktur Pajak, Catatan, Jumlah Terbayar, Sisa Pembayaran,   Sub Total, Discount (%), Discount(Rp), Biaya Lain-lain, Pajak (%), Pajak (Rp), Grand Total, Status, Jumlah Retur");
    $objAxpDB->FormPosition("TL, TL, TL, TL, HD, TR, TR, TR, TR, TR, TR, TL, TL, TR, TR, BL, BL, BL, BR, BR, BR, BR, BR, BR, BR, BR, BL");
    
    $objAxpDB->FormScript(19, "onChange=\"SalesInvoiceRecalDiscPercent();\"");
    $objAxpDB->FormScript(20, "onChange=\"SalesInvoiceRecalDiscRp();\"");
    $objAxpDB->FormScript(21, "onChange=\"SalesInvoiceRecalQty0();\"");
    $objAxpDB->FormScript(22, "onChange=\"SalesInvoiceRecalQty0();\"");
    $objAxpDB->FormScript(10, "onChange=\"OnChangeDate_fdtrans_date();\"");
    $objAxpDB->FormScript(5, "onChange=\"{$ajax_due}\"");
    $objAxpDB->FormScript(6, "onChange=\"{$ajax_due}\"");    
    $objAxpDB->FormScript(8, "OnChange=\"{$ajaxKurs}\"");

    $objAxpDB->GridSQL(0, "SELECT fnindex, ftitem_code,fnqty, ftuom_code, fcprice, ffdiscount, fcdiscount, fcamount, fnqty_base, ffformula FROM txsales_invoice_det");
    $objAxpDB->GridCaption(0, "No., Kode Barang, Qty, Satuan, Harga, Disc(%), Disc(Rp), Jml Total, Qty Base, Formula");
    $objAxpDB->GridDelJS(0,"SalesInvoiceRecalQty0();");
    //$objAxpDB->GridSize(0, ",,5,5,10,5,5,10,,,");
      
    $objAxpDB->Lookup("ftcurrency_code", "SELECT  ftsimbol, ftdescription  FROM tlcurrency_hdr ORDER BY ftsimbol", "ftsimbol", "ftdescription", 0, True);
    $objAxpDB->Lookup("ftpayment_method", "SELECT fntrans_status_code, fttrans_status_name FROM tstransaction_status WHERE fntrans_group_code = 8", "fntrans_status_code", "fttrans_status_name", -1,true);
    $objAxpDB->Lookup("fnstatus", "SELECT fntrans_status_code, fttrans_status_name FROM tstransaction_status WHERE fntrans_group_code = 2", "fntrans_status_code", "fttrans_status_name", 1,true);
    $objAxpDB->Lookup("fntax_code", "SELECT fntrans_status_code, fttrans_status_name FROM tstransaction_status WHERE fntrans_group_code = 15", "fntrans_status_code", "fttrans_status_name", -1,true);
    $objAxpDB->Lookup("fnpayment_status", "SELECT fntrans_status_code, fttrans_status_name FROM tstransaction_status WHERE fntrans_group_code = 1", "fntrans_status_code", "fttrans_status_name", 1,true);
    $objAxpDB->Lookup("ftitem_code", "SELECT ftitem_code, ftitem_name FROM tlstock_hdr", "ftitem_code", "ftitem_name", -1,false);
    $objAxpDB->Lookup("ftitem_type","SELECT fntrans_status_code, fttrans_status_name FROM tstransaction_status WHERE fttrans_group_name='tipe barang invoice'","fntrans_status_code","fttrans_status_name",1,true);
    $objAxpDB->Lookup("ftcustomer_code","SELECT ftcustomer_code, ftcustomer_name FROM tlcustomer","ftcustomer_code","ftcustomer_name", -1,false);

    $objAxpDB->Lookup("ftcustomer_code", "SELECT ftcustomer_code, ftcustomer_name FROM tlcustomer ", "ftcustomer_code", "ftcustomer_name", -1,false);
    // $objAxpDB->Lookup("ftso_no", "SELECT ftso_no, fdtrans_date FROM txsales_order_hdr WHERE fnstatus <> 9", "ftso_no", "fdtrans_date", -1,false);
    $objAxpDB->Lookup("ftdelivery_method", "SELECT fntrans_status_code, fttrans_status_name FROM tstransaction_status WHERE fntrans_group_code = 7", "fntrans_status_code", "fttrans_status_name", -1,true);
    $objAxpDB->Lookup("fnstatus", "SELECT fntrans_status_code, fttrans_status_name FROM tstransaction_status WHERE fntrans_group_code = 2", "fntrans_status_code", "fttrans_status_name", 0,true);
    $objAxpDB->Lookup("ftdo_type", "SELECT fntrans_status_code, fttrans_status_name FROM tstransaction_status WHERE fntrans_group_code = 30", "fntrans_status_code", "fttrans_status_name", 0,true);
    $objAxpDB->Lookup("ftitem_code", "SELECT ftitem_code, ftitem_name FROM tlstock_hdr $m", "ftitem_code", "ftitem_name", -1,false);
    //$objAxpDB->Lookup("ftuom_code_so", "SELECT ftuom_code, ftuom_name FROM tluom", "ftuom_code", "ftuom_name", -1,true);

    if(!$_REQUEST['id']) {
        
        // $fnid = RetRstField("SELECT fnid FROM txdelivery_order_hdr WHERE IFNULL(ftprint_counter,0) = 0 ORDER BY fnid  LIMIT 1");
        $fnid = RetRstField("SELECT a.fnid FROM txsales_invoice_hdr a INNER JOIN txsales_invoice_det d ON a.ftsales_invoice_no = d.ftsales_invoice_no  
                             WHERE IFNULL(a.ftprint_counter,0) = 0 {$sql_where} GROUP BY a.ftsales_invoice_no, d.ftwarehouse_code ORDER BY a.fnid  LIMIT 1");
        $printsetting = "height=200,width=250,top=400,left=400,scrollbars=1,resizable=1,status=1,menubar=0";
        
        if($fnid) {
            $strScript= "   var printInvoiceWindow;
                            
                            if (printInvoiceWindow) printInvoiceWindow.close();
                            window.open('penjualan.php?form=print_penjualan&mode=edit&id=1&idd={$fnid}&m=salesinvoicemonitor', 'printInvoiceWindow', '{$printsetting}');
                            <!-- cache_clear(); -->    
                        ";      
                                
        }
        
        $strScript= $strScript . "  $(document).ready(function() {
                                        setInterval(function() {
                                          cache_clear();
                                        }, 120000); 
                                    });

                                    <!-- reload 2 menit -->
                                    
                                    function cache_clear() {
                                        <!--  window.location.reload(true); -->
                                        window.location.reload(); <!-- use this if you do not remove cache -->
                                    }
                                ";        
                
        $objAxpDB->FormJS($strScript); 

    // refresh qty available if status = draft
    /*} else if ($objAxpDB->GetStatus("fnstatus") == 0) {
          $strAutoNumber0=" var i=document.getElementsByName('fnindexD0[]').length;
                            for(var j=1;j < i;j++) {
                                vfnqty = ajax_do('query2.php?code=qty&ftwarehouse_code=' + document.getElementsByName('ftwarehouse_codeD0[]')[j].value + '&ftlocation_code=' + document.getElementsByName('ftlocation_codeD0[]')[j].value+'&ftitem_code=' + document.getElementsByName('ftitem_codeD0[]')[j].value+ '&objQty=fnqty_availableD0' + j);
                                document.getElementsByName('fnqty_availableD0[]')[j].value = vfnqty;
                            }

                            ";

          $objAxpDB->FormJS($strAutoNumber0);
          */
    }
    
    $objAxpDB->SetStatus("id, fnstatus");
    
    if ($objAxpDB->GetStatus("id") == "") {
            // $objAxpDB->ButtonShow("baru");
    /* } elseif ($objAxpDB->GetStatus("id") == 0) {
            $objAxpDB->FormLocked("0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1");
            $objAxpDB->GridLocked(0, "1, 0, 0, 0, 0, 1, 1, 1, 1, 1");
            $objAxpDB->GridHidden(0, "0, 0, 0, 0, 0, 1, 1, 0, 1, 1");
            $objAxpDB->GridAllowAddNew(0,true);
            $objAxpDB->GridAllowDelete(0,true);
            $objAxpDB->ButtonShow("reset, simpan, tutup"); */
    } elseif ($objAxpDB->GetStatus("fnstatus") == 1) {
            $objAxpDB->FormLocked("1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1");
            $objAxpDB->GridLocked(0, "1, 1, 1, 1, 1, 1, 1, 1, 1, 1");
            $objAxpDB->GridHidden(0, "0, 0, 0, 0, 0, 1, 1, 0, 1, 1");
            $objAxpDB->Lookup("ftcustomer_code", "SELECT ftcustomer_code, ftcustomer_name FROM tlcustomer", "ftcustomer_code", "ftcustomer_name", 1,false);
            $objAxpDB->ButtonShow("cetak, tutup");
    } elseif (($objAxpDB->GetStatus("fnstatus") == 3) OR ($objAxpDB->GetStatus("fnstatus") == 9)) {
            $objAxpDB->GridLocked(0, "1, 1, 1, 1, 1, 1, 1, 1, 1, 1");
            $objAxpDB->GridHidden(0, "0, 0, 0, 0, 0, 1, 1, 0, 1, 1");
            $objAxpDB->FormLocked("1, 1, 1, 1, 1, 1,  1,  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1, 1");
            $objAxpDB->ButtonShow("tutup");
    } 

    $objAxpDB->Process();

    $objAxpDB->WriteHtmlTable();
    
