<?php
session_start();
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/ChanceData.php";
include "core/app/model/PersonData.php";
include "core/app/model/ProductData.php";
include "core/app/model/ProductStockData.php";
include "core/app/model/ProposalData.php";
include "core/app/model/ProposalDetailData.php";
include "core/app/model/UserData.php";


class PDF extends FPDF
{
	protected $widths;
	protected $aligns;

	function SetWidths($w)
	{
		// Set the array of column widths
		$this->widths = $w;
	}

	function SetAligns($a)
	{
		// Set the array of column alignments
		$this->aligns = $a;
	}

	function Row($data)
	{
		// Calculate the height of the row
		$nb = 0;
		for ($i = 0; $i < count($data); $i++)
			$nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
		$h = 5 * $nb;
		// Issue a page break first if needed
		$this->CheckPageBreak($h);
		// Draw the cells of the row
		for ($i = 0; $i < count($data); $i++) {
			$w = $this->widths[$i];
			$a = isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
			// Save the current position
			$x = $this->GetX();
			$y = $this->GetY();
			// Draw the border
			//$this->Rect($x, $y, $w, $h);
			// Print the text
			$this->MultiCell($w, 5, $data[$i], 0, $a);
			// Put the position to the right of the cell
			$this->SetXY($x + $w, $y);
		}
		// Go to the next line
		$this->Ln($h);
	}

	function CheckPageBreak($h)
	{
		// If the height h would cause an overflow, add a new page immediately
		if ($this->GetY() + $h > $this->PageBreakTrigger)
			$this->AddPage($this->CurOrientation);
	}

	function NbLines($w, $txt)
	{
		// Compute the number of lines a MultiCell of width w will take
		if (!isset($this->CurrentFont))
			$this->Error('No font has been set');
		$cw = $this->CurrentFont['cw'];
		if ($w == 0)
			$w = $this->w - $this->rMargin - $this->x;
		$wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize;
		$s = str_replace("\r", '', (string)$txt);
		$nb = strlen($s);
		if ($nb > 0 && $s[$nb - 1] == "\n")
			$nb--;
		$sep = -1;
		$i = 0;
		$j = 0;
		$l = 0;
		$nl = 1;
		while ($i < $nb) {
			$c = $s[$i];
			if ($c == "\n") {
				$i++;
				$sep = -1;
				$j = $i;
				$l = 0;
				$nl++;
				continue;
			}
			if ($c == ' ')
				$sep = $i;
			$l += $cw[$c];
			if ($l > $wmax) {
				if ($sep == -1) {
					if ($i == $j)
						$i++;
				} else
					$i = $sep + 1;
				$sep = -1;
				$j = $i;
				$l = 0;
				$nl++;
			} else
				$i++;
		}
		return $nl;
	}
	function Header()
	{

		//Logo
		$this->SetFillColor(0, 0, 0);
		$this->Image('logo_total.jpg', 130, 10, 60);
		$this->Cell(189, 20, '', 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', 25);
		$this->Cell(5, 5, 'PROFORMA', 0, 1, 'C');
		//$this->Cell(21, 5, 'Nro.' . $GLOBALS['bill'], 0, 1, 'C');
		$this->Cell(189, 15, '', 0, 1); //
		$this->SetFont('Arial', 'B', 16);
		$this->Cell(5, 4, '', 0, 0);
		$this->Cell(5, 8, 'FECHA', 0, 0,);
		$this->Cell(50);
		$this->Cell(5, 8, 'NRO PROFORMA', 0, 0);
		$this->Cell(60);
		$this->SetFont('Arial', '', 12);
		$this->Cell(60, 8, 'Av. Felipe Bestres, esquina', 0, 1);
		$this->Cell(15, 4, '', 0, 0);
		$this->Cell(5, 4, $GLOBALS['dia'] . '/' . $GLOBALS['mes'] . '/' . $GLOBALS['anio'], 0, 0);
		$this->Cell(50);
		$this->Cell(5, 4, $GLOBALS['bill'], 0, 0);
		$this->Cell(50);
		$this->Cell(60, 6, 'Av. Satelite, Ciudad Satelite - ', 0, 1);
		$this->Cell(125);
		$this->Cell(60, 6, 'El Alto, La Paz ', 0, 1);
		$this->Cell(125);
		$this->Cell(60, 6, '76222236-63167327', 0, 1);
		$this->Cell(125);
		$this->Cell(60, 6, 'ventas@vanaeph.com', 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);
	}

	function Footer()
	{

		$this->SetY(-20);
		$this->SetFont('Arial', 'B', 8);

		$this->Cell(60, 5, 'Vanaeph', 1, 0, 'C');
		$this->Cell(60, 5, 'Codigo: FRM-CMZ-001.00', 1, 0, 'C');
		$this->Cell(60, 5, 'V: 01/11/2022', 1, 1, 'C');
	}

	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);
	}
}
$prop = ProposalData::getById($_GET["id"]);
if ($prop->user_id > 0) {
	$us = UserData::getById($prop->user_id);
	$client = PersonData::getById(1);
} else {
	$us = UserData::getByPhone($prop->resp_id);
	//$client = PersonData::getById($prop->user_id);
}

