<?php

require_once 'newedge/classes/class.ezpdf.php';
require_once 'modules/billing/models/InvoiceEntry.php';
require_once 'modules/billing/models/Invoice.php';
require_once 'classes/Currency.php';


/**
* @package Clientexec
*/
class PDFInvoice extends NE_Model
{
    
    var $user;
    var $invoice;
    var $pdf;
    
    function PDFInvoice(&$tuser, $invoiceID)
    {
        parent::NE_Model();
        
        $this->user =& $tuser;
        $this->invoice = new Invoice($this->user, $invoiceID);
        $this->generateInvoice();
        
    }
    
    function generateInvoice()
    {
        $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());
        
        $this->pdf = new Cezpdf('letter','portrait');

        //Building Header for Invoice
        $this->pdf->selectFont('newedge/fonts/Helvetica.afm');
        $this->pdf->addInfo('Title',$tMyUser->lang("Invoice"));
        $this->pdf->addInfo('Creator','ClientExec');
        $this->pdf->setPreferences('NonFullScreenPageMode','1');

        $this->pdf->saveState();
        $this->pdf->setColor(0.9,0.9,0.9);
        $this->pdf->filledRectangle($this->pdf->ez['leftMargin'],$this->pdf->y-$this->pdf->getFontHeight(18)+$this->pdf->getFontDecender(18),$this->pdf->ez['pageWidth']-$this->pdf->ez['leftMargin']-$this->pdf->ez['rightMargin'],$this->pdf->getFontHeight(18));
        $this->pdf->restoreState();
        $y = $this->pdf->ezText("<b>".($tMyUser->withinVATCountry()? $tMyUser->lang('VAT Invoice') : $tMyUser->lang('Invoice'))." #".$this->invoice->getId()."</b>",18,array('justification'=>'right'));

        $this->pdf->ezText("\n<b>".$tMyUser->lang('Due Date')."</b>: ".date($this->settings->get('Date Format'),$this->invoice->getDate("timestamp")),10,array('justification'=>'right'));
        if ($this->invoice->isPaid() && $this->invoice->getDatePaid("timestamp") != ''){
            $this->pdf->ezText("<b>".$tMyUser->lang('Paid')."</b>: ".date($this->settings->get('Date Format'),$this->invoice->getDatePaid("timestamp")),10,array('justification'=>'right'));
        }
        $newLine = "\n";
        if ($this->invoice->isPaid() && $this->invoice->m_PluginUsed != 'none'){
            $this->pdf->ezText("\n<b>".$tMyUser->lang('Payment Method')."</b>: ".$this->invoice->m_PluginUsed,10,array('justification'=>'right'));
            $newLine = '';
        }
        if ($this->invoice->isPaid() && $this->invoice->m_CheckNum != ''){
            $this->pdf->ezText($newLine."<b>".$tMyUser->lang('Pmt Reference')."</b>: ".$this->invoice->m_CheckNum,10,array('justification'=>'right'));
        }

        //Add spaces based on logo size
        //if user has logo add spacer
        if (file_exists('images/invoicelogo.jpg')) {
            $imgsize = GetImageSize ('images/invoicelogo.jpg');
            $img_h = $imgsize[1];
            $this->pdf->addJpegFromFile('images/invoicelogo.jpg',26,(730-$img_h));
        }

