<?php if(empty($pageId)||$pageId<=1){?>
<div class="ui grid">
    <div class="row" >
        <div class="sixteen wide column">
            <div class="sixteen wide column m-b-15">
                <h3 class="ui header">Statements</h3>
            </div>
        </div>	
    </div>
</div>
<div class="ui grid">
    <div class="row" >
        <div class="eight wide computer sixteen wide mobile column"></div>
        <div class="four wide computer sixteen wide mobile column right aligned">
            <i onclick="printStatement();" title="Export To Pdf" class="big file pdf outline icon p-t-7 cp"></i>
        </div>
        <div class="four wide computer sixteen wide mobile column right floated f-r">
            <div class="ui orderby fluid selection search c-dateFilter dropdown">
                <input type="hidden" name="sortorder"  value="<?= $dateRange;?>">
                <input class="search"><div class="text" >This Fiscal Year</div>
                <i class="dropdown icon"></i>
                <div class="menu transition" tabindex="-1">
                    <div class='item' data-value="TO">Today</div>
                    <div class='item' data-value="YE">Yesterday</div>
                    <div class='item' data-value="TW">This Week</div>
                    <div class='item' data-value="LW">Last Week</div>
                    <div class='item' data-value="TM">This Month</div>
                    <div class='item' data-value="LM">Last Month</div>
                    <div class='item' data-value="TQ">This Quarter</div>
                    <div class='item' data-value="LQ">Last Quarter</div>
                    <div class='item' data-value="TFY">This Fiscal Year</div>
                    <div class='item' data-value="LFY">Last Fiscal Year</div>
                </div>
            </div>
        </div>	
    </div>    
    <div class="row p-r-2 statTbl" >
        <table class="ui unstackable sortable large table custom selectable f-s-14 c-statTbl">
            <thead>
                <tr>
                    <th data-value="['tDate']" class="left aligned">Date</th>
                    <th data-value="tType">Type</th>
                    <th data-value="id" class="left aligned">Trans No.</th>
                    <th data-value="ref" <?= $selTab=='P'?'class="hide"':'' ?>>Particulars</th>
                    <th data-value="dueDate" style="text-align: center;">Debit(<?= $currencysymbol?>)</th>
                    <th data-value="status" >Credit(<?= $currencysymbol?>)</th>
                    <th data-value="totAmount" class="t-a-r">Balance(<?= $currencysymbol?>)</th>
                </tr>
            </thead>
            <tbody>
            <?php 
                $availableBalance = (!empty($availableBalance))?$availableBalance:$statementDetail['balance']['open'];
                if(!empty($statementDetail['balance'])){
                    $statementDetail['balance']['totBalance']= ($statementDetail['balance']['tot_debit'] - $statementDetail['balance']['tot_credit']);
                }
                $statementDetail['balance']['negClose'] = false;
                if($statementDetail['balance']['close'] < 0) {	
					$statementDetail['balance']['close'] = -$statementDetail['balance']['close'];
					$statementDetail['balance']['negClose'] = true;
				}
                $statementDetail['isAoExists']=false;
                foreach($statementDetail['items'] as $item) {
                    if($item['tType'] == 'AO'){
                        $statementDetail['isAoExists']=true;
                    }
                }
                if(!$statementDetail['isAoExists']){
            ?> 
                    <tr>
                        <td><?= format_date($from_date) ?></td>
                        <td></td>
                        <td></td>
                        <td><?= $noRec ? 'By' : ''?> Opening balance</td>
                        <?php if($statementDetail['balance'] && $statementDetail['balance']['open']!=0){ ?>
                            <td class="right aligned" > 
                                <?= (!empty($statementDetail['balance']) && ($statementDetail['balance']['totBalance'] > 0)) ? ($statementDetail['balance']['open'] < 0 ? '(' . formatCurrency(abs($statementDetail['balance']['open']), $currency) . ')' : formatCurrency($statementDetail['balance']['open'], $currency)) : '0.00'; ?>
                            </td>
                            <td class="right aligned" ><?=  (!empty($statementDetail['balance']) && $statementDetail['balance']['totBalance'] < 0) ? (formatCurrency(abs($statementDetail['balance']['open']), $currency)) : '0.00' ?>
                            </td>
                        <?php } ?>
                        <?php if($statementDetail['balance'] && $statementDetail['balance']['open']==0){?>
                            <td class="right aligned">  <?= $statementDetail['balance'] && formatCurrency($statementDetail['balance']['totBalance'], $currency) ? "" : "0.00" ?></td>
                            <td class="right aligned"><?= $statementDetail['balance'] && formatCurrency($statementDetail['balance']['totBalance'], $currency) ? "0.00" : ""?></td>
                        <?php } ?>
                        <td class="right aligned"></td>
                    </tr>
                <?php } ?>
<?php } ?>
                <?php foreach($statementDetail['items'] as $item) {   
                    $availableBalance = $availableBalance + $item['debit'] -  $item['credit'] ;
                ?>
                    <tr class="keyNavigate">
                        <td><?=format_date( $item['tDate']) ?></td>
                        <td><?= $item['typeshortCode'] ?></td>
                        <td class="right aligned"><?= ($item['tType'] != 'AO') ? $item['tNo'] : "" ?></td>
                        <td class="wsn">
                            <?php if(!empty($item['tType']) &&!empty( (float)$item['debit'])){?>
                            <span>To </span>
                            <?php } if(!empty($item['tType']) && !empty( (float)$item['credit'])){?>
                            <span>By </span>
                            <?php } ?>
                            <b><?= $item['name']?></b>
                            
                            <?php if($item['particulars'] != 0){?>
                            <div class="wrappable">
                                <?= $item['particulars'] ?>
                            </div>
                            <?php } ?>
                        </td>
                        <td class="right aligned"><?= (!empty((float)$item['debit']))?formatCurrency((float)$item['debit'], $currency):''  ?></td>
                        <td class="right aligned"><?= (!empty((float)$item['credit']))?formatCurrency((float)$item['credit'], $currency):'' ?></td>
                        <td class="right aligned <?= ($availableBalance<0) ? 'sem_red' : '';?>" >
                            <?= formatCurrency(abs($availableBalance), $currency);?>
                            <span class="sem_gray" > <?= ($availableBalance > 0) ? 'Dr' : 'Cr'?></span>
                        </td>
                    </tr>
                    <?php } if((empty($pageId)||$pageId<=1) && (empty($statementDetail['items']) )){?>			
                    <tr > 
                        <td></td>
                        <td colspan="2">To Closing Balance</td>
                        <td></td>
                        <td class="right aligned"><?= $statementDetail['balance'] && $statementDetail['balance']['negClose']  ? '0.00' : ( formatCurrency($statementDetail['balance']['close'], $currency) )  ?></td>
                        <td class="right aligned"><?= $statementDetail['balance'] && $statementDetail['balance']['negClose'] ? ( formatCurrency($statementDetail['balance']['close'], $currency) ) : '0.00' ?></td>
                        <td></td>
                    </tr>

                    <?php } ?>		
                    <?php if((empty($pageId)||$pageId<=1) && (empty($statementDetail['items']) && !$noRec )){?>			
                        <tr>
                            <td colspan="7" class="center aligned ">
                                <?php if(!$noRec ){?>
                                <div class="horz loading"></div>
                                <?php } ?> 
                            </td>
                        </tr>
                    <?php } ?> 
