<?php

session_cache_limiter('none');
ini_set("include_path", dirname(__FILE__));
// need to change working dir for the pdf to work fine
chdir(realpath(ini_get('include_path')));

if (!isset($bolSendEmail)) {
    $bolSendEmail = false;
}
if (!$bolSendEmail) include_once("common/common.php");
include_once("common/currency.php");

// restore database connection encoding to latin1 if necessary
if (isset($GLOBALS['dbencoding']) && $GLOBALS['dbencoding'] == 'utf8') {
    mysql_query("SET NAMES 'latin1'");
}

$query = "SELECT customerid from invoice where id=?";

$result = $GLOBALS['db']->query($query, $_REQUEST['invoiceid']);
list($tUserID) = $result->fetch();

//check to make sure the proper user is viewing the invoice
if ((!isset($GLOBALS['customer']) || $GLOBALS['customer']->getId() != $tUserID) && !$bolSendEmail) {
    echo "<center>You are unauthorized to view this invoice</center>";exit;
}

include_once("classes/user.php");
$tMyUser =& new User($tUserID);
$tMyUser->PopulateCustomFields();

include_once 'classes/class.ezpdf.php';
include_once("classes/invoice.php");
include_once("classes/invoiceentry.php");
$tempInvoice = new Invoice($_REQUEST['invoiceid']);

$pdf = new Cezpdf('letter','portrait');

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

$pdf->saveState();
$pdf->setColor(0.9,0.9,0.9);
$pdf->filledRectangle($pdf->ez['leftMargin'],$pdf->y-$pdf->getFontHeight(18)+$pdf->getFontDecender(18),$pdf->ez['pageWidth']-$pdf->ez['leftMargin']-$pdf->ez['rightMargin'],$pdf->getFontHeight(18));
$pdf->restoreState();
$pdf->ezText("<b>".lang('Invoice')." #".$_REQUEST['invoiceid']."</b>",18,array('justification'=>'right'));

$pdf->ezText("\n<b>".lang('Due Date')."</b>: ".date($gSettingsArray['Date Format'],$tempInvoice->getDate("timestamp")),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];
    $pdf->addJpegFromFile('images/invoicelogo.jpg',26,(730-$img_h));
    $img_h = (int) ($img_h/10);
    $strSpacer = str_repeat("\n", $img_h-1);
    $pdf->ezText($strSpacer,10,array('justification'=>'left'));
}

//If invoice is paid add paid stamp
if (file_exists('images/paid_stamp.jpg')&&($tempInvoice->IsPaid()==1)) {
    $imgsize = GetImageSize ('images/paid_stamp.jpg');
    $img_i = $imgsize[1];
    $pdf->addJpegFromFile('images/paid_stamp.jpg',226,600);
    $img_i = (int) ($img_i/10);
    $strSpacer = str_repeat("\n", $img_i-1);
    $pdf->ezText($strSpacer,10,array('justification'=>'left'));
}


//Get company name and company URL
$pdf->ezText("<b>".$gSettingsArray['Company Name']."</b>\n<c:alink:".$gSettingsArray['Company URL'].">".$gSettingsArray['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->getPhone() != "") $tmpText .= $tMyUser->getPhone()."\n";

$tmpText .= "\n";

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

//Loop through and great an array for all the rows
$data = array(array('type'=>lang('Invoice Items'),'name'=>lang('Price')));
$pdf->ezTable($data,array('type'=>'<b>'.lang('Invoice Items').'</b>','name'=>'<b>'.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));

/*
//if tax show subtotal
//Loop through and great an array for all the rows
$data = array(array('type'=>'Sub Total','name'=>'$99'),);
$pdf->ezTable($data,array('type'=>'<b>Description</b>','name'=>'<b>Price</b>'),'',array('cols'=>array('type'=>array('justification'=>'right'),'name'=>array('width'=>'60','justification'=>'right')),'showHeadings'=>0,'shaded'=>1,'xPos'=>'585','xOrientation'=>'left','width'=>550));
//Loop through and great an array for all the rows
$data = array(array('type'=>'Tax','name'=>'$12'),);
$pdf->ezTable($data,array('type'=>'<b>Description</b>','name'=>'<b>Price</b>'),'',array('cols'=>array('type'=>array('justification'=>'right'),'name'=>array('width'=>'60','justification'=>'right')),'showHeadings'=>0,'shaded'=>1,'xPos'=>'585','xOrientation'=>'left','width'=>550));
//end if tax
*/

//Loop through and great an array for all the rows
$tSubTotal = 0;
foreach ($tempInvoice->m_arrInvoiceEntries as $value) {
    $tempInvoiceEntry = new InvoiceEntry($value);
    $tPrice =  $tempInvoiceEntry->getPrice();
    $tSubTotal +=$tPrice;
    $data = array(array('type'=>" - <b>".$tempInvoiceEntry->getDescription()."</b>\n".$tempInvoiceEntry->getDetail(),'name'=>ShowCurrencySymbol($tMyUser->getCurrency(),false).' '.$tPrice.' '));
    $pdf->ezTable($data,array('type'=>'<b>'.lang('Invoice Items').'</b>','name'=>'<b>'.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));
}

$tDisplaySubTotal =  $tSubTotal;
$tTax = $tempInvoice->GetTax();
$tTaxTotal = (($tSubTotal*($tempInvoice->GetTax()/100)));
$tTaxTotal =  $tTaxTotal;
$tPrice =  $tempInvoice->getPrice();
if ($tempInvoice->GetTax()>0){
    $data = array(array('type'=>lang('Subtotal').':','name'=>ShowCurrencySymbol($tMyUser->getCurrency(),false)." ".$tDisplaySubTotal.' '));
    $pdf->ezTable($data,array('type'=>'<b>'.lang('Invoice Items').'</b>','name'=>'<b>'.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'=>lang('Tax').' '.$tTax.'%:','name'=>ShowCurrencySymbol($tMyUser->getCurrency(),false).' '.$tTaxTotal.' '));
    $pdf->ezTable($data,array('type'=>'<b>'.lang('Invoice Items').'</b>','name'=>'<b>'.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'=>lang('Total Due').':','name'=>ShowCurrencySymbol($tMyUser->getCurrency(),false).' '.sprintf("%.2f",$tPrice).' '));
$pdf->ezTable($data,array('type'=>'<b>'.lang('Invoice Items').'</b>','name'=>'<b>'.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));

$pdf->ezText("\n\n".$gSettingsArray['Additional Notes For Invoices'],10,array('justification'=>'left'));

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

// restore database connection encoding to utf8 if necessary
if (isset($GLOBALS['dbencoding']) && $GLOBALS['dbencoding'] == 'utf8') {
    mysql_query("SET NAMES 'utf8'");
}

// uncomment for debugging
//$GLOBALS['logger']->log(1, $pdf->messages);
//echo '<pre>'.$pdf->messages;
//echo $pdf->output(1);die();
//$pdf->ezStream();die();

if ($bolSendEmail) $pdfsource = $pdf->ezOutput(1);
else  $pdf->ezStream();

?>
