<?php
include("includes/function.php");
$rnd       = rand();
$printArea = "printArea" . $rnd;
$btnPrint  = "btnPrint" . $rnd;
$btnExport = "btnExport" . $rnd;
$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(){
            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();
        });
        $("#<?php echo $btnExport; ?>").click(function(){
            window.open("<?php echo $this->webroot; ?>public/report/customer_receive_payment_<?php echo $user['User']['id']; ?>.csv", "_blank");
        });
    });
</script>
<div id="<?php echo $printArea; ?>">
    <?php
    $msg = '<b style="font-size: 18px;">' . MENU_REPORT_RECEIVE_PAYMENTS . '</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/customer_receive_payment_" . $user['User']['id'] . ".csv";
    $fp=fopen($filename,"wb");
    $excelContent = MENU_REPORT_RECEIVE_PAYMENTS . "\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_INVOICE_DATE."\t".TABLE_INVOICE_CODE."\t".TABLE_ACCOUNT."\t".TABLE_CREATED_BY."\t".GENERAL_AMOUNT."(".$rowCur[0].")";
    ?>
    <div id="dynamic">
        <table class="table_report">
            <thead>
                <tr>
                    <th class="first"><?php echo TABLE_NO; ?></th>
                    <th style="width: 150px !important;"><?php echo TABLE_DATE; ?></th>
                    <th style="width: 150px !important;"><?php echo TABLE_CODE; ?></th>
                    <th style="width: 150px !important;"><?php echo TABLE_INVOICE_DATE; ?></th>
                    <th style="width: 150px !important;"><?php echo TABLE_INVOICE_CODE; ?></th>
                    <th><?php echo TABLE_ACCOUNT; ?></th>
                    <th style="width: 200px !important;"><?php echo TABLE_CREATED_BY; ?></th>
                    <th style="width: 150px !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['cgroup_id'] != '') {
                    $condition != '' ? $condition .= ' AND ' : '';
                    $condition .= 'gld.customer_id IN (SELECT customer_id FROM customer_cgroups WHERE cgroup_id=' . $_POST['cgroup_id'] . ')';
                }
                if ($_POST['customer_id'] != '') {
                    $condition != '' ? $condition .= ' AND ' : '';
                    $condition .= 'gld.customer_id=' . $_POST['customer_id'];
                }
                $sqlPayment = mysql_query("
                                           SELECT
                                           gl.id,
                                           customers.id AS customer_id,
                                           customers.name AS customer_name,
                                           gl.date,
                                           rp.reference,
                                           sales_orders.order_date AS invoice_date,
                                           sales_orders.so_code AS invoice_code,
                                           (SELECT CONCAT(account_codes,' - ',account_description) FROM chart_accounts WHERE id=gld.chart_account_id) AS account,
                                           IF(gld.debit>0,gld.debit*-1,gld.credit) AS amount,
                                           users.username
                                           FROM general_ledgers gl
                                           INNER JOIN receive_payments AS rp ON rp.id = gl.receive_payment_id 
                                           INNER JOIN general_ledger_details gld ON gl.id=gld.general_ledger_id
                                           INNER JOIN customers ON customers.id = gld.customer_id
                                           LEFT JOIN sales_orders ON sales_orders.id = gl.sales_order_id
                                           LEFT JOIN users ON users.id = gl.created_by
                                           WHERE gl.is_approve=1 AND gl.is_active=1 AND gl.receive_payment_id IS NOT NULL AND gld.chart_account_id IN (SELECT id FROM chart_accounts WHERE chart_account_type_id=2)
                                           ".$condition);
                $index   = 1;
                $tmpId   = "";
                $tmpName = "";
                $amount  = 0;
                $amountTotal = 0;
                while($rowPayment = mysql_fetch_array($sqlPayment)){
                    if ($rowPayment['customer_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".trim(preg_replace('/[\t|\s]/', '', $rowPayment['customer_name']));
                ?>
                    <tr>
                        <td colspan="7" class="first"><?php echo '<b class="colspanParent">' . $rowPayment['customer_name'] . '</b>'; ?></td>
                    </tr>
                <?php
                    }
                    $excelContent .= "\n".$index."\t".dateShort($rowPayment['date'])."\t".$rowPayment['reference']."\t".dateShort($rowPayment['invoice_date'])."\t".$rowPayment['invoice_code']."\t".$rowPayment['account']."\t".$rowPayment['username']."\t".number_format($rowPayment['amount'], 2);
                ?>
                    <tr>
                        <td class="first"><?php echo '<input type="hidden" value="' . $rowPayment['id'] . '" class="link2gl" /><b>' . $index++ . '</b>'; ?></td>
                        <td><?php echo dateShort($rowPayment['date']); ?></td>
                        <td><?php echo $rowPayment['reference']; ?></td>
                        <td><?php echo dateShort($rowPayment['invoice_date']); ?></td>
                        <td><?php echo $rowPayment['invoice_code']; ?></td>
                        <td><?php echo $rowPayment['account']; ?></td>
                        <td><?php echo $rowPayment['username']; ?></td>         
                        <td style="text-align: right;"><?php echo number_format($rowPayment['amount'], 2); ?></td>
                    </tr>
                <?php
                    $tmpId   = $rowPayment['customer_id'];
                    $tmpName = $rowPayment['customer_name'];
                    $amount += $rowPayment['amount'];
                    $amountTotal += $rowPayment['amount'];
                }
                if(mysql_num_rows($sqlPayment)){ 
                    $excelContent .= "\n".'Total '.trim(preg_replace('/[\t|\s]/', '', $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);
?>