<?php if(empty($pageId)||$pageId<=1){?>
            </tbody>
            <tfoot>
                
                    	
                <tr class="strong stickytr" >
                    <td colspan=3></td>
                    <td><b>Total</b><span class="f-s-11">&nbsp;as&nbsp;on&nbsp;<?= ($to_date > date('Y-m-d')) ? format_date(date('Y-m-d')) : format_date($to_date)?></span></td>
                    <td class="right aligned"><b><?= !empty($statementDetail['balance']['tot_debit'])? ($statementDetail['balance']['tot_debit'] < 0 ? '(' . (formatCurrency(abs($statementDetail['balance']['tot_debit']), $currency)) . ')' : (formatCurrency($statementDetail['balance']['tot_debit'], $currency))):'0.00' ?></b></td>
                    <td class="right aligned"><b><?= !empty($statementDetail['balance']['tot_credit'])? (formatCurrency(abs($statementDetail['balance']['tot_credit']), $currency)):'0.00' ?></b></td>
                    <td class="right aligned"></td>
                </tr>	
               
                <?php if(!empty($statementDetail['items'])&&!empty($statementDetail['balance']) && ($statementDetail['balance']['tot_debit'] - $statementDetail['balance']['tot_credit'] != 0)){ ?>	
                <tr>
                    <td colspan="4" class="right aligned">	
                        <?= ($statementDetail['balance'] && ($statementDetail['balance']['tot_credit']  >  $statementDetail['balance']['tot_debit']))  ? 'Credit' : 'Debit' ?> Balance
                    </td>
                    <td class="right aligned">
                        <?php if($statementDetail['balance']['tot_debit'] > $statementDetail['balance']['tot_credit']){ ?>
                        <span class="f-w-700"><?= formatCurrency(abs($statementDetail['balance']['close']), $currency) ?></span>
                        <?php }?>
                    </td>
                    <td class="right aligned">
                        <?php if($statementDetail['balance']['tot_debit'] < $statementDetail['balance']['tot_credit']){ ?>
                        <span class="f-w-700" ><?= formatCurrency(abs($statementDetail['balance']['close']), $currency) ?></span>
                        <?php }?>
                    </td>
                    <td class="right aligned"></td>
                </tr>
                <?php }?>
                <tr class="trFlg hide">
                    <td colspan="7" class="center aligned flg"><i class="grey flag icon"></i></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
<script>
    $('.ui.dropdown').dropdown();
    var totRecord = "<?= $totRec;?>"-0;
    filter_type = "<?= !empty($filter_type)?$filter_type:'';?>";
    startDate = "<?= $from_date ?>";
    endDate  = "<?= $to_date;?>";
    var numOfRec = 20;
    if(totRecord<numOfRec){
        totRecReached=true;
    }
</script>
<?php } ?> 
<script>
    availableBalance = "<?= $availableBalance?>"-0;
</script> 

<script>
    /* Provide a fallback printStatement when the page bundle doesn't define it.
       This will attempt to call the ecom Orders controller to get the statement PDF URL
       and open it in a new tab. It is only defined if not already present. */
    if (typeof printStatement !== 'function'){
        function printStatement(){
            var postData = {};
            postData['from_date'] = "<?= $from_date ?>";
            postData['to_date'] = "<?= $to_date ?>";
            postData['conId'] = "<?= isset($contactId) ? $contactId : '' ?>";

            $.ajax({
                type: 'POST',
                url: '<?= base_url("ecom/Orders/get_statement_url") ?>',
                data: postData,
                success: function(data){
                    // Expecting array of results like ecom main.js
                    if (data && data.length){
                        var found = false;
                        data.forEach(function(elt){
                            if (elt && elt.url){
                                var pdfUrl = elt.url + "?t=" + new Date().getTime();
                                window.open(pdfUrl, '_blank');
                                found = true;
                            }
                        });
                        if (!found){
                            alert('No data to Print!');
                        }
                    } else {
                        alert('No data to Print!');
                    }
                },
                error: function(err){
                    console.log('printStatement fallback error', err);
                    alert('Error fetching PDF');
                }
            });
        }
    }
</script>
