<?php

require_once('newedge/classes/tcpdf/config/lang/eng.php');
require_once 'newedge/classes/tcpdf/tcpdf.php';
require_once 'modules/billing/models/InvoiceEntry.php';
require_once 'modules/billing/models/Invoice.php';
require_once 'modules/billing/models/Currency.php';
require_once 'modules/clients/models/UserPackage.php';

/**
* @package Clientexec
*/
class PDFInvoice extends NE_Model
{

    var $user;
    var $invoice;
    var $pdf;
    var $html;

    function PDFInvoice(&$tuser, $invoiceID)
    {
        parent::NE_Model();

        $this->user =& $tuser;
        $this->invoice = new Invoice($this->user, $invoiceID);
        $this->generateHtml();
        $this->generatePdf();

    }

    function generatePDF()
    {
        // create new PDF document
        $this->pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // set document information
        $this->pdf->SetCreator(PDF_CREATOR);
        $this->pdf->SetAuthor('ClientExec');
        $this->pdf->SetTitle('Invoice #' . $this->invoice->getId());
        $this->pdf->SetSubject('Invoice #' . $this->invoice->getId());
        $this->pdf->SetKeywords('ClientExec, Invoice, Billing');

        // set header and footer fonts
        $this->pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $this->pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $this->pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $this->pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $this->pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $this->pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $this->pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        //set image scale factor
        $this->pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        //set some language-dependent strings
        //$this->pdf->setLanguageArray($l);

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

        // set font
        //$this->pdf->SetFont('dejavusans', '', 10);
        //$this->pdf->SetFont('arialunicid0', '', 10);
        $this->pdf->SetFont('helvetica', '', 10);

        // add a page
        $this->pdf->AddPage();

        // output the HTML content
        $this->pdf->writeHTML($this->html, true, 0, true, 0);

        // reset pointer to the last page
        $this->pdf->lastPage();

        // ---------------------------------------------------------
    }

