<?php
/*=======================================================\
|                 Point of Sales Module                  |
|--------------------------------------------------------|
|   Creator: Phương                                      |
|   Date :   18-Dec-2017                                 |
|   Description: ERP Point of Sales Extension            |
|   Website: http://notrinos.com                         |
|                                                        |
\=======================================================*/

$page_security = 'SA_PRICEREP';

include_once($path_to_root . '/modules/pos/includes/pos_db.inc');

//----------------------------------------------------------------------------------------------------

function get_pos_invoice_range($from, $to) {
    global $SysPrefs;

    $ref = ($SysPrefs->print_invoice_no() == 1 ? 'trans_no' : 'reference');

    $sql = "SELECT trans.trans_no, trans.reference FROM ".TB_PREF."debtor_trans trans LEFT JOIN ".TB_PREF."voided voided ON trans.type=voided.type AND trans.trans_no=voided.id WHERE trans.type=".ST_SALESINVOICE." AND ISNULL(voided.id) AND trans.trans_no IN (SELECT trans_no FROM ".TB_PREF."pos_trans) AND trans.trans_no BETWEEN ".db_escape($from)." AND ".db_escape($to)." ORDER BY trans.tran_date, trans.$ref";

    return db_query($sql, 'Cant retrieve invoice range');
}

print_pos_receipt();

//----------------------------------------------------------------------------------------------------

