<?php
/* 	
 * Author   : Dhidhik / Tanggal : 24-11-2015	
 * note     : 
 * Revisi   : 
 */
//---------Untuk privellege Print and export excel ----------//
if (isset($group_user)) {
    if ($group_user->PrintPrivillage == 1) {
        $cek_autority_print = "";
    } else {
        $cek_autority_print = "disabled";
    }

    if ($group_user->ExcelPrivillage == 1) {
        $cek_autority_excel = "";
    } else {
        $cek_autority_excel = "disabled";
    }
    if ($group_user->EditPrivillage == 1) {
        $cek_autority_edit = "";
    } else {
        $cek_autority_edit = "disabled";
    }
} else {
    $cek_autority_print = "disabled";
    $cek_autority_excel = "disabled";
    $cek_autority_edit = "disabled";
}
//---------END Untuk privellege Print and export excel ----------//
?>
<!--<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>assets/custom/css/treetable/bootstrap.css">-->
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>assets/custom/css/treetable/jquery.treegrid.css">
<script type="text/javascript" src="<?= base_url() ?>assets/custom/js/treetable/jquery.treegrid.bootstrap3.js"></script>
<script type="text/javascript" src="<?= base_url() ?>assets/custom/js/treetable/jquery.treegrid.js"></script>
<style type="text/css">

    .margin-left5persen{
        margin-left:5%; 
    }
    .margin-right5persen{
        margin-right:5%; 
    }
    @media print {
        .noPrint { display: none; visibility: hidden; }
        .displayPrint{
            display: inline-block;
            left: 0px;
            position: fixed;
            background-color: white;
            width: 82%;
        }
        .layout-panel-west{display: none; visibility: hidden; }
        table{
            width: 100%;
        }       
    }
    /* style sheet for "A4" printing */
    @media print and (width: 21cm) and (height: 29.7cm) {
        @page {
            margin: 3cm;
        }
    }

    /* style sheet for "letter" printing */
    @media print and (width: 8.5in) and (height: 11in) {
        @page {
            margin: 1in;
        }
    }

    /* A4 Landscape*/
    @page {
        size: A4 landscape;
    }
</style>
<div id="cc" class="easyui-layout" data-options="fit:true, border:false">

    <div data-options="region:'center',border:false,iconCls:'icon-ok'">
        <div style="padding:2px" id="form-header">
            <a href="#" class="easyui-linkbutton noPrint" data-options="plain:true,iconCls:'icon-print'" onClick="window.print_detail()" <?= $cek_autority_print ?>>Print</a>
            &nbsp;&nbsp;           
            <a href="#" class="easyui-linkbutton noPrint" data-options="plain:true,iconCls:'icon-excel'" onclick="actionExcel()" <?= $cek_autority_excel ?>>Export File </a>
            &nbsp;&nbsp;           
            <a href="#" class="easyui-linkbutton noPrint" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload();">Refresh</a>
        </div><br />
        <div id="databox" class="displayPrint">
<!--            uri code = <?php //echo $vendorCode;   ?><br>
            total Amount = <?php //echo number_format($totalAmount,2);   ?><br>-->
        </div>	
    </div>

</div>

