<?php
/*
Date: 2013-04-19
Author: Edward
Revision: (2013-04-25:rev1.1) YS Chin: Customized for CBMTI
Page Name: PaymentVoucher_PDF.php
Page Type: EMP
Description: To generate payment voucher
*/

include('includes/session.php');
include('includes/SQL_CommonFunctions.inc');

// require_once('includes/tcpdf/config/lang/eng.php');
require_once('includes/tcpdf/tcpdf.php');

//20140804 YS Chin: Check if page is called from itself of from Payments.php
//if (isset($_POST['PvType']) && isset($_POST['PvTransNo']))
if($_GET['pv_transno'] != "" && $_GET['pv_transtype'] == '1' || $_GET['pv_transtype'] == '22')
{
    $_POST['PvTransNo'] = $_GET['pv_transno'];
    $_POST['PvType'] = $_GET['pv_transtype'];
    
    unset($_GET['pv_transtype']);
    unset($_GET['pv_transno']);
}

//check if session variables are not empty
//if($_SESSION['pv_transno'] != "" && $_SESSION['pv_transtype'])
if (isset($_POST['PvType']) && isset($_POST['PvTransNo']))
{
    //retrieve company details
    $sql_company_details = "SELECT coyname, regoffice1, regoffice2, regoffice3, regoffice4, regoffice5, regoffice6, telephone, fax, email
                            FROM companies LIMIT 1";

    //retrieve payment voucher details
    //20130425 YS Chin: Retrieve description from gltrans
    //20140828 YS Chin: Get Payee Bank
    //20141001 YS Chin: Group by amount instead of by account only - multiple item in same account will be grouped together
    if ($_POST['PvType']=='1')
    {
        $sql_pv_details = "SELECT g. narrative, b.transdate, b.banktranstype, g.amount, b.currcode, g.chequeno, b.ref, a.bankaccountcode
                        FROM banktrans b
                        LEFT JOIN gltrans g ON g.typeno=b.transno and g.type='".$_POST['PvType']."' and g.amount>0
                        LEFT JOIN bankaccounts a on a.accountcode = b.bankact
                        WHERE b.transno = '".$_POST['PvTransNo']."'
                        AND b.type = '".$_POST['PvType']."'
                        GROUP BY g.counterindex
                        ORDER BY g.counterindex;";
    }
    else
    {
        //20150114 YS Chin: Get the Payee details from Supplier table
        $sql_pv_details = "SELECT g. narrative, b.transdate, b.banktranstype, g.amount, b.currcode, g.chequeno, s.suppname as ref, a.bankaccountcode
                FROM banktrans b
                LEFT JOIN gltrans g ON g.typeno=b.transno and g.type='".$_POST['PvType']."' and g.amount>0
                LEFT JOIN bankaccounts a on a.accountcode = b.bankact
                JOIN supptrans st on st.transno = g.typeno and st.type = g.type
                JOIN suppliers s on s.supplierid = st.supplierno 
                WHERE b.transno = '".$_POST['PvTransNo']."'
                AND b.type = '".$_POST['PvType']."'
                GROUP BY g.counterindex
                ORDER BY g.counterindex;";
        
    }
    //retrieve company details
    $result=DB_query($sql_company_details);
    
    $row=DB_num_rows($result);
    while($row = DB_fetch_row($result))
    {
        $companyname    = $row[0];
        $address1       = $row[1];
        $address2       = $row[2];
        $address3       = $row[3];
        $address4       = $row[4];
        $address5       = $row[5];
        $address6       = $row[6];
        $tel            = $row[7];
        $fax            = $row[8];
        $email          = $row[9];
    }
    
    if($address1 != "")
    {
        $companyheader = $companyheader . $address1 . "\n";
    }
    if($address2 != "")
    {
        $companyheader = $companyheader . $address2 . "\n";
    }
       
    $companyheader = $companyheader . "Tel: " . $tel . " / Fax: " . $fax . "\nEmail: " . $email . "\n";
    
    
    //retrieve company details
    $result=DB_query($sql_pv_details);
    $i=0;
    $row=DB_num_rows($result);
    //20130425 YS Chin: Display all gltrans lines
    while($row = DB_fetch_row($result))
    {
        $ref[$i]        = $row[0];
        $transdate      = $row[1];
        $transtype      = $row[2];
        $amount[$i]     = $row[3];
        $currencycode   = $row[4];
        //20130425 YS Chin: Cheque No: gltrans.chequeno
        $chequeno       = $row[5];
        //20130425: Payee Name: banktrans.ref
        $payee          = $row[6];
        $bank           = $row[7];
        $i++;
    }
    
    if ($chequeno=="0" || strlen($chequeno) == 0)
        $chequeno="";
    else
    {
        //$chequeno=" (CHQ: ". $chequeno .")";
        //20140828 YS Chin: Append bank code
        $chequeno= $chequeno . ' (' . $bank . ')';
    }
    
    //get total amount
    $totalamount = 0;
    for($i=0; $i<count($amount); $i++)
    {
        $totalamount += $amount[$i];
    }
    
    //20130425 YS Chin: Retrieve from banktrans.ref
    //retrieve description and payee
    /*list($payee, $description) = explode('-', $ref, 2);
    if($payee=="")
    {
        $description = $payee;
        $payee = "";
    }
    */
    
    // ---------------------------------------------------------
    
    //PDF Settings etc
    // ---------------------------------------------------------
    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('EMP');
    $pdf->SetTitle('PaymentVoucher');
    $pdf->SetSubject('PaymentVoucher');
    $pdf->SetKeywords('PDF, EMP, Payment Voucher');
    
    // set default header data
    //$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $companyname, $companyheader);
    $pdf->SetHeaderData('../../../' . $_SESSION['LogoFile'], 70, "", "");
    //$pdf->SetHeaderData('/logo.jpg', PDF_HEADER_LOGO_WIDTH, $companyname, $companyheader, array(0,64,255), array(0,64,128));
    // set header and footer fonts
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    //set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    
    //20140804 YS Chin: Remove page header and footer lines
    //$pdf->setPrintHeader(false);
    //$pdf->setPrintFooter(false);

    //set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    //set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    //set some language-dependent strings
    $pdf->setLanguageArray($l);
    // set font
    //$pdf->SetFont('times', 'BI', 12);
    $pdf->SetFont('times', '', 11);
    // add a page
    $pdf->AddPage();

    // ---------------------------------------------------------
    
    //Determine the labelling of PV#
    //1: Bank Payment
    //2: Supplier Payment
    if ($_POST['PvType']=='1')
        $pvLabel = "Payment Voucher: PV-G-" . $_POST['PvTransNo'];
    else
        $pvLabel = "Payment Voucher: PV-S-" . $_POST['PvTransNo'];
    
    //20130425 YS Chin: ChequeNo from gltrans
    //html to output to pdf
    $html = '
    <br/>
    <table>
        <tr><td></td></tr>
        <tr>
            <td>'. $pvLabel .'</td>
        </tr>
        <tr>
            <td>Date: '.$transdate.'</td>
        </tr>
        <tr>
            <td>Payment Type: '.$transtype.' '. $chequeno .'</td>
        </tr>
        <tr><td></td></tr>
        <tr>
            <td>Payee: '.$payee.'</td>
        </tr>
        <tr><td></td></tr>
    </table>
    
    <br/><br/>
    
    <table border="1" cellpadding="2">
        <tr>
            <th width="5%"> No</th>
            <th width="70%"> Description</th>
            <th width="20%"> Amount (' . $currencycode .')</th>
        </tr>
    ';
    //20130425 YS Chin: Loop to display all gltrans lines    
    for($j=0; $j<$i; $j++)
    {
        $rownumber = $j+1;
        $html = $html . '
        <tr>
        <td> '. $rownumber .'</td>
        <td> '.$ref[$j].'</td>
        <td align="right"> '.number_format($amount[$j], 2, '.', ',').'</td>
        </tr>';
    }
    //20130425 YS Chin: Display total
    $html = $html . '
        <tr>
        <td colspan="2" align="right"> Total (' . $currencycode .')</td>
        <td align="right"> '.number_format($totalamount, 2, '.', ',').'  </td>
        </tr>
    </table>
    
    <br/><br/><br/><br/><br/><br/>
    
    <table>
        <tr><td>Received by</td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td></td></tr>
        <tr><td>....................................................</td></tr>
        <tr><td>Name:</td></tr>
        <tr><td>IC No.:</td></tr>
        <tr><td>Date:</td></tr>
        <tr><td>Company Chop (if applicable):</td></tr>
    </table>
    
    <br/><br/><br/><br/><br/><br/>
    
    <table width="100%">
        <tr>
            <td colspan="2">'.$companyname.'</td>
        </tr>
        <tr><td></td></tr>
        <tr>
            <td><br/><br/><br/><br/>....................................................<br/>Prepared by</td>
            <td><br/><br/><br/><br/>....................................................<br/>Authorized by</td>
        </tr>
    
        <tr>
            <td>Name:</td>
            <td>Name:</td>
        </tr>
    
        <tr>
            <td>Date:</td>
            <td>Date:</td>
        </tr>
    </table>

    ';
    
    $pdf->writeHTML($html, true, false, true, false, '');
    
    // reset pointer to the last page
    $pdf->lastPage();
    
    // ---------------------------------------------------------
    
    //Close and output PDF document
    $pdf->Output('PV' . $_POST['PvTransNo'] . '.pdf', 'I');
}

