<?php
header('Content-Type: text/html; charset=UTF-8');
require('fpdf/fpdf.php');
date_default_timezone_set("America/La_Paz");
include "core/autoload.php";
include "core/app/model/ProductData.php";
include "core/app/model/PersonData.php";
include "core/app/model/ProposalData.php";
include "core/app/model/UserData.php";
include "core/app/model/SpendBoxData.php";
include "core/app/model/OperationPData.php";
//include "core/app/model/ProductProvData.php";
include "core/app/model/ProductProviderData.php";

class PDF extends FPDF
{

	function Header()
	{

		//Logo
		$this->SetFillColor(0, 0, 0);
		//$this->Image('logomod.jpg',0,2,60);
		$this->Cell(189, 10, '', 0, 1); //end of line
		//Arial bold 15
		$this->SetFont('Arial', 'B', 8);
		//Movernos a la derecha
		$this->Cell(30);
		//T�tulo
		$this->Cell(21, 5, '', 0, 0, 'C');
		$this->Cell(100);
		$this->SetFont('Arial', 'B', 15);
		$this->Cell(21, 5, 'Nro.' , 0, 1, 'C');
		$this->Cell(20);
		$this->Cell(31, 5, '', 0, 0, 'C');
		$this->Cell(25);
		$this->SetFont('Arial', 'B', 12);
		$this->Cell(31, 5, 'COSTEO', 0, 0, 'C');
		$this->Cell(35);
		$this->SetFont('Arial', 'B', 9);
		$this->Cell(10, 5, 'DIA', 0, 0, 'C');
		$this->Cell(5);
		$this->Cell(10, 5, 'MES', 0, 0, 'C');
		$this->Cell(5);
		$this->Cell(10, 5, utf8_decode('AÑO'), 0, 1, 'C');

		$this->SetFont('Arial', '', 8);
		$this->Cell(31, 4, '', 0, 0);
		$this->Cell(108);
		$this->Cell(15, 4, $GLOBALS['dia'], 0, 0, 'C');
		$this->Cell(15, 4, $GLOBALS['mes'], 0, 0, 'C');
		$this->Cell(15, 4, $GLOBALS['anio'], 0, 1, 'C');
		$this->Cell(31, 4, '', 0, 1);
		$this->Cell(31, 4, '', 0, 1);
		$this->Cell(31, 4, '', 0, 0);
		$this->Cell(100);
		$this->Cell(31, 4, '', 0, 1);
		$this->Cell(31, 4, '', 0, 1);
		//Salto de l�nea
		$this->Ln(5);
		$this->SetAlpha(0.1);
		//$this->Image('fondo9.png', 16, 60, $fpdf->w, $fpdf->h);
		$this->SetAlpha(1);
	}

	protected $B = 0;
	protected $I = 0;
	protected $U = 0;
	protected $HREF = '';

