<?php
include('includes/function.php');
$rnd       = rand();
$printArea = "printArea" . $rnd;
$btnPrint  = "btnPrint" . $rnd;
$btnExport = "btnExport" . $rnd;
$tblName   = "tbl" . rand(); 
$sqlCur    = mysql_query("SELECT symbol FROM currency_centers WHERE id = (SELECT currency_center_id FROM companies WHERE id = 1 LIMIT 1)");
$rowCur    = mysql_fetch_array($sqlCur);
?>
<script type="text/javascript">
    $(document).ready(function(){
        $("#<?php echo $btnPrint; ?>").click(function(){
            $(".dataTables_length").hide();
            $(".dataTables_filter").hide();
            $(".dataTables_paginate").hide();
            w=window.open();
            w.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
            w.document.write('<link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/style.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/table.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/button.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/print.css" media="print" />');
            w.document.write($("#<?php echo $printArea; ?>").html());
            w.document.close();
            w.print();
            w.close();
            $(".dataTables_length").show();
            $(".dataTables_filter").show();
            $(".dataTables_paginate").show();
        });
        $("#<?php echo $btnExport; ?>").click(function(){
            window.open("<?php echo $this->webroot; ?>public/report/vendor_pay_bill_<?php echo $user['User']['id']; ?>.csv", "_blank");
        });
    });
