<?php
// --- Auth gate: PDF standalone, sin sesión no se sirve ---
if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
if (empty($_SESSION['user_id'])) { header('Location: index.php?view=login'); exit; }
// --- end auth gate ---
/**
 * expenses_pdf.php — Monthly Expenses PDF Report
 *
 * Params (GET):
 *   year   = 4-digit year (default: current)
 *   month  = 1-12        (default: current)
 *   category = optional category filter
 *   status   = optional status filter (auto_aprobado|pendiente|aprobado|rechazado)
 *
 * Mirrors the filter set used by core/app/view/expenses-view.php so the PDF
 * matches the on-screen view.
 */

include __DIR__ . '/core/autoload.php';
include_once __DIR__ . '/core/app/model/ExpenseData.php';
include_once __DIR__ . '/core/app/model/UserData.php';
include_once Model::getFullPath('ExpenseData');
include_once Model::getFullPath('UserData');

// Session is already started by autoload.php
$userId = $_SESSION['user_id'] ?? null;
$userName = 'Sistema';
if ($userId) {
    $u = UserData::getById($userId);
    if ($u) {
        $n = trim(($u->name ?? '') . ' ' . ($u->lastname ?? ''));
        $userName = $n !== '' ? $n : ($u->username ?? 'Sistema');
    }
}

$year  = isset($_GET['year']) ? max(2000, min(2100, (int)$_GET['year'])) : (int)date('Y');
$month = isset($_GET['month']) ? max(1, min(12, (int)$_GET['month'])) : (int)date('m');
$category = isset($_GET['category']) ? trim((string)$_GET['category']) : '';
$status   = isset($_GET['status'])   ? trim((string)$_GET['status'])   : '';

$date_from = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-01";
$date_to   = date('Y-m-t', strtotime($date_from));

$monthNames = [
    1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril',
    5 => 'Mayo', 6 => 'Junio', 7 => 'Julio', 8 => 'Agosto',
    9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre'
];

$filters = ['date_from' => $date_from, 'date_to' => $date_to];
if ($category !== '') $filters['category'] = $category;
if ($status   !== '') $filters['status']   = $status;

$expenses = ExpenseData::getAll($filters);
$total    = ExpenseData::getGrandTotal($filters);
$byCategory = ExpenseData::getTotalByCategory($year, $month);
$byPayment  = ExpenseData::getTotalByPaymentMethod($year, $month);

// ─────────────────────────────────────────────────────────────────────────
// FPDF output must arrive clean — drop any buffered output (notices, BOM,
// whitespace from autoload) BEFORE FPDF sends its headers.
// ─────────────────────────────────────────────────────────────────────────
while (ob_get_level() > 0) { ob_end_clean(); }
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', '0');

require_once __DIR__ . '/fpdf/fpdf.php';

$pdf = new FPDF('P', 'mm', 'A4');
$pdf->AddPage();

// Header
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 10, 'REPORTE DE EGRESOS', 0, 1, 'C');
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(0, 6, 'Cedimik', 0, 1, 'C');
$pdf->Cell(0, 6, 'Periodo: ' . $monthNames[$month] . ' ' . $year, 0, 1, 'C');
$pdf->Cell(0, 6, 'Generado: ' . date('d/m/Y H:i') . ' | ' . $userName, 0, 1, 'C');
$pdf->Ln(3);

// Filter summary
$filterLines = [];
if ($category !== '') $filterLines[] = 'Categoria: ' . $category;
if ($status   !== '') $filterLines[] = 'Estado: '   . $status;
if (!empty($filterLines)) {
    $pdf->SetFont('Arial', 'I', 9);
    $pdf->Cell(0, 5, 'Filtros aplicados: ' . implode(' | ', $filterLines), 0, 1, 'C');
    $pdf->Ln(2);
}

// Summary
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, 'RESUMEN', 0, 1, 'L');
$pdf->SetFont('Arial', '', 10);
$pdf->SetTextColor(220, 0, 0);
$pdf->Cell(60, 6, 'Total Egresos:', 0, 0, 'L');
$pdf->Cell(0, 6, number_format((float)$total, 2) . ' Bs', 0, 1, 'L');
$pdf->SetTextColor(0);
$pdf->Cell(60, 6, 'Cantidad de Gastos:', 0, 0, 'L');
$pdf->Cell(0, 6, is_array($expenses) ? count($expenses) : 0, 0, 1, 'L');
$pdf->Ln(4);