	function WriteHTML($html)
	{
		// HTML parser
		$html = str_replace("\n", ' ', $html);
		$a = preg_split('/<(.*)>/U', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
		foreach ($a as $i => $e) {
			if ($i % 2 == 0) {
				// Text
				if ($this->HREF)
					$this->PutLink($this->HREF, $e);
				else
					$this->Write(5, $e);
			} else {
				// Tag
				if ($e[0] == '/')
					$this->CloseTag(strtoupper(substr($e, 1)));
				else {
					// Extract attributes
					$a2 = explode(' ', $e);
					$tag = strtoupper(array_shift($a2));
					$attr = array();
					foreach ($a2 as $v) {
						if (preg_match('/([^=]*)=["\']?([^"\']*)/', $v, $a3))
							$attr[strtoupper($a3[1])] = $a3[2];
					}
					$this->OpenTag($tag, $attr);
				}
			}
		}
	}

	function OpenTag($tag, $attr)
	{
		// Opening tag
		if ($tag == 'B' || $tag == 'I' || $tag == 'U')
			$this->SetStyle($tag, true);
		if ($tag == 'A')
			$this->HREF = $attr['HREF'];
		if ($tag == 'BR')
			$this->Ln(5);
	}

	function CloseTag($tag)
	{
		// Closing tag
		if ($tag == 'B' || $tag == 'I' || $tag == 'U')
			$this->SetStyle($tag, false);
		if ($tag == 'A')
			$this->HREF = '';
	}

	function SetStyle($tag, $enable)
	{
		// Modify style and select corresponding font
		$this->$tag += ($enable ? 1 : -1);
		$style = '';
		foreach (array('B', 'I', 'U') as $s) {
			if ($this->$s > 0)
				$style .= $s;
		}
		$this->SetFont('', $style);
	}

	function PutLink($URL, $txt)
	{
		// Put a hyperlink
		$this->SetTextColor(0, 0, 255);
		$this->SetStyle('U', true);
		$this->Write(5, $txt, $URL);
		$this->SetStyle('U', false);
		$this->SetTextColor(0);
	}
}

$sell = ProposalData::getById($_GET["id"]);

$us = UserData::getById($sell->user_id);
$sdate = $sell->created_at;
$hora = date('h:m:s', strtotime($sdate));
$dia = date('d', strtotime($sdate));
$anio = date('Y', strtotime($sdate));
$mes = date('m', strtotime($sdate));
$operations = OperationPData::getAllProductsBySellId($sell->id);
$total = 0;

if ($mes == '01')
	$letra = 'Enero';
if ($mes == '02')
	$letra = 'Febrero';
if ($mes == '03')
	$letra = 'Marzo';
if ($mes == '04')
	$letra = 'Abril';
if ($mes == '05')
	$letra = 'Mayo';
if ($mes == '06')
	$letra = 'Junio';
if ($mes == '07')
	$letra = 'Julio';
if ($mes == '08')
	$letra = 'Agosto';
if ($mes == '09')
	$letra = 'Septiembre';
if ($mes == '10')
	$letra = 'Octubre';
if ($mes == '11')
	$letra = 'Noviembre';
if ($mes == '12')
	$letra = 'Diciembre';

$pdf  = new PDF('P', 'mm', 'letter');
$pdf->AliasNbPages();
$pdf->AddPage();

$pdf->SetFont('Arial', '', 10);


//set font to arial, bold, 14pt
$pdf->SetFont('Arial', 'B', 10);


$pdf->Cell(25);
//$pdf->Cell(87, 5, 'Nombre: ' . $client->getChance()->getPerson()->name, 0, 0);

$pdf->Cell(189, 10, '', 0, 1); //end of line

$pdf->Cell(189, 5, '', 0, 1); //end of line


//Numbers are right-aligned so we give 'R' after new line parameter
//display the items
$i = 11;
$c = count($operations);

$pdf->SetFont('Arial', 'B', 10);

$pdf->Cell(20, 5, 'Cantidad', 0, 0);
$pdf->Cell(110, 5, 'Detalle', 0, 0, 'C');
$pdf->Cell(25, 5, 'P/Unit.', 0, 0);
$pdf->Cell(20, 5, 'TOTAL', 0, 1); //end of line

$pdf->SetFont('Arial', '', 10);


$ic = $i - $c;
$subtotal = 0;
$u = 0;
foreach ($operations as $o) {
	$product = ProductProviderData::getById($o->product_id);
	$pu = ($product->price) * (1 / (1 - ($o->c_adm / 100))) * (1 / (1 - ($o->margin / 100))) * (1 / (1 - ($sell->imp / 100)));
	$pt = ($o->q * $pu);

	$pdf->Cell(20, 5, $o->q, 0, 0, 'C');
	$pdf->SetFont('Arial', '', 8);
	$pdf->Cell(110, 5, $product->getProduct()->name, 0, 0,'C');
	$pdf->SetFont('Arial', '', 10);
	$pdf->Cell(25, 5, number_format(round($pu,0,PHP_ROUND_HALF_UP), 2, '.', ','), 0, 0);
	$subtotal += round($pt,0,PHP_ROUND_HALF_UP);
	$pdf->Cell(20, 5, number_format(round($pt,0,PHP_ROUND_HALF_UP), 2, '.', ','), 0, 1, 'R'); //end of line
	$u += $subtotal;
}

while ($ic > 1) {
	$pdf->Cell(20, 5, "", 0, 0);
	$pdf->Cell(20, 5, "", 0, 0);
	$pdf->Cell(110, 5, "", 0, 0);
	//$pdf->Cell(25 ,5,"",1,0);
	$pdf->Cell(25, 5, "", 0, 0);
	$pdf->Cell(20, 5, "", 0, 1, 'R'); //end of line
	$ic = $ic - 1;
}
//$pdf->Cell(155, 5, 'SUBTOTAL BS.', 0, 0);
//$pdf->Cell(20, 5, number_format($subtotal, 2, '.', ','), 0, 1, 'R'); //end of line
$pdf->Cell(155, 5, 'TOTAL BS.', 0, 0);
$pdf->Cell(20, 5, number_format(round($subtotal,0,PHP_ROUND_HALF_UP), 2, '.', ','), 0, 1, 'R'); //end of line

$formatterES = new NumberFormatter("es-ES", NumberFormatter::SPELLOUT);
$n = $subtotal;
$izquierda = intval(floor($n));
$derecha = intval(($n - floor($n)) * 100);
$litdec = explode('.',$subtotal);
$literal = $formatterES->format($izquierda). " CON 00/100";
$pdf->Cell(175 ,5,"Son:".strtoupper($literal).' BOLIVIANOS',0,1);


//$pdf->SetY(-40);
$pdf->SetFont('Arial', 'I', 8);

$pdf->Cell(40, 5, 'Usuario:' . $us->name . ' ' . $us->lastname, 0, 0, 'C');
$pdf->Cell(70, 5, 'Hora:' . $hora, 0, 0, 'C');
$pdf->Cell(70, 5, '', 0, 1, 'C');

//$pdf->Output();
$attachdata = $pdf->Output('cotizacion.pdf','S');

require 'PHPMailer/PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "tls://mail.agtech-srl.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "asanchez@agtech-srl.com";
//Password to use for SMTP authentication
$mail->Password = "Alefortress8.";
//Set who the message is to be sent from
$mail->setFrom('asanchez@agtech-srl.com', 'Alejandro Sanchez');
//Set an alternative reply-to address
//$mail->addReplyTo('asanchez@vanaeph.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('wgonzalesm@gmail.com', 'John Doe');
//Set the subject line
$mail->Subject = 'Cotizacion Web';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->Body = "Detalle";

$mail->AddStringAttachment($attachdata, 'cotizacion.pdf');
if (!$mail->send()) {
	echo "Mailer Error: " . $mail->ErrorInfo;
} else {
	echo "Mensaje Enviado";
}
