<?php
$this->load->view ( $left );
$this->load->view ( $header );
?>
<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-4">
        <h2>Balance Sheet</h2>
    </div>
    <!-- <div class="col-sm-8">
        <div class="title-action">
            <a href="<?php //echo site_url("bank/newbank");?>" class="btn btn-primary">
                <i class="fa fa-plus-square-o"></i>
                <span class="m-l-xs">Add Bank</span>
            </a>
        </div>
    </div> -->
</div>
<div class="wrapper wrapper-content">
    <div class="row text-center animated fadeInRightBig">
        <?php /* ?>
        <div class="ibox float-e-margins">
            <div class="ibox-content" style="padding: 15px 20px 15px 20px;">
                <div class="row">
                    <div class="col-lg-3">
                        <label class="col-lg-3 m-t-xs">From</label>
                        <div class="date_calender col-lg-9">
                            <div class="input-group date">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                <input type="text" name="start_date" id="start_date" class="form-control" value="<?php echo (!empty($start_date) ? date('d/m/Y',strtotime(str_replace('/', '-', $start_date))) : date('d/m/Y'));?>">
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3">
                        <label class="col-lg-3 m-t-xs">To</label>
                        <div class="date_calender col-lg-9">
                            <div class="input-group date">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                <input type="text" name="end_date" id="end_date" class="form-control" value="<?php echo (!empty($end_date) ? date('d/m/Y',strtotime(str_replace('/', '-', $end_date))) : date('d/m/Y'));?>">
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-1"><button type="button" class="btn btn-info generate_report"><i class="fa fa-search"></i> Search</button></div>
                    <!-- <div class="col-lg-1"><button type="button" class="btn btn-info generate_excel"><i class="fa fa-file-excel-o"></i> Export Excel</button></div> -->
                </div>
            </div>
        </div> <?php */ ?>
        <div class="ibox float-e-margins">
            <div class="ibox-content" style="padding: 15px 20px 15px 20px;">
                <div class="row">
                    <table class="table" id="myTable" border="1">
                        <thead>
                            <tr>
                                <th colspan="3">Dr.</th>
                                <th colspan="3">Cr.</th>
                            </tr>
                            <tr>
                                <th>Particulars</th>
                                <th></th>
                                <th>Amount</th>
                                <th>Particulars</th>
                                <th></th>
                                <th>Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>To Opening Stock</td>
                                <td></td>
                                <td><?php echo $opening_balance; ?></td>
                                <td>By Sales</td>
                                <td><?php echo !empty($credit_note[0]->credit_amount) ? number_format((float)$sales[0]->sale_amount, 2, '.', '') : '';?></td>
                                <td><?php echo !empty($sales[0]->sale_amount) ? number_format((float)$sales[0]->sale_amount, 2, '.', '') : '0.00';?></td>
                            </tr>
                            <tr>
                                <td>To Purchase</td>
                                <td><?php echo !empty($debit_note[0]->debit_amount) ? number_format((float)$purchase[0]->purchase_amount, 2, '.', '') : '';?></td>
                                <td><?php echo !empty($purchase[0]->purchase_amount) ? number_format((float)$purchase[0]->purchase_amount, 2, '.', '') : '0.00';?></td>
                                <td><?php echo !empty($credit_note[0]->credit_amount) ? 'Credit Note' : '';?></td>
                                <td><?php echo !empty($credit_note[0]->credit_amount) ? number_format((float)$credit_note[0]->credit_amount, 2, '.', '') : '';?></td>
                                <td><?php echo !empty($credit_note[0]->credit_amount) ? number_format((float)($sales[0]->sale_amount - $credit_note[0]->credit_amount), 2, '.', '') : '';?></td>
                            </tr>
                            <tr>
                                <td><?php echo !empty($debit_note[0]->debit_amount) ? 'Less Purchase Return' : '';?></td>
                                <td><?php echo !empty($debit_note[0]->debit_amount) ? number_format((float)$debit_note[0]->debit_amount, 2, '.', '') : '';?></td>
                                <td><?php echo !empty($debit_note[0]->debit_amount) ? number_format((float)($purchase[0]->purchase_amount - $debit_note[0]->debit_amount), 2, '.', '') : '';?></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td><?php echo 'By Closing Stock';?></td>
                                <td></td>
                                <td>
                                    <?php 
                                        $closing_amount=$opening_balance;
                                        if (count($closing_stock_details) > 0) {
                                            foreach ($closing_stock_details as $key => $value) {
                                                $closing_amount += (($value->buy - $value->sale) * $value->rate_purchase);
                                            }
                                        }
                                        echo number_format((float)$closing_amount, 2, '.', '');
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <td><?php $gross_profit = (($sales[0]->sale_amount - $credit_note[0]->credit_amount)-($opening_balance+$purchase[0]->purchase_amount-$debit_note[0]->debit_amount) + $closing_amount);?>
                                    <?php echo ($gross_profit > 0) ? 'To. Gross Profit' : '';?>
                                </td>
                                <td></td>
                                <td><?php echo ($gross_profit > 0) ? number_format((float)$gross_profit, 2, '.', '') : '';?></td>
                                <td><?php echo ($gross_profit <= 0) ? 'To. Gross Loss' : '';?></td>
                                <td></td>
                                <td><?php echo ($gross_profit <= 0) ? number_format((float)abs($gross_profit), 2, '.', '') : '';?></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td>
                                    <strong>
                                        <?php echo number_format((float)abs($opening_balance + $purchase[0]->purchase_amount - $debit_note[0]->debit_amount + (($gross_profit > 0) ? $gross_profit : 0)), 2, '.', '');?>
                                    </strong>
                                </td>
                                <td></td>
                                <td></td>
                                <td><strong><?php echo number_format((float)abs($sales[0]->sale_amount - $credit_note[0]->credit_amount + $closing_amount + (($gross_profit < 0) ? $gross_profit : 0)), 2, '.', '');?></strong></td>
                            </tr>
                            <tr>
                                <td><?php echo ($gross_profit <= 0) ? 'To. Gross Loss' : '';?></td>
                                <td></td>
                                <td><?php echo ($gross_profit <= 0) ? number_format((float)abs($gross_profit), 2, '.', '') : '';?></td>
                                <td><?php $gross_profit = (($sales[0]->sale_amount - $credit_note[0]->credit_amount)-($opening_balance+$purchase[0]->purchase_amount-$debit_note[0]->debit_amount) + $closing_amount);?>
                                    <?php echo ($gross_profit > 0) ? 'To. Gross Profit' : '';?>
                                </td>
                                <td></td>
                                <td><?php echo ($gross_profit > 0) ? number_format((float)$gross_profit, 2, '.', '') : '';?></td>
                            </tr>
                            <?php $total_expence = 0;
                                if (count($expences) > 0) {
                                    foreach ($expences as $key => $value) {?>
                                        <tr>
                                            <td><?php echo $value->expence_acc_name;?></td>
                                            <td></td>
                                            <td><?php echo number_format((float)($value->paid_amount), 2, '.', '');?></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                        </tr>
                                <?php $total_expence += $value->paid_amount;
                                }
                            }?>
                            <tr>
                                <td> 
                                    <?php $net_profit = ($gross_profit - $total_expence);?>
                                    <?php echo ($net_profit > 0) ? 'Net Profit' : '';?>
                                </td>
                                <td></td>
                                <td><?php echo ($net_profit > 0) ? number_format((float)abs($net_profit), 2, '.', '') : '';?></td>
                                <td><?php echo ($net_profit <= 0) ? 'Net Lose' : '';?></td>
                                <td></td>
                                <td><?php echo ($net_profit <= 0) ? number_format((float)abs($net_profit), 2, '.', '') : '';?></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td><strong><?php echo ($net_profit > 0) ? number_format((float)($net_profit + $total_expence), 2, '.', '') : (($gross_profit < 0) ? number_format((float)(abs($gross_profit) + $total_expence), 2, '.', '') : number_format((float)($total_expence), 2, '.', ''));?></strong></td>
                                <td></td>
                                <td></td>
                                <td><strong><?php echo ($net_profit <= 0) ? (($gross_profit > 0) ? number_format((float)(abs($gross_profit)+abs($net_profit)), 2, '.', '') : number_format((float)abs($net_profit), 2, '.', '')) : '';?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $this->load->view($footer); ?>