</script>
<div id="<?php echo $printArea; ?>">
    <?php
    $msg = '<b style="font-size: 18px;">' . MENU_REPORT_PAY_BILLS . '</b><br /><br />';
    if($_POST['date_from']!='') {
        $msg .= REPORT_FROM.': '.$_POST['date_from'];
    }
    if($_POST['date_to']!='') {
        $msg .= ' '.REPORT_TO.': '.$_POST['date_to'];
    }
    echo $this->element('/print/header-report',array('msg'=>$msg));
    /**
     * export to excel
     */
    $filename="public/report/vendor_pay_bill_" . $user['User']['id'] . ".csv";
    $fp=fopen($filename,"wb");
    $excelContent = MENU_REPORT_PAY_BILLS . "\n\n";
    if($_POST['date_from']!='') {
        $excelContent .= REPORT_FROM . ': ' . $_POST['date_from'];
    }
    if($_POST['date_to']!='') {
        $excelContent .= ' '.REPORT_TO . ': ' . $_POST['date_to'];
    }
    $excelContent .= "\n\n".TABLE_NO."\t".TABLE_DATE."\t".TABLE_CODE."\t".TABLE_PURCHASE_BILL_CODE."\t".TABLE_ACCOUNT."\t".TABLE_MEMO."\t".TABLE_CREATED_BY."\t".GENERAL_AMOUNT." (".$rowCur[0].")";
    ?>
    <div id="dynamic">
        <table id="<?php echo $tblName; ?>" class="table_report">
            <thead>
                <tr>
                    <th class="first"><?php echo TABLE_NO; ?></th>
                    <th style="width: 90px !important;"><?php echo TABLE_DATE; ?></th>
                    <th style="width: 100px !important;"><?php echo TABLE_CODE; ?></th>
                    <th style="width: 120px !important;"><?php echo TABLE_PURCHASE_BILL_CODE; ?></th>
                    <th style="width: 200px !important;"><?php echo TABLE_ACCOUNT; ?></th>
                    <th><?php echo TABLE_MEMO; ?></th>
                    <th style="width: 200px !important;"><?php echo TABLE_CREATED_BY; ?></th>
                    <th style="width: 120px !important;"><?php echo GENERAL_AMOUNT; ?>(<?php echo $rowCur[0]; ?>)</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $condition = "";
                if ($_POST['date_from'] != '') {
                    $condition .= 'AND "' . dateConvert($_POST['date_from']) . '" <= gl.date';
                }
                if ($_POST['date_to'] != '') {
                    $condition != '' ? $condition .= ' AND ' : '';
                    $condition .= '"' . dateConvert($_POST['date_to']) . '" >= gl.date';
                }
                if ($_POST['branch_id'] != '') {
                    $condition != '' ? $condition .= ' AND ' : '';
                    $condition .= 'gld.branch_id=' . $_POST['branch_id'];
                }else{
                    $condition != '' ? $condition .= ' AND ' : '';
                    $condition .= 'gld.branch_id IN (SELECT branch_id FROM user_branches WHERE user_id = '.$user['User']['id'].')';
                }
                if ($_POST['vendor_id'] != '') {
                    $condition != '' ? $condition .= ' AND ' : '';
                    $condition .= 'gld.vendor_id=' . $_POST['vendor_id'];
                }
                $sqlPaybill = mysql_query("SELECT
                                            gl.id,
                                            gl.date,
                                            rp.reference,
                                            purchase_orders.po_code AS bill_code,
                                            vendors.id AS vendor_id,
                                            CONCAT_WS(' ',vendors.vendor_code,vendors.name) AS vendor_name,
                                            (SELECT CONCAT(account_codes,' - ',account_description) FROM chart_accounts WHERE id=gld.chart_account_id) AS account,
                                            IF(gld.debit>0,gld.debit,gld.credit*-1) AS amount,
                                            rp.note,
                                            users.username
                                            FROM general_ledgers gl 
                                            INNER JOIN general_ledger_details gld ON gl.id=gld.general_ledger_id 
                                            INNER JOIN vendors ON vendors.id = gld.vendor_id
                                            INNER JOIN pay_bills AS rp ON rp.id = gl.pv_id
                                            LEFT JOIN purchase_orders ON purchase_orders.id = gl.purchase_order_id
                                            LEFT JOIN users ON users.id = gl.created_by
                                            WHERE gl.is_approve=1 AND gl.is_active=1 AND gl.pv_id IS NOT NULL AND gld.chart_account_id IN (SELECT id FROM chart_accounts WHERE chart_account_type_id = 6)
                                            ".$condition);
                $index   = 1;
                $tmpId   = "";
                $tmpName = "";
                $amount  = 0;
                $amountTotal = 0;
                while($rowPaybill = mysql_fetch_array($sqlPaybill)){
                    if ($rowPaybill['vendor_id'] != $tmpId) {
                        if($tmpName != ""){
                            $excelContent .= "\n".'Total '.$tmpName."\t\t\t\t\t\t\t".number_format($amount, 2);
                ?>
                    <tr>
                        <td class="first" colspan="7"><b>Total <?php echo $tmpName; ?></b></td>
                        <td style="text-align: right; font-size: 12px; font-weight: bold;"><?php echo number_format($amount, 2); ?></td>
                    </tr>
                <?php
                            $index  = 1;
                            $amount = 0;
                        }
                        $excelContent .= "\n".$rowPaybill['vendor_name'];
                ?>
                    <tr>
                        <td colspan="8" class="first"><?php echo '<b class="colspanParent">' . $rowPaybill['vendor_name'] . '</b>'; ?></td>
                    </tr>
                <?php
                    }
                    $excelContent .= "\n".$index."\t".dateShort($rowPaybill['date'])."\t".$rowPaybill['reference']."\t".$rowPaybill['bill_code']."\t".$rowPaybill['account']."\t".$rowPaybill['note']."\t".$rowPaybill['username']."\t".number_format($rowPaybill['amount'], 2);
                ?>
                    <tr>
                        <td class="first"><?php echo '<input type="hidden" value="' . $rowPaybill['id'] . '" class="link2gl" /><b>' . $index++ . '</b>'; ?></td>
                        <td><?php echo dateShort($rowPaybill['date']); ?></td>
                        <td><?php echo $rowPaybill['reference']; ?></td>
                        <td><?php echo $rowPaybill['bill_code']; ?></td>
                        <td><?php echo $rowPaybill['account']; ?></td>
                        <td><?php echo $rowPaybill['note']; ?></td>
                        <td><?php echo $rowPaybill['username']; ?></td>         
                        <td style="text-align: right;"><?php echo number_format($rowPaybill['amount'], 2); ?></td>
                    </tr>
                <?php
                    $tmpId   = $rowPaybill['vendor_id'];
                    $tmpName = $rowPaybill['vendor_name'];
                    $amount += $rowPaybill['amount'];
                    $amountTotal += $rowPaybill['amount'];
                }
                if(mysql_num_rows($sqlPaybill)){ 
                    $excelContent .= "\n".'Total '.$tmpName."\t\t\t\t\t\t\t".number_format($amount, 2);
                ?>
                    <tr>
                        <td class="first" colspan="7"><b>Total <?php echo $tmpName; ?></b></td>
                        <td style="text-align: right; font-size: 12px; font-weight: bold;"><?php echo number_format($amount, 2); ?></td>
                    </tr>
                <?php 
                }
                    $excelContent .= "\n".'Total Amount '."\t\t\t\t\t\t\t".number_format($amountTotal, 2);
                ?>
                <tr><td colspan="8">&nbsp;</td></tr>
                <tr style="font-weight: bold;">
                    <td class="first" colspan="7" style="font-size: 14px; font-weight: bold;">Total Amount</td>
                    <td style="text-align: right;font-size: 14px;text-decoration: underline;"><?php echo number_format($amountTotal, 2); ?></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<div style="clear: both;"></div>
<br />
<div class="buttons">
    <button type="button" id="<?php echo $btnPrint; ?>" class="positive">
        <img src="<?php echo $this->webroot; ?>img/button/printer.png" alt=""/>
        <?php echo ACTION_PRINT; ?>
    </button>
    <button type="button" id="<?php echo $btnExport; ?>" class="positive">
        <img src="<?php echo $this->webroot; ?>img/button/csv.png" alt=""/>
        <?php echo ACTION_EXPORT_TO_EXCEL; ?>
    </button>
</div>
<div style="clear: both;"></div>
<?php
$excelContent = chr(255).chr(254).@mb_convert_encoding($excelContent, 'UTF-16LE', 'UTF-8');
fwrite($fp,$excelContent);
fclose($fp);
?>