function print_pos_receipt() {
    global $path_to_root, $SysPrefs;

    include_once($path_to_root.'/reporting/includes/pdf_report.inc');

    $from = $_POST['PARAM_0'];
    $to = $_POST['PARAM_1'];
    $customer = $_POST['PARAM_2'];
    $comments = $_POST['PARAM_3'];
    $orientation = $_POST['PARAM_4'];

    if (!$from || !$to) return;

    $orientation = ($orientation ? 'L' : 'P');
    $fno = explode("-", $from);
    $tno = explode("-", $to);
    $from = min($fno[0], $tno[0]);
    $to = max($fno[0], $tno[0]);

    $rep = new FrontReport(_('POS Receipt'), 'PosReceipt', 'A6', 9, $orientation);
    $rep->SetMargins(10,10);

    $x = $rep->getPageWidth();
    $y = $rep->getPageHeight();

    $comp_details = get_company_prefs();
    $comp_name = $comp_details['coy_name'];
    $comp_adrs = $comp_details['postal_address'];
    $comp_phone = $comp_details['phone'];
    $comp_logo = company_path().'/images/'.$comp_details['coy_logo'];

    $range = get_pos_invoice_range($from, $to);

    while($row = db_fetch($range)) {

        $myrow = get_customer_trans($row['trans_no'], ST_SALESINVOICE);

        if($customer && $myrow['debtor_no'] != $customer)
            continue;

        $sales_order = get_sales_order_header($myrow["order_"], ST_SALESORDER);
        $result = get_customer_trans_details(ST_SALESINVOICE, $row['trans_no']);
        $trans = get_pos_trans($row['trans_no']);
        $cash = $trans['cash_amount'];
        $bill_discount = $trans['discount'];
        
        if($trans['order_type'] == 1)
            $order_type = _('Dine-In');
        elseif($trans['order_type'] == 2)
            $order_type = _('Take Away');
        elseif($trans['order_type'] == 3)
            $order_type = _('Delivery');
        else
            $order_type = '';

        $comp_cell = "<table align='left'>
            <tr><td align='center'><b>".$comp_name."</b></td></tr>
            <tr><td><b>"._('Address').": </b><i>".$comp_adrs."</i></td></tr>
            <tr><td><b>"._('Phone').": </b>".$comp_phone."</td></tr>
        </table>";

        $date_cell = "<table align='left'>
            <tr>
                <td><b>"._('Date').": </b>".sql2date($myrow["tran_date"])."</td>
                <td><b>"._('Order Type:').'&nbsp;</b>'.$order_type."</td>
            </tr>
            <tr>
                <td><b>"._('Reference').": </b>".$myrow['reference']."</td>
                <td><b>"._('Table:').'&nbsp;</b>'.$trans['table_id']."</td>
            </tr>
        </table>";
        $cus_cell = "<table>
            <tr>
                <td width='70' align='left'>"._('Customer').':'."</td>
                <td width='200' align='left'>".$myrow['DebtorName']."</td>
            </tr>
            <tr>
                <td width='70' align='left'>"._('Sales Person:')."</td>
                <td width='200' align='left'>".$_SESSION['wa_current_user']->name."</td>
            </tr>
        </table>";

        $receipt_header = "<table>
            <tr>
                <td width='55' align='center'><b>"._('Quantity')."</b></td>
                <td width='85' align='right'><b>"._('Price')."</b></td>
                <td width='45' align='right'><b>"._('Disc')."</b></td>
                <td width='85' align='right'><b>"._('Total')."</b></td>
            </tr>
        </table>";
        $receipt_items = "<table>";

        $sub_total = 0;
        $row_count = 0;

        while ($item_row = db_fetch($result)) {
            if($item_row['quantity']==0 || $item_row['unit_price'] == 0) continue;

            $value = round2(((1 - $item_row['discount_percent']) * $item_row['unit_price'] * $item_row['quantity']), user_price_dec());
            $sub_total += $value;

            if ($item_row['discount_percent'] == 0)
                $display_discount = "";
            else
                $display_discount = percent_format($item_row['discount_percent']*100) . "%";

            $receipt_items .= "<tr>";
            $receipt_items .= "<td colspan='4'><b>".$item_row['StockDescription']."</b></td>";
            $receipt_items .= "</tr>";

            $receipt_items .= "<tr>";
            $receipt_items .= "<td width='50' align='center'>".$item_row['quantity'].'&nbsp;'.$item_row['units']."</td>";
            // $receipt_items .= "<td>".$item_row["units"]."</td>";
            $receipt_items .= "<td width='90' align='right'>".price_format($item_row['unit_price'])."</td>";
            $receipt_items .= "<td width='50' align='right'>".$display_discount."</td>";
            $receipt_items .= "<td width='85' align='right'>".price_format($value)."</td>";
            $receipt_items .= "</tr>";
            $row_count++;
        }
        $receipt_items .= "</table>";

        $display_total = $myrow['ov_freight']+$myrow['ov_gst']+$myrow['ov_amount']+$myrow['ov_freight_tax'];
        $refund = $cash - ($display_total - $bill_discount);

        $receipt_total = "<table><tr>";
        $receipt_total .= "<td colspan='2' align='right'>"._('Subtotal')."</td><td nowrap align='right'>".price_format($sub_total)."</td>";
        $receipt_total .= "</tr>";
        $receipt_total .= "<tr>";
        $receipt_total .= "<td colspan='2' align='right'>"._("Bill Discount")."</td><td nowrap align='right'>".price_format($bill_discount)."</td>";
        $receipt_total .= "</tr>";
        $receipt_total .= "<tr>";
        $receipt_total .= "<td colspan='2' align='right'><b>"._("TOTAL RECEIPT")."</b></td><td nowrap align='right'><b>".price_format($display_total-$bill_discount)."</b></td>";
        $receipt_total .= "</tr>";
        $receipt_total .= "<tr>";
        $receipt_total .= "<td colspan='2' align='right'>"._("Cash Tendered")."</td><td nowrap align='right'>".price_format($cash)."</td>";
        $receipt_total .= "</tr>";
        $receipt_total .= "<tr>";
        $receipt_total .= "<td colspan='2' align='right'>"._("Refund")."</td><td nowrap align='right'>".price_format($refund)."</td>";
        $receipt_total .= "</tr></table>";

        $rep->AddPage();
        $rep->SetFont('', '', 9);

        $rep->Image($comp_logo, 0, 5, '', 45, '', '', '', false, '300', 'C');
        $rep->writeHTMLCell(0, 0, 0, 55, $comp_cell, 0, 1, 0, true, 'C', false);
        // $rep->writeHTMLCell(0, 0, 0, 0, '', 0, 1, 0, true, 'C', false);

        $rep->writeHTMLCell(0, 0, 0, '', $date_cell, 0, 1, 0, true, 'C', false);
        $rep->writeHTMLCell(0,0,0,0, '', 0, 1, 0, true, 'C', false);

        $rep->SetFont('', 'B', 16);
        $rep->writeHTMLCell(0, 0, 0, 140, _('RECEIPT'), 0, 1, 0, true, 'C', false);
        $rep->SetFont('', '', 9);
        // $rep->writeHTMLCell(0, 0, 0, 0, '', 0, 1, 0, true, 'C', false);

        $rep->writeHTMLCell(0, 0, '', '',$cus_cell , 0, 1, 0, true, 'L', false);
        $rep->writeHTMLCell(0, 0, 0, 0, '', 0, 1, 0, true, 'C', false);
        $rep->LineTo(10, 209, $x-10, 209);

        $rep->writeHTMLCell(0, 0, '', '', $receipt_header, 0, 1, 0, true, 'L', false);
        $rep->writeHTMLCell(0, 0, '', '', $receipt_items, 0, 1, 0, true, 'L', false);
        $rep->SetFont('', '', 10);
        $rep->writeHTMLCell(0, 0, '', '', $receipt_total, 0, 1, 0, true, 'L', false);
    }

    $rep->End();
}