$bill = $prop->id;
$sdate = $prop->created_at;
$hora = date('h:m:s', strtotime($sdate));
$dia = date('d', strtotime($sdate));
$anio = date('Y', strtotime($sdate));
$mes = date('m', strtotime($sdate));
$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();

//set font to arial, bold, 14pt
$pdf->SetFont('Arial', 'B', 14);
$pdf->Cell(5);
$pdf->Cell(87, 5, 'PARA: ', 0, 1);
$pdf->SetFont('Arial', '', 14);
$pdf->Cell(5);
$pdf->Cell(87, 10, $client->name, 0, 1); //end of line

$pdf->Cell(189, 5, '', 0, 1); //end of line
$pdf->SetFont('Arial', 'B', 12);

$pdf->Cell(20, 5, 'GARANTIA', 0, 0);
$pdf->Cell(50, 5, 'ENTREGA', 0, 0, 'C');
$pdf->Cell(55, 5, 'CONDICIONES DE PAGO', 0, 0);
$pdf->Cell(50, 5, 'VALIDEZ PROPUESTA', 0, 1);
$pdf->Cell(189, 4, '', 0, 1); //end of line
$pdf->SetFont('Arial', '', 12);

$pdf->Cell(20, 5, $prop->warranty . ' MESES', 0, 0);
$pdf->Cell(50, 5, $prop->delivery . ' DIAS', 0, 0, 'C');
$pdf->Cell(55, 5, 'CONTRAENTREGA', 0, 0);
$pdf->Cell(50, 5, $prop->validity . ' DIAS', 0, 1);
//Numbers are right-aligned so we give 'R' after new line parameter
//display the items
$pdf->Cell(189, 5, '', 0, 1); //end of line
//$c = count($operations);
$pdf->SetFont('Arial', 'B', 12);

$pdf->Cell(40, 5, 'CANTIDAD', 0, 0);
$pdf->Cell(70, 5, 'DESCRIPCION', 0, 0);
$pdf->Cell(45, 5, 'PRECIO UNITARIO', 0, 0);
$pdf->Cell(20, 5, 'TOTAL', 0, 1, 'R');
$pdf->Cell(189, 1, '___________________________________________________________________________', 0, 1); //end of lineend of line
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(189, 5, '', 0, 1); //end of line
//$pdf->Cell(30, 5, $prop->q, 0, 0, 'C');
$total = 0;
$details = ProposalDetailData::getAllByProposal($prop->id);
foreach ($details as $d) {
	//$product = ProductData::getById($d->product_id);
	//$txt = iconv('utf-8', 'cp1252', $product->name);
	//$factor = ($client->factor / 100) + 1;
	//$pdf->MultiCell(70, 5, $txt, 1, 0);
	//$pdf->Cell(20, 10, number_format(round($client->factor * $product->price_out, 0, PHP_ROUND_HALF_UP), 2, '.', ','), 0, 0);
	$pd = $d->getProductStock();
	$price =  round($pd->price * $prop->factor, 0, PHP_ROUND_HALF_UP);
	$subtotal = $price * $d->q;
	// $pdf->Cell(15, 10, number_format(round($client->factor * $product->price_out, 0, PHP_ROUND_HALF_UP) * $prop->q, 2, '.', ','), 0, 1, 'R'); //end of line

	$pdf->SetWidths(array(40, 70, 45, 20));
	//$pdf->Row(array($d->q, $txt, number_format(round($factor * $product->price_out, 0, PHP_ROUND_HALF_UP), 2, '.', ','), number_format(round($factor * $product->price_out, 0, PHP_ROUND_HALF_UP) * $d->q, 2, '.', ',')));
	$pdf->Row(array($d->q, $pd->brand . ' ' . $pd->code, number_format($price, 2, ".", ","), number_format($d->q * $price, 2, ".", ",")));
	$total += $subtotal;
}

$pdf->Cell(155, 10, 'TOTAL BS.', 0, 0, 'R');
$pdf->Cell(20, 10, number_format(round($total, 0, PHP_ROUND_HALF_UP), 2, '.', ','), 0, 1, 'R'); //end of line

$formatterES = new NumberFormatter("es-ES", NumberFormatter::SPELLOUT);
$n = $total;
$izquierda = intval(floor($n));
$derecha = intval(($n - floor($n)) * 100);
$litdec = explode('.', $total);
$literal = $formatterES->format($izquierda) . " CON 00/100";
$txt = iconv('utf-8', 'cp1252', $literal);
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(175, 5, " *SON:" . strtoupper($txt) . ' BOLIVIANOS', 0, 1);
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(20, 5, '*Precio facturado.', 0, 1); //end of line
//$pdf->Output();
//$pdf->Output('assets/images/quote/COTIZACION_'.$_GET["id"].'.pdf','F');
$n_c = 'Presupuesto - VNP_COT_' . $bill . '_2024';
$pdf->Output($n_c . '.pdf', 'I');