else
{
    //20140804 YS Chin: Allow reprint of payment vouchers
    //echo "No data received\n";
    $Title=_('Print Payment Voucher');
    include('includes/header.php');

    echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '" method="post">';
    echo '<div>';
    echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

    echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/printer.png" title="' . _('Print') . '" alt="" />' . ' ' . _('Print Payment Vouchers') . '</p>';

    echo '<table class="selection">
            <tr>
                <td>' . _('Select PV Type') . '</td>
                <td><select name="PvType">';

    if ($PvType=='22' OR !isset($PvType))
    {
       echo '<option selected="selected" value="22">' . _('Payment to Supplier') . '</option>';
       echo '<option value="1">' . _('Other Payment') . '</option>';
    } else {
       echo '<option selected="selected" value="1">' . _('Other Payment') . '</option>';
       echo '<option value="22">' . _('Payment to Supplier') . '</option>';
    }
    echo '</select></td>
            </tr>';

    echo '<tr>
            <td>' . _('Enter the PV number to print') . '</td>
            <td><input class="number" type="text" maxlength="6" size="7" name="PvTransNo" /></td>
            </tr>
            </table>';
            
    echo '<div class="centre">
                    <br />
                    <input type="submit" name="PrintPDF" value="' . _('Print PDF') . '" />
            </div>';
            
    $sql = "SELECT typeno FROM systypes WHERE typeid=1";

    $result = DB_query($sql);
    $myrow = DB_fetch_row($result);

    echo '<div class="page_help_text"><b>' . _('The last PV (Other Payment) created was number') . ' ' . $myrow[0] . '</b><br />' . _('If only a single invoice is required') . ', ' . _('enter the invoice number to print in the Start transaction number to print field and leave the End transaction number to print field blank') . '. ' . _('Only use the end invoice to print field if you wish to print a sequential range of invoices') . '';

    $sql = "SELECT typeno FROM systypes WHERE typeid='22'";

    $result = DB_query($sql);
    $myrow = DB_fetch_row($result);

    echo '<br /><b>' . _('The last PV (Payment to Supplier) created was number') . ' ' . $myrow[0] . '</b><br />' . _('A sequential range can be printed using the same method as for invoices above') . '. ' . _('A single credit note can be printed by only entering a start transaction number') . '</div>';

        
    echo '</div>
    </form>';
    
    include('includes/footer.php');
}

?>