        //If invoice is paid, void or refunded then add stamp image
        $image = false;
        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';
        }
        if ($image !== false && file_exists($image)) {
            $imgsize = GetImageSize ($image);
            $this->pdf->addJpegFromFile($image,226,600);
        }
        $y = $this->pdf->ezText("\n\n");

        //Get company name and company URL
        $companyY = $this->pdf->ezText("<b>".$this->settings->get('Company Name')."</b>\n".$this->settings->get('Company Address')."\n<c:alink:".$this->settings->get('Company URL').">".$this->settings->get('Company URL')."</c:alink>\n\n",11,array('justification'=>'left'));

        $this->pdf->ezSetY($y);
        $tmpText = "<b>".$tMyUser->lang("Bill To:")."</b>\n";
        if ($tMyUser->getOrganization() != "") $tmpText .= $tMyUser->getOrganization()."\n";
        if ($tMyUser->GetFullName() != "") $tmpText .= $tMyUser->GetFullName()."\n";
        if ($tMyUser->getAddress() != "") $tmpText .= $tMyUser->getAddress()."\n";
        if ($tMyUser->getCity() != "") $tmpText .= $tMyUser->getCity().", ";
        if ($tMyUser->getState() != "") $tmpText .= $tMyUser->getState()." ";
        if ($tMyUser->getZipCode() != "") $tmpText .= $tMyUser->getZipCode()."\n";
        if ($tMyUser->getCountry(true) != "") $tmpText .= $tMyUser->getCountry(true)."\n";
        if ($tMyUser->getPhone() != "") $tmpText .= $tMyUser->getPhone()."\n";
        if ($tMyUser->getCustomFieldByType(typeVATNUMBER)) $tmpText .= $tMyUser->lang("VAT"). " #: " . $tMyUser->getCustomFieldByType(typeVATNUMBER)."\n";

        $tmpText .= "\n";

        $userY = $this->pdf->ezText($tmpText,11,array('justification'=>'right'));
        
        $this->pdf->ezSetY(min($companyY, $userY));

        // If the customer is taxable show the tax header
        if ($tMyUser->isTaxable()) {
             $data = array(array('type'=>$tMyUser->lang('Invoice Items'),'name'=>$tMyUser->lang('Price'),'tax'=>$tMyUser->lang('Tax')));
            $this->pdf->ezTable($data,array('type'=>'<b>'.$tMyUser->lang('Invoice Items').'</b>','name'=>'<b>'.$tMyUser->lang('Price').'</b>','tax'=>'<b>'.$tMyUser->lang('Tax').'</b>'),'',array('cols'=>array('type'=>array('justification'=>'left'),'name'=>array('width'=>'60','justification'=>'right'),'tax'=>array('width'=>'70','justification'=>'right')),'showHeadings'=>0,'shaded'=>2,'xPos'=>'585','xOrientation'=>'left','width'=>550));
        } else {
            $data = array(array('type'=>$tMyUser->lang('Invoice Items'),'name'=>$tMyUser->lang('Price')));
            $this->pdf->ezTable($data,array('type'=>'<b>'.$tMyUser->lang('Invoice Items').'</b>','name'=>'<b>'.$tMyUser->lang('Price').'</b>'),'',array('cols'=>array('type'=>array('justification'=>'left'),'name'=>array('width'=>'60','justification'=>'right')),'showHeadings'=>0,'shaded'=>2,'xPos'=>'585','xOrientation'=>'left','width'=>550));
        }

        //Loop through and great an array for all the rows
        foreach ($this->invoice->getInvoiceEntries() as $invoiceEntry) {
            $packageID = "";
            if ($invoiceEntry->AppliesTo() > 0) $packageID = "CE".$invoiceEntry->AppliesTo()." - ";
            $tPrice =  $invoiceEntry->getPrice();
            // If the customer is taxable show the tax pricing
            if ($tMyUser->isTaxable()) {
                if ($invoiceEntry->getTaxable()) {
                    $strTaxPrice = $currency->format($tMyUser->getCurrency(), ($invoiceEntry->getPrice() * $this->invoice->getTax() / 100), true, false);
                } else {
                    $strTaxPrice = $tMyUser->lang('Not Taxable');
                }
                $data = array(array('type'=>" - <b>".$packageID.$invoiceEntry->getDescription()."</b>\n".str_replace("<br>", "\n", $invoiceEntry->getDetail()),'name'=>$currency->format($tMyUser->getCurrency(), $tPrice, true, false).' ','tax'=>$strTaxPrice.' '));
                $this->pdf->ezTable($data,array('type'=>'<b>'.$tMyUser->lang('Invoice Items').'</b>','name'=>'<b>'.$tMyUser->lang('Price').'</b>','tax'=>'<b>'.$tMyUser->lang('Tax').'</b>'),'',array('cols'=>array('type'=>array('justification'=>'left'),'name'=>array('width'=>'60','justification'=>'right'),'tax'=>array('width'=>'70','justification'=>'right')),'showHeadings'=>0,'shaded'=>1,'xPos'=>'585','xOrientation'=>'left','width'=>550, 'splitRows' => 1, 'protectRows' => 0));                
            } else {
                $data = array(array('type'=>" - <b>".$packageID.$invoiceEntry->getDescription()."</b>\n".str_replace("<br>", "\n", $invoiceEntry->getDetail()),'name'=>$currency->format($tMyUser->getCurrency(), $tPrice, true, false).' '));
                $this->pdf->ezTable($data,array('type'=>'<b>'.$tMyUser->lang('Invoice Items').'</b>','name'=>'<b>'.$tMyUser->lang('Price').'</b>'),'',array('cols'=>array('type'=>array('justification'=>'left'),'name'=>array('width'=>'60','justification'=>'right')),'showHeadings'=>0,'shaded'=>1,'xPos'=>'585','xOrientation'=>'left','width'=>550, 'splitRows' => 1, 'protectRows' => 0));
            }
        }
        
        $tTaxTotal = $this->invoice->getTaxCharged();
        $tDisplaySubTotal =  $this->invoice->getSubTotal();
        $tTax = $this->invoice->GetTax();
        $tPrice =  $this->invoice->getPrice();
        
        // If the customer is taxable show the tax information
        if ($tMyUser->isTaxable() && $this->invoice->GetTax()>0){
            $data = array(array('type'=>$tMyUser->lang('Subtotal').':','name'=>$currency->format($tMyUser->getCurrency(), $tDisplaySubTotal, true, false).' '));
            $this->pdf->ezTable($data,array('type'=>'<b>'.$tMyUser->lang('Invoice Items').'</b>','name'=>'<b>'.$tMyUser->lang('Price').'</b>'),'',array('cols'=>array('type'=>array('justification'=>'right'),'name'=>array('width'=>'60','justification'=>'right')),'showHeadings'=>0,'showLines'=>0,'shaded'=>1,'xPos'=>'585','xOrientation'=>'left','width'=>550));
            $data = array(array('type'=>$tMyUser->lang('Tax').' '.$tTax.'%:','name'=>$currency->format($tMyUser->getCurrency(), $tTaxTotal, true, false).' '));
            $this->pdf->ezTable($data,array('type'=>'<b>'.$tMyUser->lang('Invoice Items').'</b>','name'=>'<b>'.$tMyUser->lang('Price').'</b>'),'',array('cols'=>array('type'=>array('justification'=>'right'),'name'=>array('width'=>'60','justification'=>'right')),'showHeadings'=>0,'showLines'=>0,'shaded'=>1,'xPos'=>'585','xOrientation'=>'left','width'=>550));
        }
        $data = array(array('type'=>$tMyUser->lang('Total Due').':','name'=>$currency->format($tMyUser->getCurrency(), $tPrice, true, false).' '));
        $this->pdf->ezTable($data,array('type'=>'<b>'.$tMyUser->lang('Invoice Items').'</b>','name'=>'<b>'.$tMyUser->lang('Price').'</b>'),'',array('cols'=>array('type'=>array('justification'=>'right'),'name'=>array('width'=>'60','justification'=>'right')),'showHeadings'=>0,'showLines'=>0,'shaded'=>1,'xPos'=>'585','xOrientation'=>'left','width'=>550));

        $this->pdf->ezText("\n\n".$this->settings->get('Additional Notes For Invoices'),10,array('justification'=>'left'));

        // put a line top and bottom on the last page
        $all = $this->pdf->openObject();
        $this->pdf->saveState();
        $this->pdf->setStrokeColor(0,0,0,1);
        $this->pdf->line(10,50,578,50);
        $this->pdf->addText(10,34,12,$tMyUser->lang('Detailed invoice information can be found at').' - <c:alink:'.NE_Lib::getSoftwareURL().'>'.NE_Lib::getSoftwareURL().'</c:alink>');
        $this->pdf->restoreState();
        $this->pdf->closeObject();
        $this->pdf->addObject($all,'add');

        // 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 show()
    {
        //check to make sure the proper user is viewing the invoice
        if ($this->user->getId() == $this->invoice->getUserID() || $this->user->isAdmin()) {
            // work-around IE bug when using SSL
            header("Pragma: public");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            $this->pdf->ezStream();   
        } else {
            echo "<center>You are unauthorized to view this invoice</center>";exit;
        }
    }
    
    function get()
    {
        return $this->pdf->ezOutput(1);
    }
    
}

?>