    function generateHtml()
    {
        $currency = new Currency($this->user);

        session_cache_limiter('none');

        // restore database connection encoding to latin1 if necessary
        /*if (isset($this->settings->configuration['application']['dbEncoding']) && $this->settings->configuration['application']['dbEncoding'] == 'utf8') {
            $this->db->query("SET NAMES 'latin1'");
        }*/

        $tMyUser = new User($this->invoice->getUserID());
        $UserCurrency = $tMyUser->getCurrency();
        $paidLabel = "";
        $paidDate = "";
        $paymentLabel = "";
        $paymentMethod = "";
        $pmtRefLabel = "";
        $pmtRef = "";
        $vatNumberLabel = "";
        $vatNumber = "";
        if ($this->invoice->isPaid() && $this->invoice->getDatePaid("timestamp") != ''){
            $paidLabel = $tMyUser->lang('Paid'). " : ";
            $paidDate = date($this->settings->get('Date Format'),$this->invoice->getDatePaid("timestamp"));
        }
        $newLine = "\n";
        if ($this->invoice->isPaid() && $this->invoice->m_PluginUsed != 'none'){
            $newLine = '';
            $paymentLabel = $tMyUser->lang('Payment Method')." : ";
            $paymentMethod = $this->invoice->m_PluginUsed;
        }
        if ($this->invoice->isPaid() && $this->invoice->m_CheckNum != ''){
            $pmtRefLabel = $tMyUser->lang('Pmt Reference'). " :";
            $pmtRef = $this->invoice->m_CheckNum;
        }

        //Add spaces based on logo size
        //if user has logo add spacer
        $invoicelogo = "images/blank.png";
        if (file_exists('images/invoicelogo.jpg')) {
            $invoicelogo = 'images/invoicelogo.jpg';
        }

        //If invoice is paid, void, refunded or credited then add stamp image
        $image = 'images/blank.png';
        if ($this->invoice->isPaid()) {
            $image = 'images/paid_stamp.jpg';
        } elseif ($this->invoice->isVoid()) {
            $image = 'images/void_stamp.jpg';
        } elseif ($this->invoice->isRefunded()) {
            $image = 'images/refund_stamp.jpg';
        } elseif ($this->invoice->isCredited()) {
            $image = 'images/credited_stamp.jpg';
        }


        $customerAddress = array();
        if ($tMyUser->getAddress() != "") $customerAddress[] = $tMyUser->getAddress();
        if ($tMyUser->getCity() != "" && $tMyUser->getState() != "") $customerAddress[] = $tMyUser->getCity() .", " .$tMyUser->getState();
        else if ($tMyUser->getCity() != "") $customerAddress[] = $tMyUser->getCity();
        else if ($tMyUser->getState() != "") $customerAddress[] = $tMyUser->getState();
		if ($tMyUser->getZipCode() != "") $customerAddress[] = $tMyUser->getZipCode();
        if ($tMyUser->getCountry(true) != "") $customerAddress[] = $tMyUser->getCountry(true);
        $cAddr = implode("<br />", $customerAddress);


        require_once 'newedge/classes/NE_Template.php';

        $tpl = new NE_Template($this->user, $this->user, $this->settings,"billing");

        $tpl->no_strict();
        $companyAddressArr = explode("\n", $this->settings->get("Company Address"));
        $companyAddress = " ";
        foreach ($companyAddressArr as $key => $value) {
            //if(trim($value) != ""){
                $companyAddress .= "<tr align=\"right\"><td align=\"right\">".$value."</td></tr>";
            //}
        }
        $customerOrg = "";
        if(trim($tMyUser->getOrganization()) != ""){
            $customerOrg = "<tr><td>".$tMyUser->getOrganization()."</td></tr>";
        }
        if ($tMyUser->withinVATCountry() && $tMyUser->getVatValidation() != ''){
            $vatNumberLabel = $tMyUser->lang('VAT Number'). ":";
            $vatNumber = $tMyUser->getVatValidation();
        }
        $tpl->define(array('invoiceTemplate' => '../admin/views/clients/invoices/invoicetemplate.tpl'));
        $tpl->setKey(array(
            'companyEmail'         => $this->settings->get("Billing E-mail"),
            'companyName'          => $this->settings->get("Company Name"),
            //'companyAddress'       => str_replace("\n", "<br/>", $this->settings->get("Company Address")),
            'companyAddress'       => $companyAddress,
            'companyURL'           => $this->settings->get("Company URL"),
            'invoice'              => $tMyUser->withinVATCountry()? $tMyUser->lang('VAT Invoice') : $tMyUser->lang('Invoice'),
            'invoiceNum'           => $this->invoice->getId(),
            'dueDateLabel'         => $tMyUser->lang('Due Date'),
            'duedate'              => date($this->settings->get('Date Format'),$this->invoice->getDate("timestamp")),
            'datecreated'          => date($this->settings->get('Date Format'),$this->invoice->getDateCreated("timestamp")),
            'imgurl'               => $image,
            'invoicelogo'          => $invoicelogo,
            'paidLabel'            => $paidLabel ,
            'paidDate'             => $paidDate."<br/>" ,
            'paymentLabel'         => $paymentLabel,
            'paymentMethod'        => $paymentMethod,
            'pmtRefLabel'          => $pmtRefLabel,
            'pmtRef'               => $pmtRef,
            'pmtTransactions'      => $this->ParseInvoiceTransactions($this->invoice->getId()),
            'vatNumberLabel'       => $vatNumberLabel,
            'vatNumber'            => $vatNumber,
            'customerNum'          => $this->invoice->getUserID(),
            'customerOrg'          => $customerOrg,
            'customerName'         => $tMyUser->getFirstName().' '.$tMyUser->getLastName(),
            'customerAddress'      => $cAddr,
            'customerPhone'        => $tMyUser->getPhone(),
            'customerEmail'        => $tMyUser->getEmail(),
            'additionalnotes'      => str_replace( "\n", "<br/>",$this->settings->get('Additional Notes For Invoices'))
        ));

        // If the customer is taxable show the tax header
        $taxName = $this->invoice->getTaxName();
        if($taxName == ''){
            $taxName = $tMyUser->lang('Tax');
        }
        $tax2Name = $this->invoice->getTax2Name();
        if($tax2Name == ''){
            $tax2Name = $tMyUser->lang('Tax');
        }
        $invoiceheaders = array();
        $columnWidth = array();
        $totalHeaders = 2;
        if ($tMyUser->isTaxable()) {
            if($this->invoice->GetTax() > 0 && $this->invoice->GetTax2() > 0){
                $invoiceheaders = array($tMyUser->lang('Invoice Items'),$tMyUser->lang('Price'),$taxName,$tax2Name);
                $columnWidth = array("55%","15%","15%","15%");
                $totalHeaders = 4;
            }elseif($this->invoice->GetTax2() > 0){
                $invoiceheaders = array($tMyUser->lang('Invoice Items'),$tMyUser->lang('Price'),$tax2Name);
                $columnWidth = array("70%","15%","15%");
                $totalHeaders = 3;
            }else{
                $invoiceheaders = array($tMyUser->lang('Invoice Items'),$tMyUser->lang('Price'),$taxName);
                $columnWidth = array("70%","15%","15%");
                $totalHeaders = 3;
            }
        } else {
            $invoiceheaders = array($tMyUser->lang('Invoice Items'),$tMyUser->lang('Price'));
            $columnWidth = array("85%","15%");
            $totalHeaders = 2;
        }
        for ($i = 0; $i < count($invoiceheaders); $i++) {
            $tpl->setkey("width",$columnWidth[$i]);
            if($columnWidth[$i] == "15%"){
                $tpl->setkey("align","right");
            }else{
                $tpl->setkey("align","left");
            }
            $tpl->setkey("invoiceheader",$invoiceheaders[$i]);
            $tpl->parse('invoiceheaders_out', '.invoiceheaders');
        }
        $totalTaxed = 0;
        $totalTaxed2 = 0;

        //invoice entries

        foreach ($this->invoice->getInvoiceEntries() as $invoiceEntry) {

            $packageID = "";
            //get full identifier
            if ($invoiceEntry->AppliesTo() > 0) {
                $UserPackage = new UserPackage($invoiceEntry->AppliesTo());
                //lets get type of product .. if it is hosting or domain then lets not add full identifier
                if ( $UserPackage->getCustomField('Server Id') > 0 || $UserPackage->getProductType() == 3 ) {
                    $packageID = "#".$invoiceEntry->AppliesTo()." - ";
                } else {
                    $packageID = $UserPackage->getReference(true). " - ";
                }
            }
            $tPrice =  $invoiceEntry->getPrice();
            // If the customer is taxable show the tax pricing
            if ($tMyUser->isTaxable()) {
                $taxPrice = 0;
                if ($invoiceEntry->getTaxable()) {
                    $taxPrice = $invoiceEntry->getPrice() * $this->invoice->getTax() / 100;

                    if($invoiceEntry->isCoupon()){
                        $taxPrice = $this->invoice->getTaxesDiscount($invoiceEntry->AppliesTo());
                    }

                    $totalTaxed += $taxPrice;

                    $strTaxPrice = $currency->format($UserCurrency, $taxPrice, true, false);
                } else {
                    $strTaxPrice = $tMyUser->lang('Not Taxable');
                }

                $tax2Price = 0;
                if ($invoiceEntry->getTaxable() && $this->invoice->GetTax2() > 0) {

                    if($taxPrice > 0 && $this->invoice->isTax2Compound()){
                        $tax2Price = ($invoiceEntry->getPrice() + $taxPrice) * $this->invoice->GetTax2() / 100;
                    }else{
                        $tax2Price = $invoiceEntry->getPrice() * $this->invoice->GetTax2() / 100;
                    }

                    if($invoiceEntry->isCoupon()){
                        $tax2Price = $this->invoice->getTaxesDiscount($invoiceEntry->AppliesTo(), 2);
                    }

                    $totalTaxed2 += $tax2Price;

                    $strTax2Price = $currency->format($UserCurrency, $tax2Price, true, false);
                } else {
                    $strTax2Price = $tMyUser->lang('Not Taxable');
                }
                if($this->invoice->GetTax() > 0 && $this->invoice->GetTax2() > 0){
                    $dataLabel = "&nbsp;&nbsp;<b>".$packageID.str_replace("thru", $tMyUser->lang('thru'),$invoiceEntry->getDescription())."</b><br/>";
                    $dataLabel = $dataLabel."&nbsp;&nbsp; -&nbsp;".str_replace( "\n", "<br/>",$invoiceEntry->getDetail());
                    $dataLabel = str_replace( "<br>","<br/>", $dataLabel);
                    $price = $currency->format($UserCurrency, $tPrice, true, false);
                    $data = array($dataLabel,$price,$strTaxPrice,$strTax2Price);
                    $columnWidth = array("55%","15%","15%","15%");
                    for ($i = 0; $i < count($data); $i++) {
                        $tpl->setkey("width",$columnWidth[$i]);
                        $tpl->setkey("data",$data[$i]);
                        if($columnWidth[$i] == "15%"){
                            $tpl->setkey("align","right");
                        }else{
                            $tpl->setkey("align","left");
                        }
                        $tpl->parse('invoicedatas_out', '.invoicedatas');
                    }
                }elseif($this->invoice->GetTax2() > 0){
                    $dataLabel = "&nbsp;&nbsp;<b>".$packageID.str_replace("thru", $tMyUser->lang('thru'),$invoiceEntry->getDescription())."</b><br/>";
                    $dataLabel = $dataLabel."&nbsp;&nbsp; -&nbsp;".str_replace( "\n", "<br/>",$invoiceEntry->getDetail());
                    $dataLabel = str_replace( "<br>","<br/>", $dataLabel);
                    $price = $currency->format($UserCurrency, $tPrice, true, false);
                    $data = array($dataLabel,$price,$strTax2Price);
                    $columnWidth = array("70%","15%","15%");
                    for ($i = 0; $i < count($data); $i++) {
                        if($columnWidth[$i] == "15%"){
                            $tpl->setkey("align","right");
                        }else{
                            $tpl->setkey("align","left");
                        }
                        $tpl->setkey("width",$columnWidth[$i]);
                        $tpl->setkey("data",$data[$i]);
                        $tpl->parse('invoicedatas_out', '.invoicedatas');
                    }
                }else{
                    //echo("in first else***");

                    $dataLabel = "&nbsp;&nbsp;<b>".$packageID.str_replace("thru", $tMyUser->lang('thru'),$invoiceEntry->getDescription())."</b><br/>";
                    $dataLabel = $dataLabel."&nbsp;&nbsp; -&nbsp;".str_replace( "\n","<br/>", $invoiceEntry->getDetail());
                    $dataLabel = str_replace( "<br>","<br/>", $dataLabel);
                    $price = $currency->format($UserCurrency, $tPrice, true, false);
                    $data = array();
                    $columnWidth = array();
                    $data = array($dataLabel,$price,$strTaxPrice);
                    $columnWidth = array("70%","15%","15%");
                    for ($i = 0; $i < count($columnWidth); $i++) {
                        if($columnWidth[$i] == "15%"){
                            $tpl->setkey("align","right");
                        }else{
                            $tpl->setkey("align","left");
                        }
                        $tpl->setkey("width",$columnWidth[$i]);
                        $tpl->setkey("data",$data[$i]);

                        $tpl->parse('invoicedatas_out', '.invoicedatas');
                    }
                    //$tpl->parse('invoicedatas_out', '.invoicedatas');
                }

            } else {
                $dataLabel ="&nbsp;&nbsp;<b>".$packageID.str_replace("thru", $tMyUser->lang('thru'),$invoiceEntry->getDescription())."</b><br/>";
                $dataLabel = $dataLabel."&nbsp;&nbsp; -&nbsp;".str_replace( "\n","<br/>", $invoiceEntry->getDetail());
                $dataLabel = str_replace( "<br>","<br/>", $dataLabel);

                $price = $currency->format($UserCurrency, $tPrice, true, false);
                $data = array();
                $data = array($dataLabel,$price);
                $columnWidth = array("85%","15%");
                    for ($i = 0; $i < count($data); $i++) {
                        if($columnWidth[$i] == "15%"){
                            $tpl->setkey("align","right");
                        }else{
                            $tpl->setkey("align","left");
                        }
                        $tpl->setkey("width",$columnWidth[$i]);
                        $tpl->setkey("data",$data[$i]);
                        $tpl->parse('invoicedatas_out', '.invoicedatas');
                    }

            }

            $tpl->parse('invoiceentries_out', '.invoiceentries');
            $tpl->clear_dynamic("invoicedatas");
        }


        $totalLabels = array();
        $totalPrices = array();


        $tTaxTotal = $totalTaxed;
        $tTax2Total = $totalTaxed2;
        $tDisplaySubTotal =  $this->invoice->getSubTotal();
        $tTax = $this->invoice->GetTax();
        $tTax2 = $this->invoice->GetTax2();
        $tPrice =  $this->invoice->getPrice();

        // If the customer is taxable show the tax information
        if ($tMyUser->isTaxable() && ($this->invoice->GetTax() > 0 || $this->invoice->GetTax2() > 0)){
            $totalLabels[] = $tMyUser->lang('Subtotal').':';
            $totalPrices[] = $currency->format($UserCurrency, $tDisplaySubTotal, true, false);
            if ($this->invoice->GetTax() > 0){
                $totalLabels[] = $taxName.' '.$tTax.'%:';
                $totalPrices[] = $currency->format($UserCurrency, $tTaxTotal, true, false);
            }
            if ($this->invoice->GetTax2() > 0){
                $totalLabels[] = $tax2Name.' '.$tTax2.'%:';
                $totalPrices[] = $currency->format($UserCurrency, $tTax2Total, true, false);
            }
        }

        if ($this->invoice->isPaid()) {
            $totalLabels[] = $tMyUser->lang('Total Paid').':';
        }else{
            $totalLabels[] = $tMyUser->lang('Total Due').':';
        }
        $totalPrices[] = $currency->format($UserCurrency, $tPrice, true, false);


        //  ADDED FOR: VARIABLE_PAYMENTS - Balance Due  //
        if($this->invoice->isPartiallyPaid()){
            $tBalanceDue = $this->invoice->getBalanceDue();
            $PartiallyPaid = $tPrice - $tBalanceDue;
            $totalLabels[] = $tMyUser->lang('Paid').':';
            $totalPrices[] = $currency->format($UserCurrency, $PartiallyPaid, true, false);

            $totalLabels[] = $tMyUser->lang('Balance Due').':';
            $totalPrices[] = $currency->format($UserCurrency, $tBalanceDue, true, false);

        }

        for ($i = 0; $i < count($totalLabels); $i++) {
            if($totalHeaders == 4){
                $tpl->setkey("totalwidth","55%");
                $tpl->setkey("pricewidth","45%");
                $tpl->setkey("colspan","colspan='3' ");
            }elseif ($totalHeaders == 3) {
                $tpl->setkey("totalwidth","70%");
                $tpl->setkey("pricewidth","30%");
                $tpl->setkey("colspan","colspan='2' ");
            }else {
                $tpl->setkey("totalwidth","85%");
                $tpl->setkey("pricewidth","15%");
                $tpl->setkey("colspan"," ");
            }

            $tpl->setkey("totalLabel",$totalLabels[$i]);
            $tpl->setkey("totalPrice",$totalPrices[$i]);
            $tpl->parse('totalentries_out', '.totalentries');
        }
        //  ADDED FOR: VARIABLE_PAYMENTS - Balance Due  //

        $tpl->parse('invoice', 'invoiceTemplate');
        //$tpl->FastPrint('invoice');
        $this->html = $tpl->fetch('invoice');

        // restore database connection encoding to utf8 if necessary
        /*if (isset($this->settings->configuration['application']['dbEncoding']) && $this->settings->configuration['application']['dbEncoding'] == 'utf8') {
            $this->db->query("SET NAMES 'utf8'");
        }*/

    }

