<?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',$this->user->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();
        $this->pdf->ezText("<b>".$this->user->lang('Invoice')." #".$this->invoice->getId()."</b>",18,array('justification'=>'right'));

        $this->pdf->ezText("\n<b>".$this->user->lang('Due Date')."</b>: ".date($this->settings->get('Date Format'),$this->invoice->getDate("timestamp")),10,array('justification'=>'right'));
        if($this->invoice->getDatePaid("timestamp") != ''){
            $this->pdf->ezText("<b>".$this->user->lang('Paid')."</b>: ".date($this->settings->get('Date Format'),$this->invoice->getDatePaid("timestamp")),10,array('justification'=>'right'));
        }
        $newLine = "\n";
        if($this->invoice->m_PluginUsed != 'none'){
            $this->pdf->ezText("\n<b>".$this->user->lang('Payment Method')."</b>: ".$this->invoice->m_PluginUsed,10,array('justification'=>'right'));
            $newLine = '';
        }
        if($this->invoice->m_CheckNum != ''){
            $this->pdf->ezText($newLine."<b>".$this->user->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));
            $img_h = (int) ($img_h/10);
            $strSpacer = str_repeat("\n", $img_h-1);
            $this->pdf->ezText($strSpacer,10,array('justification'=>'left'));
        }

        //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);
            $img_i = $imgsize[1];
            $this->pdf->addJpegFromFile($image,226,600);
            $img_i = (int) ($img_i/10);
            $strSpacer = str_repeat("\n", $img_i-1);
            $this->pdf->ezText($strSpacer,10,array('justification'=>'left'));
        }

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

        $tmpText = "";
        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";

        $tmpText .= "\n";

        $this->pdf->ezText($tmpText,11,array('justification'=>'left'));

        // If the customer is taxable show the tax header
        if ($tMyUser->isTaxable()) {
             $data = array(array('type'=>$this->user->lang('Invoice Items'),'name'=>$this->user->lang('Price'),'tax'=>$this->user->lang('Tax')));
            $this->pdf->ezTable($data,array('type'=>'<b>'.$this->user->lang('Invoice Items').'</b>','name'=>'<b>'.$this->user->lang('Price').'</b>','tax'=>'<b>'.$this->user->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'=>$this->user->lang('Invoice Items'),'name'=>$this->user->lang('Price')));
            $this->pdf->ezTable($data,array('type'=>'<b>'.$this->user->lang('Invoice Items').'</b>','name'=>'<b>'.$this->user->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 = $this->user->lang('Not Taxable');
                }
                $data = array(array('type'=>" - <b>".$packageID.$invoiceEntry->getDescription()."</b>\n".$invoiceEntry->getDetail(),'name'=>$currency->format($tMyUser->getCurrency(), $tPrice, true, false).' ','tax'=>$strTaxPrice.' '));
                $this->pdf->ezTable($data,array('type'=>'<b>'.$this->user->lang('Invoice Items').'</b>','name'=>'<b>'.$this->user->lang('Price').'</b>','tax'=>'<b>'.$this->user->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".$invoiceEntry->getDetail(),'name'=>$currency->format($tMyUser->getCurrency(), $tPrice, true, false).' '));
                $this->pdf->ezTable($data,array('type'=>'<b>'.$this->user->lang('Invoice Items').'</b>','name'=>'<b>'.$this->user->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'=>$this->user->lang('Subtotal').':','name'=>$currency->format($tMyUser->getCurrency(), $tDisplaySubTotal, true, false).' '));
            $this->pdf->ezTable($data,array('type'=>'<b>'.$this->user->lang('Invoice Items').'</b>','name'=>'<b>'.$this->user->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'=>$this->user->lang('Tax').' '.$tTax.'%:','name'=>$currency->format($tMyUser->getCurrency(), $tTaxTotal, true, false).' '));
            $this->pdf->ezTable($data,array('type'=>'<b>'.$this->user->lang('Invoice Items').'</b>','name'=>'<b>'.$this->user->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'=>$this->user->lang('Total Due').':','name'=>$currency->format($tMyUser->getCurrency(), $tPrice, true, false).' '));
        $this->pdf->ezTable($data,array('type'=>'<b>'.$this->user->lang('Invoice Items').'</b>','name'=>'<b>'.$this->user->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,$this->user->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);
    }
    
}

?>
