<?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 $customerrCode;?><br>
            total Amount = <?php //echo number_format($totalAmount,2);?><br>-->
        </div>	
    </div>

</div>

<script type="text/javascript">
    var shortingText    = "";
    var rstTypeShorting = "ASC";
    var stringHTML      = "";
    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("","");
//        asem();
    });
    function asem(){
        alert("okeoke");
        var stringHTML = "<table></table>";
        stringHTML += "wahhh";
        $("#databox").html(stringHTML);
    }
    
    function search_detailAmount_invoices_outstanding(txtTable, txtFieldShorting) {//(namaVariableTabelDiModel, namaField)
        var url          = base_url + 'report/index_account_receivables/ajax_detailTotalAmountSalesOutstanding';
        var typeShorting = checkShorting(txtFieldShorting);
        var dataSend = {
            txt_customer      : "<?php echo $customerCode;?>",
            txtTable        : txtTable,
            txtField        : txtFieldShorting,
            typeShorting    : typeShorting
        };
        
        modal_open('Progress Bar','dlg_loading');
        $.post(url, dataSend).done(function (result) {
            var parseResult = JSON.parse(result);
            //console.log('parseResult= '+JSON.stringify(parseResult));
            var tempTotalAmount = 0, tempTotalFiscal = 0;
            var tempCode        = "";
            var arTempDatas     = [];   // temporer untuk menyimpan   
            var stringHTML      = "";   // untuk menyimpan yang akan ditampilkan ke layar
            
            stringHTML += "<table border='0' cellspacing='0' cellpadding='3' width='96%' align='center' class='tree-2' style='margin-bottom:30px;'>"
                    + "<tr>"
                    + "<td colspan='12' class='s0 text-center'><span class='normal_bold span_block ' ><small>" + parseResult.company + "</small></span></td>"
                    + "</tr>"
                    + "<tr>"
                    + "<td colspan='12' class='s0 text-center'><span class='normal_bold span_block ' ><small>" ;
                    parseResult.branch==undefined||parseResult.branch==""?stringHTML +="All Branch":stringHTML +=parseResult.branch ;
                    stringHTML += "</small></span></td>"
                    + "</tr>"
                    + "<tr>"
                    + "<td colspan='12' class='s1 text-center'><span class='normal_bold span_block ' ><small>Customer's Invoices (On Progress)</small></span></td>"
                    + "</tr>"
                    + "<tr><td colspan='12' class='s2 text-center'> As &nbsp;&nbsp; " + parseResult.enddate + "</td></tr>"
                    + "<tr>"
                    + "<td colspan='12' class='s1'>&nbsp;</td>"
                    + "</tr>";
            //=== JIKA DATA DITEMUKAN ========================================//
            if (parseResult.datas != 0) {
                // === LOOP PEMBACAAN DATA ===================================//
                parseResult.datas.forEach(function (dtResults) {
                    if(tempCode==""){//PEMBACAAN DATA PERTAMA KALI INVOICE
                        if(dtResults.CustomerCode!=null && dtResults.CustomerCode!="" && dtResults.CustomerCode!=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, "CustomerCode",dtResults.CustomerCode);//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.CustomerCode!=null && dtResults.CustomerCode!="" && dtResults.CustomerCode!=undefined){
                                var dataJSONLevel0 = arJSONLevel0(dtResults);
                                dataJSONLevel0!=0?arTempDatas.push(dataJSONLevel0):"";
                            }     
                        } 
                    }//end PEMBACAAN DATA UNTUK DATA PAYMENT
                    
                });// === END LOOP PEMBACAAN DATA ============================/  
                
                //===CARA BARU================================================================================================================//                
                var noTree = 1;               
                arTempDatas.forEach(function (arDataLevel_0) {//MULAI LOOP UNTUK DAPAT NAMA VENDOR
                    var noContentItem =1;                    
                    if(noTree>1 && noContentItem==1){
                        stringHTML+=tableHTMLFooterSummary(tempTotalAmount,tempTotalFiscal);//MEMBUAT FOOTER SUMARY PER SQ
                        tempTotalAmount     = 0;
                        tempTotalFiscal     = 0;
                    }
                                        
                    stringHTML+=tableHTMLHeader(arDataLevel_0);//membuat tabel header
                    var noUrutLevel_1 = 1;
                    arDataLevel_0['data'].forEach(function (arDataLevel_1) {//MULAI LOOP UNTUK DAPAT NAMA PURCHASE INVOICE
                        var parentLevel_1 = noTree;
                        stringHTML+=tableHTMLContentFirst(noTree,noUrutLevel_1,arDataLevel_1); 
                        //console.log("totalamaountSI="+arDataSI['PInvTotalAmount_PI']);
                        //=====pengisian nilai summary Footer===================//
                        tempTotalAmount      = ( tempTotalAmount* 1)+ ( arDataLevel_1['totalAmount']* 1);
                        tempTotalFiscal      = ( tempTotalFiscal* 1)+ ( arDataLevel_1['totalFiscal']* 1);
                        //=====end pengisian nilai summary Footer===================//                        
                        
                        noTree++;
                        noUrutLevel_1++;
                        noContentItem++;
                    });//END MULAI LOOP UNTUK DAPAT NAMA PURCHASE INVOICE
                });//END MULAI LOOP UNTUK DAPAT NAMA VENDOR
                //===END CARA BARU================================================================================================================//
                stringHTML+=tableHTMLFooterSummary(tempTotalAmount, tempTotalFiscal);
                //stringHTML+=tableHTMLFooterSummary(tempTotalQtyInv,tempTotalQtyRet,tempTotalDisc,tempTotalAmount);//MEMBUAT FOOTER SUMARY 
                stringHTML+="</table><script>"
                +"$(document).ready(function () {"
                +"    $('.tree-2').treegrid({"
                +"        expanderExpandedClass: ' treegrid-expander-expanded ',"
                +"        expanderCollapsedClass: 'treegrid-expander-collapsed'"
                +"    });"
                +"    $('.tree-2').treegrid('');"
                +"});"                
                +"</script"+">";
                //stringHTML+=summaryHTMLAll("ALL ITEM","left",arSumAll);//MEMBUAT  SUMARY ALL
                stringHTML+=stringLegend();
            }//=== END JIKA DATA DITEMUKAN ===================================//
            else{
                stringHTML+=tableHTMLNotFound();
            }
            //console.log("arTempDatas="+JSON.stringify(arTempDatas));
            $("#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 cekArraySummary(masterAr, cekName,cekValue){
        var checkIndexSumAll       = -1;
        var checkIndexArAll        = 0;
        masterAr.forEach(function (dtStatusAll) {//cek nilai status pada array statusAll ada ato tidak
            if (dtStatusAll[cekName] == cekValue) {
                checkIndexSumAll = checkIndexArAll;
                return checkIndexSumAll;
            }
            checkIndexArAll++;
        });
        return checkIndexSumAll;
    }

    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 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'>Total 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('Customers','list/customers', 'icon-edit', 'edit', '" + data.CustomerCode + "')\" <?=$cek_autority_edit?>><u><b>" + data.CustomerName + " </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('Sales Invoices','list/sales_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' >"+formatRp(data.totalAmount)+"</span></td>"
            + "<td width='' class='s5' align='right'><span class='small_bold' >"+formatRp(data.totalFiscal)+"</span></td>"
            + "<td width='' class='s5' align='right'><span class='small_bold' >" +data.TransStatus + "</span></td>"
            + "</tr>";
        }
        return strContent;
    }    
    function tableHTMLFooterSummary(TotalAmount,TotalFiscal){
        var amount      = TotalAmount>=0?TotalAmount:0;
        TotalFiscal>=0?TotalFiscal=TotalFiscal:TotalFiscal=0;
        var strFooter= "<tr>"
            + "<td class='s5' align='right' colspan='6'><hr class='hrTableSummary' style='size:3px;'></td></tr>"
            + "<tr><td class='s5' align='right' colspan='3'><b>TOTAL : </b></td>"
            + "<td width='' class='s5' align='right'><span class='small_bold' ><b>"+formatRp(amount)+"</b></span></td>"
            + "<td width='' class='s5' align='right'><span class='small_bold' ><b>"+formatRp(TotalFiscal)+"</b></span></td>"
            + "</tr>"
            + "<tr><td colspan='6'><span> </span></td></tr>"
        return strFooter;
    } 
    function tableHTMLFooter(){
        var strFooter= "<tr>"
            + "<td class='' align='right' colspan='6'><hr class='hrTableSummary'></td></tr>";
        return strFooter;
    }  
    
    function arJSONLevel0(dtResults){
        //console.log('dtResults = '+dtResults);
        var arData = 0;
        var tempData ={
            CustomerCode : dtResults.CustomerCode,
            CustomerName : dtResults.CustomerName,
            data :[]
        };        
        if(dtResults.Journal_Number!=null && dtResults.Journal_Number!="" && dtResults.Journal_Number!=undefined
            &&(dtResults.SInvNumber==null || dtResults.SInvNumber=="" || dtResults.SInvNumber==undefined)
        ){ // jika SInvNumber 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.SInvNumber==null || dtResults.SInvNumber=="" || dtResults.SInvNumber==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,  
                data : []
            };
        }else{
            tempData = 0;
        }            
        return tempData;
    }
    
    function stringLegend(){
        var strLgnd = {
            marginLeft:'2%',
            datas :[
                {boxColor:'#F4F4FF !important',strLabel:"Data Sales Invoices"},
                {boxColor:'',strLabel:"'Date' : Tanggal Transaksi."},
                {boxColor:'',strLabel:"'No.Transaction' : Nomor Transaksi."},
                {boxColor:'',strLabel:"'Amount' : Jumlah Nominal Invoice."},
                {boxColor:'',strLabel:"'Tax PPN 10%' : Jumlah Nominal dari Pajak PPN 10%."},
                {boxColor:'',strLabel:"'Status' : Status Transaksi Sales Invoices."}
            ]
        };
        var rst = legendsTable(strLgnd);
        return rst;
    }
</script>
