<?php
// Iniciar buffering antes de cualquier salida
ob_start();

header('Content-Type: application/pdf');
error_reporting(0);
ini_set('display_errors', 0);

require_once(__DIR__ . '/fpdf/fpdf.php');
@require_once(__DIR__ . '/core/autoload.php');

date_default_timezone_set('America/La_Paz');

class PDF extends FPDF
{
	function Header()
	{
		$this->SetFont('Arial', 'B', 16);
		$this->Cell(0, 10, 'REPORTE DE VENTAS', 0, 1, 'C');
		$this->SetFont('Arial', '', 10);
		$this->Cell(0, 5, 'Fecha de generacion: ' . date('d/m/Y H:i:s'), 0, 1, 'C');
		$this->Ln(6);
	}

	function Footer()
	{
		$this->SetY(-15);
		$this->SetFont('Arial', 'I', 8);
		$this->Cell(0, 10, 'Pagina ' . $this->PageNo(), 0, 0, 'C');
	}
}

try {
	$startDate = isset($_POST['sd']) && $_POST['sd'] !== '' ? $_POST['sd'] : date('Y-m-01');
	$endDate = isset($_POST['ed']) && $_POST['ed'] !== '' ? $_POST['ed'] : date('Y-m-d');
	$clientId = isset($_POST['client_id']) ? (int) $_POST['client_id'] : 0;

	// Cargar modelos requeridos para consultas reales.
	$modelsPath = __DIR__ . '/core/app/model/';
	if (!class_exists('SellData') && file_exists($modelsPath . 'SellData.php')) {
		require_once($modelsPath . 'SellData.php');
	}
	if (!class_exists('OperationData') && file_exists($modelsPath . 'OperationData.php')) {
		require_once($modelsPath . 'OperationData.php');
	}
	if (!class_exists('ProductData') && file_exists($modelsPath . 'ProductData.php')) {
		require_once($modelsPath . 'ProductData.php');
	}
	if (!class_exists('PersonData') && file_exists($modelsPath . 'PersonData.php')) {
		require_once($modelsPath . 'PersonData.php');
	}
	if (!class_exists('UserData') && file_exists($modelsPath . 'UserData.php')) {
		require_once($modelsPath . 'UserData.php');
	}

	if (!class_exists('SellData')) {
		throw new Exception('No se pudo cargar el modelo SellData.');
	}

	$operations = array();

	if ($clientId > 0 && method_exists('SellData', 'getAllByDateBCOp')) {
		$operations = SellData::getAllByDateBCOp($clientId, $startDate, $endDate, 2);
	} else if (method_exists('SellData', 'getAllByDateOp')) {
		$operations = SellData::getAllByDateOp($startDate, $endDate, 2);
	}

	if (!is_array($operations)) {
		$operations = array();
	}

	$pdf = new PDF('P', 'mm', 'letter');
	$pdf->AddPage();

	$pdf->SetFont('Arial', 'B', 11);
	$pdf->Cell(30, 7, 'DEL:', 0, 0);
	$pdf->SetFont('Arial', '', 11);
	$pdf->Cell(0, 7, $startDate, 0, 1);

	$pdf->SetFont('Arial', 'B', 11);
	$pdf->Cell(30, 7, 'AL:', 0, 0);
	$pdf->SetFont('Arial', '', 11);
	$pdf->Cell(0, 7, $endDate, 0, 1);

	if ($clientId > 0) {
		$pdf->SetFont('Arial', 'B', 11);
		$pdf->Cell(30, 7, 'CLIENTE ID:', 0, 0);
		$pdf->SetFont('Arial', '', 11);
		$pdf->Cell(0, 7, $clientId, 0, 1);
	}

	$pdf->Ln(6);

	$pdf->SetFont('Arial', 'B', 10);
	$pdf->SetFillColor(220, 220, 220);
	$pdf->Cell(22, 7, 'Nro', 1, 0, 'C', true);
	$pdf->Cell(82, 7, 'Cliente', 1, 0, 'C', true);
	$pdf->Cell(28, 7, 'Monto', 1, 0, 'C', true);
	$pdf->Cell(28, 7, 'Tipo', 1, 0, 'C', true);
	$pdf->Cell(30, 7, 'Fecha', 1, 1, 'C', true);

	$grandTotal = 0.0;

	if (is_array($operations) && count($operations) > 0) {
		$pdf->SetFont('Arial', '', 9);
		foreach ($operations as $op) {
			if (isset($op->total) && (float) $op->total <= 0) {
				continue;
			}

			$clientName = 'N/D';
			if (class_exists('PersonData') && isset($op->person_id)) {
				$person = PersonData::getById((int) $op->person_id);
				if ($person && isset($person->id)) {
					$clientName = trim(($person->name ?? '') . ' ' . ($person->lastname ?? ''));
				}
			}
			if ($clientName === 'N/D' && class_exists('UserData') && isset($op->person_id)) {
				$user = UserData::getById((int) $op->person_id);
				if ($user && isset($user->id)) {
					$clientName = trim(($user->name ?? '') . ' ' . ($user->lastname ?? ''));
				}
			}
			if ($clientName === '') {
				$clientName = 'N/D';
			}

			$amount = 0.0;
			if (class_exists('OperationData') && isset($op->id)) {
				$sellOps = OperationData::getBySellId((int) $op->id);
				if (is_array($sellOps)) {
					foreach ($sellOps as $item) {
						$q = isset($item->q) ? (float) $item->q : 0.0;
						$disc = isset($item->disc) ? (float) $item->disc : 0.0;
						if ($disc > 0) {
							$amount += $q * $disc;
						} else {
							$priceOut = 0.0;
							if (method_exists($item, 'getProduct')) {
								$product = $item->getProduct();
								if ($product && isset($product->price_out)) {
									$priceOut = (float) $product->price_out;
								}
							}
							$amount += $q * $priceOut;
						}
					}
				}
			}

			if ($amount <= 0 && isset($op->total)) {
				$amount = (float) $op->total;
			}

			$type = isset($op->pay) ? $op->pay : 'N/D';
			$createdAt = isset($op->created_at) ? date('d/m/Y', strtotime($op->created_at)) : '';

			$pdf->Cell(22, 6, isset($op->id) ? $op->id : '', 1, 0, 'C');
			$pdf->Cell(82, 6, $clientName, 1, 0, 'L');
			$pdf->Cell(28, 6, number_format($amount, 2, '.', ','), 1, 0, 'R');
			$pdf->Cell(28, 6, $type, 1, 0, 'C');
			$pdf->Cell(30, 6, $createdAt, 1, 1, 'C');

			$grandTotal += $amount;
		}

		$pdf->SetFont('Arial', 'B', 10);
		$pdf->SetFillColor(240, 240, 240);
		$pdf->Cell(104, 7, 'TOTAL', 1, 0, 'R', true);
		$pdf->Cell(28, 7, number_format($grandTotal, 2, '.', ','), 1, 0, 'R', true);
		$pdf->Cell(58, 7, '', 1, 1, 'C', true);
	} else {
		$pdf->SetFont('Arial', '', 10);
		$pdf->Cell(190, 8, 'No hay datos disponibles por el momento.', 1, 1, 'C');
	}

	$pdf->Output();
} catch (Exception $e) {
	$pdf = new PDF('P', 'mm', 'letter');
	$pdf->AddPage();
	$pdf->SetFont('Arial', 'B', 14);
	$pdf->Cell(0, 10, 'ERROR EN REPORTE DE VENTAS', 0, 1, 'C');
	$pdf->Ln(8);
	$pdf->SetFont('Arial', '', 11);
	$pdf->MultiCell(0, 6, $e->getMessage());
	$pdf->Output();
}