    function ParseInvoiceTransactions($invoiceid) {
        $invoicetransactions = "";

        if ($invoiceid != 0) {
        //get all transactions and loop thru to show them
            $query = "SELECT id, accepted, response, UNIX_TIMESTAMP(transactiondate) AS transdate FROM invoicetransaction WHERE invoiceid=? ORDER BY transactiondate DESC";
            $result = $this->db->query($query, $invoiceid);
            $num = $result->getNumRows();

            while(list($transid,$accepted,$response,$transdate) = $result->fetch()) {

                $invoicetransactions .= date($this->settings->get('Date Format'),$transdate)." ".date ("h:i:s A",$transdate)." - Transaction: ".$transid." -";

                $classResponse = '';
                if($accepted == 0) {
                    $classResponse = 'red';
                }

                $response = NE_Lib::convertCurrencyToHTML($response);
                $invoicetransactions .= "<font class='.$classResponse.'>".$response."</font>";

                $invoicetransactions .= "<br/>";
            }

            if ($num==0) {
                $invoicetransactions = "<font class=red>".$this->user->lang("There are no recorded transactions for this invoice")."</font>";
            }

            $invoicetransactions = "<p style='padding-top:10px;padding-left:25px;'>".$invoicetransactions."</p>";

        }
        return $invoicetransactions;
    }

    function show()
    {
        //Close and output PDF document
        $this->pdf->Output('invoice-'.$this->invoice->getId().'.pdf', 'I');
    }

    function get()
    {
        return $this->pdf->getPDFData();
    }

}

?>