<script type="text/javascript">
    $(document).ready(function(){
        $('.date_calender .input-group.date').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            language: 'en',
            autoclose: true
        });

        $('.generate_report').on('click',function(){ 
            var from = chage_date_format($('#start_date').val());
            var to = chage_date_format($('#end_date').val());
            var customer = $('#choose_customer').val();
            window.location.href = '<?php echo site_url("Reports/balance_sheet/'+from+'/'+to+'");?>';
            $('#data_report').html('');
            $('#data_report').html(tr);
        });

        $('.generate_excel').on('click',function(){
            var from = chage_date_format($('#start_date').val());
            var to = chage_date_format($('#end_date').val());
            var customer = $('#choose_customer').val();
            $.ajax({
                    url: '<?php echo site_url("reports/payment_receive_list/'+customer+'/'+from+'/'+to+'");?>',
                    type: "GET",
                    data:{
                        'data' :'json',
                        'excel' :'1'
                    },
                    success: function(response){ 
                        var data = JSON.parse(response);
                        JSONToCSVConvertor(data, "Invoice Report", true);
                    }
                });
        });

        function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
            //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
            var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
            var CSV = '';    
            //Set Report title in first row or line
            //CSV += ReportTitle + '\r\n\n';
            //This condition will generate the Label/Header
            if (ShowLabel) {
                var row = "";
                //This loop will extract the label from 1st index of on array
                for (var index in arrData[0]) {
                    //Now convert each value to string and comma-seprated
                    row += index + ',';
                }
                row = row.slice(0, -1);
                //append Label row with line break
                CSV += row + '\r\n';
            }
            //1st loop is to extract each row
            for (var i = 0; i < arrData.length; i++) {
                var row = "";   
                //2nd loop will extract each column and convert it in string comma-seprated
                for (var index in arrData[i]) {
                    row += '"' + arrData[i][index] + '",';
                }
                row.slice(0, row.length - 1);
                //add a line break after each row
                CSV += row + '\r\n';
            }
            if (CSV == '') {        
                alert("Invalid data");
                return;
            }   
            //Generate a file name
            var fileName = "";
            //this will remove the blank-spaces from the title and replace it with an underscore
            fileName += ReportTitle.replace(/ /g,"_");   
            //Initialize file format you want csv or xls
            var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
            // Now the little tricky part.
            // you can use either>> window.open(uri);
            // but this will not work in some browsers
            // or you will not get the correct file extension    
            
            //this trick will generate a temp <a /> tag
            var link = document.createElement("a");    
            link.href = uri;
            
            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";
            
            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        function chage_date_format(date_str){
            return date_str.replace('/','-').replace('/','-');
        }
    });
</script>