<?php

if (ob_get_level() === 0) {
	ob_start();
}

include('bd.php');
require('fpdf/fpdf.php');
require('alphapdf.php');
date_default_timezone_set("America/La_Paz");

include "core/autoload.php";
include "core/app/model/SellData.php";
include "core/app/model/UserData.php";
include "core/app/model/SpendBoxData.php";
include "core/app/model/OperationData.php";
include "core/app/model/OperationTypeData.php";

class PDF extends AlphaPDF
{
	function Header()
	{
		$dia = date('d');
		$anio = date('Y');
		$mes = date('m');

		$this->SetFillColor(0, 0, 0);
		$logoPath = __DIR__ . '/logo.jpg';
		if (file_exists($logoPath)) {
			$this->Image($logoPath, 0, 2, 45);
		}

		$this->SetFont('Arial', 'B', 8);
		$this->Cell(30);
		$this->Cell(21, 5, 'PLASTICOS BAUTISTA | A & B', 0, 0, 'C');
		$this->Cell(100);
		$this->SetFont('Arial', 'B', 9);
		$this->Cell(21, 5, 'COCHABAMBA', 0, 1, 'C');
		$this->Cell(20);
		$this->Cell(31, 5, 'A & B', 0, 0, 'C');
		$this->Cell(25);
		$this->SetFont('Arial', 'B', 12);
		$this->Cell(31, 5, 'GASTOS CAJA CHICA', 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, 'ANO', 0, 1, 'C');

		$this->SetFont('Arial', '', 8);
		$this->Cell(31, 4, 'Km. 7.5 carretera Sacaba', 0, 0);
		$this->Cell(108);
		$this->Cell(15, 4, $dia, 0, 0, 'C');
		$this->Cell(15, 4, $mes, 0, 0, 'C');
		$this->Cell(15, 4, $anio, 0, 1, 'C');
		$this->Cell(31, 4, 'Esmeralda Norte - Zona Puntiti', 0, 1);
		$this->Cell(31, 4, 'Telf: 4245622 - 76418600 - 76490462', 0, 1);
		$this->Cell(31, 4, 'Email: ventas@plasticosbautista-ayb.com', 0, 1);
		$this->Cell(31, 4, 'www.plasticosbautista-ayb.com', 0, 1);

		$this->Ln(5);

		$fondoPath = __DIR__ . '/fondo.png';
		if (file_exists($fondoPath)) {
			$this->SetAlpha(0.1);
			$this->Image($fondoPath, 16, 100, 180);
			$this->SetAlpha(1);
		}
	}

	function Footer()
	{
		$this->SetY(-15);
		$this->Cell(70, 5, 'Generado por', 0, 0, 'C');
		$this->Cell(70, 5, '', 0, 0, 'C');
		$this->Cell(70, 5, 'V.B.', 0, 0, 'C');
	}
}

function isValidDateYmd($date)
{
	if (!is_string($date) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
		return false;
	}
	$dt = DateTime::createFromFormat('Y-m-d', $date);
	return $dt && $dt->format('Y-m-d') === $date;
}

$defaultStart = date("Y-m-01");
$defaultEnd = date("Y-m-d");
$fi = isset($_POST["sd"]) ? $_POST["sd"] : $defaultStart;
$ff = isset($_POST["ed"]) ? $_POST["ed"] : $defaultEnd;
$user_id = isset($_POST["user_id"]) ? $_POST["user_id"] : "";
$useStaticData = isset($_POST["static_data"]) || isset($_GET["static_data"]) || isset($_POST["debug_static"]) || isset($_GET["debug_static"]);
$dbErrorMsg = "";

if (!isValidDateYmd($fi)) {
	$fi = $defaultStart;
}
if (!isValidDateYmd($ff)) {
	$ff = $defaultEnd;
}
if ($fi > $ff) {
	$tmp = $fi;
	$fi = $ff;
	$ff = $tmp;
}

if ($useStaticData) {
	$operations = array();
} else {
	try {
		if ($user_id == "") {
			$operations = SpendBoxData::getAllByDateOp($fi, $ff);
		} else {
			$operations = SpendBoxData::getAllByDateBCOp($user_id, $fi, $ff, 0);
		}
		if (!is_array($operations)) {
			$operations = array();
		}
	} catch (Throwable $e) {
		$operations = array();
		$dbErrorMsg = "No se pudo consultar la base de datos para gastos.";
		$useStaticData = true;
	}
}

$supertotal = 0;

if ($useStaticData) {
	$operations = array(
		(object) array("code" => "G-001", "name" => "Combustible", "description" => "Visita comercial", "spend" => 350.50, "created_at" => $fi . " 09:00:00"),
		(object) array("code" => "G-002", "name" => "Almuerzo", "description" => "Reunion con proveedor", "spend" => 120.00, "created_at" => $fi . " 13:30:00"),
		(object) array("code" => "G-003", "name" => "Papeleria", "description" => "Compra de materiales", "spend" => 89.90, "created_at" => $ff . " 11:10:00")
	);
}

$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();

$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(0, 5, 'DEL: ' . $fi, 1, 1);
$pdf->Cell(0, 5, 'AL: ' . $ff, 1, 1);
$pdf->SetFont('Arial', '', 8);
if ($useStaticData) {
	$pdf->SetTextColor(200, 0, 0);
	$pdf->Cell(0, 5, 'MODO PRUEBA: datos estaticos', 1, 1);
	$pdf->SetTextColor(0, 0, 0);
}
if ($dbErrorMsg != "") {
	$pdf->SetTextColor(180, 0, 0);
	$pdf->Cell(0, 5, $dbErrorMsg, 1, 1);
	$pdf->SetTextColor(0, 0, 0);
}
$pdf->Cell(189, 10, '', 0, 1);

$pdf->Cell(10, 5, 'Nro', 1, 0);
$pdf->Cell(35, 5, 'Concepto', 1, 0, 'C');
$pdf->Cell(75, 5, 'Descripcion', 1, 0);
$pdf->Cell(25, 5, 'Total', 1, 0);
$pdf->Cell(25, 5, 'Usuario', 1, 0);
$pdf->Cell(20, 5, 'Fecha', 1, 1);

$pdf->SetFont('Arial', '', 8);
foreach ($operations as $o) {
	$userName = "-";
	if (!$useStaticData && method_exists($o, "getUser")) {
		$user = $o->getUser();
		$userName = $user ? $user->name : "-";
	}
	$pdf->Cell(10, 5, $o->code, 1, 0);
	$pdf->Cell(35, 5, $o->name, 1, 0);
	$pdf->Cell(75, 5, $o->description, 1, 0);
	$pdf->Cell(25, 5, 'Bs.' . number_format($o->spend, 2, '.', ','), 1, 0);
	$pdf->Cell(25, 5, $userName, 1, 0);
	$dt = date_create($o->created_at);
	$df = $dt ? date_format($dt, 'd/m/Y') : '-';
	$pdf->Cell(20, 5, $df, 1, 1, 'R');
	$supertotal += (float)$o->spend;
}

$pdf->SetFont('Arial', '', 20);
$pdf->Cell(25, 5, '', 0, 1);
$pdf->Cell(25, 5, 'TOTAL BS.' . number_format($supertotal, 2, '.', ','), 0, 0);

while (ob_get_level() > 0) {
	ob_end_clean();
}

$pdf->Output();