// By category
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, 'EGRESOS POR CATEGORIA', 0, 1, 'L');
$pdf->SetFont('Arial', 'B', 9);
$pdf->SetFillColor(220, 220, 220);
$pdf->Cell(120, 7, 'Categoria', 1, 0, 'C', true);
$pdf->Cell(50, 7, 'Total', 1, 1, 'C', true);

$pdf->SetFont('Arial', '', 9);
if (is_array($byCategory) && count($byCategory) > 0) {
    foreach ($byCategory as $cat => $monto) {
        $pdf->SetTextColor(0);
        $pdf->Cell(120, 6, (string)($cat ?: 'Sin categoria'), 1, 0, 'L');
        $pdf->SetTextColor(220, 0, 0);
        $pdf->Cell(50, 6, number_format((float)$monto, 2) . ' Bs', 1, 1, 'R');
    }
} else {
    $pdf->SetTextColor(120, 120, 120);
    $pdf->Cell(170, 6, 'Sin datos en el periodo', 1, 1, 'C');
    $pdf->SetTextColor(0);
}
$pdf->SetTextColor(0);
$pdf->Ln(4);

// By payment method
if (is_array($byPayment) && count($byPayment) > 0) {
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(0, 8, 'EGRESOS POR METODO DE PAGO', 0, 1, 'L');
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->SetFillColor(220, 220, 220);
    $pdf->Cell(120, 7, 'Metodo', 1, 0, 'C', true);
    $pdf->Cell(50, 7, 'Total', 1, 1, 'C', true);
    $pdf->SetFont('Arial', '', 9);
    foreach ($byPayment as $pmt => $monto) {
        $pdf->SetTextColor(0);
        $pdf->Cell(120, 6, (string)($pmt ?: 'Sin especificar'), 1, 0, 'L');
        $pdf->SetTextColor(220, 0, 0);
        $pdf->Cell(50, 6, number_format((float)$monto, 2) . ' Bs', 1, 1, 'R');
    }
    $pdf->SetTextColor(0);
    $pdf->Ln(4);
}

// Detail
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, 'DETALLE DE EGRESOS', 0, 1, 'L');
$pdf->SetFont('Arial', 'B', 8);
$pdf->SetFillColor(200, 0, 0);
$pdf->SetTextColor(255);
$pdf->Cell(22, 7, 'Fecha', 1, 0, 'C', true);
$pdf->Cell(48, 7, 'Proveedor', 1, 0, 'C', true);
$pdf->Cell(48, 7, 'Concepto', 1, 0, 'C', true);
$pdf->Cell(30, 7, 'Categoria', 1, 0, 'C', true);
$pdf->Cell(22, 7, 'Pago', 1, 1, 'C', true);
$pdf->SetTextColor(0);

$pdf->SetFont('Arial', '', 8);
if (is_array($expenses) && count($expenses) > 0) {
    foreach ($expenses as $e) {
        $pdf->SetTextColor(0);
        $pdf->Cell(22, 6, date('d/m/Y', strtotime($e->date ?? 'now')), 1, 0, 'C');
        $pdf->Cell(48, 6, substr((string)($e->provider ?? '-'), 0, 25), 1, 0, 'L');
        $pdf->Cell(48, 6, substr((string)($e->concept ?? '-'), 0, 25), 1, 0, 'L');
        $pdf->Cell(30, 6, substr((string)($e->category ?? '-'), 0, 15), 1, 0, 'L');
        $pdf->SetTextColor(220, 0, 0);
        $pdf->Cell(22, 6, number_format((float)($e->amount ?? 0), 2), 1, 1, 'R');
    }
    $pdf->SetTextColor(0);
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->Cell(148, 7, 'TOTAL', 1, 0, 'R');
    $pdf->SetTextColor(220, 0, 0);
    $pdf->Cell(22, 7, number_format((float)$total, 2), 1, 1, 'R');
    $pdf->SetTextColor(0);
} else {
    $pdf->SetTextColor(120, 120, 120);
    $pdf->Cell(170, 6, 'Sin egresos en el periodo', 1, 1, 'C');
}

$pdf->Output('reporte_egresos_' . $year . str_pad($month, 2, '0', STR_PAD_LEFT) . '.pdf', 'I');