<script type="text/javascript">
    var shortingText = "";
    var rstTypeShorting = "ASC";
    var pre_url = base_url + 'report/index_account_payables/pre_ajax_detailTotalAmountPurchaseOutstanding';
    var url = base_url + 'report/index_account_payables/ajax_detailTotalAmountPurchaseOutstanding';
    var dataSend = {};
    var noTree = 1;
    var noUrutLevel_1 = 1;
    var stringHTML = "";
    var pages = {limit: limitRowInPage(), pages: 1};
    var tempArSumm = [];
    function variableDefault() {
        shortingText = "";
        rstTypeShorting = "ASC";
        dataSend = {};
        noTree = 1;
        noUrutLevel_1 = 1;
        stringHTML = "";
        pages['pages'] = 1;
        tempArSumm = [];
    }

    function checkShorting(txtCheckShorting) {
        if (shortingText == txtCheckShorting) {
            rstTypeShorting == "DESC" ? rstTypeShorting = "ASC" : rstTypeShorting = "DESC";
        } else {
            rstTypeShorting = "ASC";
            shortingText = txtCheckShorting;
        }
        //alert("cek="+txtCheckShorting+"-"+rstTypeShorting);
        return rstTypeShorting;
    }
    $(document).ready(function () {
        search_detailAmount_invoices_outstanding("", "");
    });

    function search_detailAmount_invoices_outstanding(txtTable, txtFieldShorting) {//(namaVariableTabelDiModel, namaField)
//        var url          = base_url + 'report/index_account_payables/ajax_detailTotalAmountPurchaseOutstanding';
        variableDefault();
        var typeShorting = checkShorting(txtFieldShorting);
        
        dataSend = {
            pages: pages,
            predata: [],
            cmb_company: "<?=$paramUrlCompanyCode; ?>",
            cmb_branch: "<?=$paramUrlBranchCode; ?>",
            txt_vendor: "<?=$paramUrlVendorCode; ?>",
            txt_DateTo: "<?=$paramUrlDateTo; ?>",
            txtTable: txtTable,
            txtField: txtFieldShorting,
            typeShorting: typeShorting,
            dataIn: "expandAll"
        };

        modal_open('Progress Bar', 'dlg_loading');
        $.post(pre_url, dataSend).done(function (pre_result) {//preAjax
            var preResult = JSON.parse(pre_result);
            //Array Pre_result diambil code nya saja
            var dataTopHeader = {
                CompanyName: preResult.company.CompanyName,
                BranchName: preResult.company.BranchName == undefined || preResult.company.BranchName == "" ? "All Branch" : preResult.company.BranchName,
                reportLabel: " Vendor's Invoices (On Progress) ",
                startdate: "<?=$paramUrlDateTo; ?>",
                enddate: preResult.enddate,
                colspan: 12
            };
            stringHTML += tableHTMLTopHeaderReport(dataTopHeader);//topHeader   

            if (preResult.datas != 0) {//jika pre ajax data ada 
                var pre_arData = [];
                preResult.datas.forEach(function (pre_dtResults) {//untuk mempersiapkan pre Array utk search
                    var pre_code = pre_dtResults['code'];
                    pre_arData.push(pre_code);
                });
                dataSend['predata'] = pre_arData;//isi preArray dengan value baru

                $.post(url, dataSend).done(function (result) {
                    var parseResult = JSON.parse(result);
                    var arTempDatas = [];   // temporer untuk menyimpan   

                    //=== JIKA DATA DITEMUKAN ========================================//
                    if (parseResult.datas != 0) {
                        //console.log("arTempDatas="+JSON.stringify(arTempDatas));
                        arTempDatas = prepareReport(parseResult);
                        stringHTML += createReport(arTempDatas);
                        pages['pages'] = (pages['pages'] * 1) + 1;
                    }//=== END JIKA DATA DITEMUKAN ===================================//
                    else {
                        stringHTML += tableHTMLNotFound();
                    }
                    //console.log("arTempDatas="+JSON.stringify(arTempDatas));
                    $("#databox").html(stringHTML);
                    modal_close('dlg_loading');
                }, 'json');
            } else {
                stringHTML += tableHTMLNotFound();
                $("#databox").html(stringHTML);
                modal_close('dlg_loading');
            }
        }, 'json');
    }

    function print_detail() {
        //var opt_print   = $("input[type='radio'][name='opt_print']:checked").val();
        var data_print = $("#databox").html();
        Popup(data_print);

    }
    function Popup(data) {
        var mywindow = window.open('', 'print-container', 'height=528,width=700');
        //var css = '<link rel="stylesheet" href="<?php echo base_url() ?>assets/custom/css/print.css" type="text/css" />';
        var varCSS = "<style>table{width: 100%;"
                + "font-family: 'Times New Roman';"
                + "font-size: small;"
                + "}"
                + ".thead{border:1px solid #333333;} .margin-left5persen{margin-left:0px;} .margin-right5persen{margin-right:0px;}"
                + ".table-summary{width:auto;}</style>";
        mywindow.document.write('<html><head><title>Print Detail</title>');
        mywindow.document.write(varCSS);
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10

        mywindow.print();
        mywindow.close();

        return true;
    }
    function actionExcel() {
        var htmls = "";
        var delRow = "";
        htmls = $('#databox').html();
        htmls = htmls.replace(/<table border='0' /gi, "<table border='1' ");
        htmls = htmls.replace(/<table border="0" /gi, "<table border='1' ");
        htmls = htmls.replace(/border='0'/gi, " ");
        htmls = htmls.replace(/'s0 text-center'/gi, "'s0 text-center' style='font-size:7;text-align: center;font-weight: bold;' ");
        htmls = htmls.replace(/'s1 text-center'/gi, "'s1 text-center' style='font-size:9;text-align: center;font-weight: bold;' ");
        htmls = htmls.replace(/'s2'/gi, "'s2' style='text-align: center;font-weight: bold;' ");
        htmls = htmls.replace(/id='tableHeader'/gi, " style='background-color:#d5d5d5;' ");
        htmls = htmls.replace(/<script/gi, " ");
        delRow = ">$(document).ready(function () {    $('.tree-2').treegrid({        expanderExpandedClass: ' treegrid-expander-expanded ',        expanderCollapsedClass: 'treegrid-expander-collapsed'    });    $('.tree-2').treegrid('";
        htmls = htmls.replace(delRow, " ");
        delRow = "collapseAll');});</";
        htmls = htmls.replace(delRow, " ");
        delRow = "expandAll');});</";
        htmls = htmls.replace(delRow, " ");
        htmls = htmls.replace(/script>/gi, " ");
        delRow = '';
        htmls = htmls.replace(/display: none;/gi, " ");

//        delRow="<tr>"
//            +"<td class='s5' align='right' colspan='6'><hr></td>"
//            +"</tr>";
//        htmls = htmls.replace(delRow, " ");
        //console.log("htmls = "+htmls);
        exportToExcel(htmls);
    }

    function prepareReport(parseResult) {
        var tempCode = "";
        var arTempDatas = [];
        // === LOOP PEMBACAAN DATA ===================================//
        parseResult.datas.forEach(function (dtResults) {
            if (tempCode == "") {//PEMBACAAN DATA PERTAMA KALI INVOICE
                if (dtResults.VendorCode != null && dtResults.VendorCode != "" && dtResults.VendorCode != undefined) {
                    tempCode = dtResults.Journal_Number;
                    var dataJSONLevel0 = arJSONLevel0(dtResults);
                    dataJSONLevel0 != 0 ? arTempDatas.push(dataJSONLevel0) : "";
                }
            }//END PEMBACAAN DATA PERTAMA KALI                    
            else {//PEMBACAAN DATA UNTUK DATA PAYMENT
                var indexCodeLevel_0 = cekArraySummary(arTempDatas, "VendorCode", dtResults.VendorCode);//mendapatkan index array VENDOR
                //console.log("indexCodeLevel_0="+indexCodeLevel_0);
                if (indexCodeLevel_0 > -1) {//jika VENDOR ditemukan data yg sama                            
                    var dataJSONLevel1 = arJSONLevel1(dtResults);
                    dataJSONLevel1 != 0 ? arTempDatas[indexCodeLevel_0]['data'].push(dataJSONLevel1) : "";
                } else {
                    if (dtResults.VendorCode != null && dtResults.VendorCode != "" && dtResults.VendorCode != undefined) {
                        var dataJSONLevel0 = arJSONLevel0(dtResults);
                        dataJSONLevel0 != 0 ? arTempDatas.push(dataJSONLevel0) : "";
                    }
                }
            }//end PEMBACAAN DATA UNTUK DATA PAYMENT

        });
        // === END LOOP PEMBACAAN DATA ============================/ 
        return arTempDatas;
    }
    function createReport(arTempDatas) {
        var tempStringHtml = "";
        tempStringHtml += createRowReport(arTempDatas);
        tempStringHtml += tableHTMLBlankForNext();
        tempStringHtml += "</table><script>"
                + "$(document).ready(function () {"
                + "    $('.tree-2').treegrid({"
                + "        expanderExpandedClass: ' treegrid-expander-expanded ',"
                + "        expanderCollapsedClass: 'treegrid-expander-collapsed'"
                + "    });"
                + "    $('.tree-2').treegrid('" + dataSend['dataIn'] + "');"
                + "});"
                + "</script" + ">";

//        tempStringHtml += summaryHTMLAll(" ALL ITEM ", "left", tempArSumm);
        tempStringHtml += stringLegend();
        return tempStringHtml;
    }
    function createRowReport(arTempDatas) {
        var tempStringHtml = "";
        //MULAI LOOP
        if(tempArSumm['footer']==undefined ||tempArSumm['footer']!='yes'){            
            tempArSumm = {
                footer:"yes",
                TotalAmount: 0,
                TotalFiscal: 0,
                CurrencySymbol: ""
            };
        }
        arTempDatas.forEach(function (arDataLevel_0) {//MULAI LOOP UNTUK DAPAT NAMA VENDOR
            pages['pages']<2?tempStringHtml += tableHTMLHeader(arDataLevel_0):"";//membuat tabel header
            arDataLevel_0['data'].forEach(function (arDataLevel_1) {//MULAI LOOP UNTUK DAPAT NAMA PURCHASE INVOICE
                var parentLevel_1 = noTree;
                tempStringHtml += tableHTMLContentFirst(noTree, noUrutLevel_1, arDataLevel_1);
                //=====pengisian nilai summary Footer===================//
                tempArSumm['TotalAmount'] = (tempArSumm['TotalAmount'] * 1) + (arDataLevel_1['totalAmount'] * 1);
                tempArSumm['TotalFiscal'] = (tempArSumm['TotalFiscal'] * 1) + (arDataLevel_1['totalFiscal'] * 1);
                tempArSumm['CurrencySymbol'] = arDataLevel_1['CurrencySymbol'];
                //=====end pengisian nilai summary Footer===================// 
                noTree++;
                noUrutLevel_1++;
            });//END MULAI LOOP UNTUK DAPAT NAMA PURCHASE INVOICE
        });
        //END MULAI LOOP
        tempStringHtml += tableHTMLFooterSummary(tempArSumm);//MEMBUAT FOOTER SUMARY 
        return tempStringHtml;
    }
    function seeMore() {
        modal_open('Progress Bar', 'dlg_loading');
        $.post(pre_url, dataSend).done(function (pre_result) {//preAjax
            var preResult = JSON.parse(pre_result);
            if (preResult.datas != 0) {//jika pre ajax data ada                 
                //Array Pre_result diambil code nya saja
                var pre_arData = [];
                preResult.datas.forEach(function (pre_dtResults) {
                    var pre_code = pre_dtResults['code'];
                    pre_arData.push(pre_code);
                });
                dataSend['predata'] = pre_arData;//isi preArray dengan value baru
                //End Array Pre_result diambil code nya saja

                var prearTempDatas = [];
                var pre_stringHTML = "";
                $.post(url, dataSend).done(function (result) {//loadAjax
                    var parseResult = JSON.parse(result);
                    if (parseResult.datas != 0) {
                        $("#footerSumAll_hr").replaceWith("");
                        $("#footerSumAll_row").replaceWith("");
                        prearTempDatas = prepareReport(parseResult);
                        pre_stringHTML += createRowReport(prearTempDatas);
                        pre_stringHTML += tableHTMLBlankForNext();

                        pages['pages'] = (pages['pages'] * 1) + 1;
                        $("#tr-see-more").replaceWith("");//clear row button 
                        $("#rowBlankForNext").replaceWith(pre_stringHTML);//mengganti row blank dengan ros data page baru
//                        $("#tableSumAll").replaceWith(summaryHTMLAll(" ALL ITEM ", "left", tempArSumm));
                        var htmlDataBox = $("#databox").html();//mengambil html pada div #databox yg data sudah baru
                        $("#databox").html(htmlDataBox);//mengisi kembali div #databox agar Tree-nya dapat work                      
                    } else {
                        $("#btn-see-more").prop("disabled", true);
                        $("#btn-see-more").val("Data Completed");
                    }
                    modal_close('dlg_loading');
                }, 'json');
            } else {
                $("#btn-see-more").prop("disabled", true);
                $("#btn-see-more").val("Data Completed");
                modal_close('dlg_loading');
            }
        }, 'json');
    }
    function tableHTMLNotFound() {
//        var strHeader = "<tr><td colspan='12' class='s3' align='left'><b><u>_____</u></b></td></tr>"
        var strHeader = "<tr id='tableHeader'>"//baris heading table
                + "<td width='' class='s4 text-left'><span class='small_bold' >No</span></td>"
                + "<td width='' class='s4 text-center'><span class='small_bold'>Date</span></td>"
                + "<td width='' class='s4 text-center'><span class='small_bold'>No.Transaction</span></td>"
                + "<td width='' class='s4 text-left'><span class='small_bold'>Amount</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Tax PPN 10%</span></td>"
                + "<td width='' class='s4 text-left'><span class='small_bold' >Status</span></td>"
                + "</tr>"
                + "<tr>"
                + "<td width='' class='s5 text-center' colspan='6' align='center'><span class='small_bold' >Data Not Found</span></td>"
                + "</tr></table>";
        return strHeader;
    }
    function tableHTMLHeader(data) {
        var strHeader = "<tr><td colspan='6'> </td></tr><tr><td colspan='6'> </td></tr>"
                + "<tr><td colspan='6' class='s3' align='left'><a class='linkParentTab' href='#'onclick=\"parent.tab_edit('Vendors','list/vendors', 'icon-edit', 'edit', '" + data.VendorCode + "')\" <?= $cek_autority_edit ?>><u><b>" + data.VendorName + " </b></u></a></td></tr>"
                + "<tr id='tableHeader'>"//baris heading table
                + "<td width='' class='s4'><span class='small_bold' >No</span></td>"
                + "<td width='80' class='s4 linkParentTab' style='cursor:pointer;' onclick=\"search_detailAmount_invoices_outstanding('avtrans_1','Journal_Date');\"><span class='small_bold'>Date</span></td>"
                + "<td width='' class='s4 linkParentTab' style='cursor:pointer;' onclick=\"search_detailAmount_invoices_outstanding('avtrans_1','Journal_Number');\"><span class='small_bold'>No.Transaction</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Amount</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Tax PPN 10%</span></td>"
                + "<td width='' class='s4 linkParentTab' align='right' style='cursor:pointer;' onclick=\"search_detailAmount_invoices_outstanding('avtrans_1','TransStatus');\"><span class='small_bold' >Status</span></td>"
                + "</tr>";
        return strHeader;
    }
    function tableHTMLContentFirst(noTree, noUrut, data) {
        strContent = "";
        if (data.Journal_Number != null && data.Journal_Number != "" && data.Journal_Number != undefined) {
            var strContent = "<tr class='treegrid-" + noTree + "' style='-webkit-print-color-adjust:exact;background-color:#F4F4FF;font-weight: bold;'>"
                    + "<td width='' class='s5'><span class='small_bold' >" + noUrut + "</span></td>"
                    + "<td width='' class='s5'><span class='small_bold' >" + data.Journal_Date + "</span></td>"
                    + "<td width='' class='s5'><span class='small_bold' ><a class='linkParentTab' href=\"#\" onclick=\"parent.tab_edit('Purchase Invoices','list/purchases_invoice', 'icon-edit', 'edit', '" + data.Journal_Number + "')\" <?= $cek_autority_edit ?>>" + data.Journal_Number + "</a></span></td>"
                    + "<td width='' class='s5' align='right'><span class='small_bold' >" + data.CurrencySymbol + " " + formatRp(data.totalAmount) + "</span></td>"
                    + "<td width='' class='s5' align='right'><span class='small_bold' >Rp. " + formatRp(data.totalFiscal) + "</span></td>"
                    + "<td width='' class='s5' align='right'><span class='small_bold' >" + data.TransStatus + "</span></td>"
                    + "</tr>";
        }
        return strContent;
    }
    function tableHTMLFooterSummary(data) {
        var strFooter = "<tr id='footerSumAll_hr'>"
                + "<td class='s5' align='right' colspan='6'><hr class='hrTableSummary' style='size:3px;'></td></tr>"
                + "<tr id='footerSumAll_row'><td class='s5' align='right' colspan='3'><b>TOTAL : </b></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold' ><b>" + data['CurrencySymbol'] + " " + formatRp(data['TotalAmount']) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold' ><b>Rp. " + formatRp(data['TotalFiscal']) + "</b></span></td>"
                + "</tr>";
        return strFooter;
    }
    function tableHTMLFooter() {
        var strFooter = "<tr>"
                + "<td class='' align='right' colspan='6'><hr class='hrTableSummary'></td></tr>";
        return strFooter;
    }
    function tableHTMLBlankForNext() {
        var strFooter = "<tr id='rowBlankForNext'>"
                + "<td class='s5' align='right' colspan='10'></td></tr>";
        strFooter += "<tr id='tr-see-more'><td colspan='5'><br><br><input id='btn-see-more' name='btn-see-more' type='button' onclick='seeMore()' value=' See More ' style='cursor:pointer;'></td></tr>";

        return strFooter;
    }

    function arJSONLevel0(dtResults) {
        //console.log('dtResults = '+dtResults);
        var arData = 0;
        var tempData = {
            VendorCode: dtResults.VendorCode,
            VendorName: dtResults.VendorName,
            data: []
        };
        if (dtResults.Journal_Number != null && dtResults.Journal_Number != "" && dtResults.Journal_Number != undefined
                && (dtResults.PInvNumber == null || dtResults.PInvNumber == "" || dtResults.PInvNumber == undefined)
                ) { // jika PInvNumber kosong, berarti data invoice 
            arData = arJSONLevel1(dtResults);
            tempData['data'].push(arData);
        }
        if (arData == 0) {
            tempData = 0;
        }
        return tempData;
    }
    function arJSONLevel1(dtResults) {//Data Invoice
        if ((dtResults.PInvNumber == null || dtResults.PInvNumber == "" || dtResults.PInvNumber == undefined) && dtResults.TransStatus == 1) {
            var tempData = {
                totalAmount: dtResults.totalAmount,
                totalFiscal: dtResults.totalFiscal,
                Journal_Date: dateSqlToIndo(dtResults.Journal_Date),
                Journal_Number: dtResults.Journal_Number,
                Sub_Type_Name: dtResults.Sub_Type_Name,
                Acc_Type_Name: dtResults.Acc_Type_Name,
                Amount_Currency: dtResults.Amount_Currency,
                CurrencyCode: dtResults.CurrencyCode,
                TransStatus: get_status(dtResults.TransStatus),
                BranchName: dtResults.BranchName,
                CompanyName: dtResults.CompanyName,
                CurrencySymbol: dtResults.CurrencySymbol,
                data: []
            };
        } else {
            tempData = 0;
        }
        return tempData;
    }
    function stringLegend() {
        var strLgnd = {
            marginLeft: '2%',
            datas: [
                {boxColor: '#F4F4FF !important', strLabel: "Data Purchase Invoices"},
                {boxColor: '', strLabel: "'Date' : Tanggal transaksi."},
                {boxColor: '', strLabel: "'No.Transaction' : Nomor transaksi."},
                {boxColor: '', strLabel: "'Amount' : Jumlah nominal tagihan pada transaksi invoices."},
                {boxColor: '', strLabel: "'Tax PPN 10%' : Pajak PPn 10%."},
                {boxColor: '', strLabel: "'Status' : Status transaksi invoices."}
            ]
        };
        var rst = legendsTable(strLgnd);
        return rst;
    }
</script>
