<?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 ---
/**
 * estado-resultado-pdf.php — Export PDF del Estado de Resultado diario.
 *
 * Parámetros:
 *   preset = hoy | semana | mes_curso | mes_anterior | custom
 *   from/to = YYYY-MM-DD (cuando preset = custom)
 */

include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/UserData.php';
include __DIR__ . '/core/lib/DateHelper.php';

if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
$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');
    }
}
$generatedBy = 'Generado por: ' . $userName . ' | ' . date('d/m/Y H:i:s');

$preset = $_GET['preset'] ?? 'mes_curso';
$from   = $_GET['from']   ?? null;
$to     = $_GET['to']     ?? null;

$today = date('Y-m-d');
switch ($preset) {
    case 'hoy':
        $from = $today;
        $to = $today;
        $presetLabel = 'Hoy ' . date('d/m/Y', strtotime($today));
        break;
    case 'semana':
        $dow = date('N', strtotime($today));
        $from = date('Y-m-d', strtotime($today . ' -' . ($dow - 1) . ' days'));
        $to = date('Y-m-d', strtotime($today . ' +' . (7 - $dow) . ' days'));
        $presetLabel = 'Semana del ' . date('d/m/Y', strtotime($from)) . ' al ' . date('d/m/Y', strtotime($to));
        break;
    case 'mes_anterior':
        $from = date('Y-m-01', strtotime($today . ' -1 month'));
        $to = date('Y-m-t', strtotime($today . ' -1 month'));
        $presetLabel = DateHelper::monthName($from) . ' ' . date('Y', strtotime($from));
        break;
    case 'custom':
        $fromValid = $from && preg_match('/^\d{4}-\d{2}-\d{2}$/', $from);
        $toValid = $to && preg_match('/^\d{4}-\d{2}-\d{2}$/', $to);
        if (!$fromValid || !$toValid) {
            $from = date('Y-m-01');
            $to = $today;
            $presetLabel = 'Rango personalizado';
        } else {
            $presetLabel = 'Del ' . date('d/m/Y', strtotime($from)) . ' al ' . date('d/m/Y', strtotime($to));
        }
        break;
    case 'mes_curso':
    default:
        $from = date('Y-m-01');
        $to = $today;
        $presetLabel = DateHelper::monthName($from) . ' ' . date('Y', strtotime($from)) . ' (en curso)';
        break;
}

if (strtotime($from) > strtotime($to)) {
    [$from, $to] = [$to, $from];
}

$con = Database::getCon();
$fromEsc = $con->real_escape_string($from);
$toEsc = $con->real_escape_string($to);

$ingSql = "SELECT DATE(cp.created_at) as d, cp.billing_type as bt, SUM(cp.amount) as total
           FROM cotizacion_pago cp
           WHERE DATE(cp.created_at) BETWEEN '$fromEsc' AND '$toEsc'
           GROUP BY d, bt";
$ingQ = $con->query($ingSql);

$egrSql = "SELECT e.date as d, SUM(e.amount) as total
           FROM expense e
           WHERE e.is_active = 1
             AND e.status != 'rechazado'
             AND e.date BETWEEN '$fromEsc' AND '$toEsc'
           GROUP BY d";
$egrQ = $con->query($egrSql);

$conSql = "SELECT DATE(m.created_at) as d, SUM(m.quantity * i.last_cost) as total_costo
           FROM inventory_movement m
           INNER JOIN inventory_item i ON i.id = m.item_id
           WHERE m.movement_type = 'exit'
             AND DATE(m.created_at) BETWEEN '$fromEsc' AND '$toEsc'
           GROUP BY d";
$conQ = $con->query($conSql);

$days = [];
$cur = strtotime($from);
$end = strtotime($to);
while ($cur <= $end) {
    $key = date('Y-m-d', $cur);
    $days[$key] = [
        'date' => $key,
        'particular' => 0.0,
        'facturado' => 0.0,
        'total_ing' => 0.0,
        'egresos' => 0.0,
        'consumo' => 0.0,
        'resultado' => 0.0,
    ];
    $cur = strtotime('+1 day', $cur);
}

if ($ingQ) while ($r = $ingQ->fetch_assoc()) {
    $d = $r['d'];
    if (!isset($days[$d])) continue;
    $bt = $r['bt'];
    $amt = floatval($r['total']);
    if ($bt === 'particular' || $bt === 'facturado') {
        $days[$d][$bt] += $amt;
    } else {
        $days[$d]['particular'] += $amt;
    }
    $days[$d]['total_ing'] += $amt;
}
if ($egrQ) while ($r = $egrQ->fetch_assoc()) {
    $d = $r['d'];
    if (!isset($days[$d])) continue;
    $days[$d]['egresos'] += floatval($r['total']);
}
if ($conQ) while ($r = $conQ->fetch_assoc()) {
    $d = $r['d'];
    if (!isset($days[$d])) continue;
    $days[$d]['consumo'] += floatval($r['total_costo']);
}

$totParticular = 0.0;
$totFacturado = 0.0;
$totIng = 0.0;
$totEgr = 0.0;
$totCon = 0.0;
$totRes = 0.0;
foreach ($days as &$row) {
    $row['resultado'] = $row['total_ing'] - $row['egresos'] - $row['consumo'];
    $totParticular += $row['particular'];
    $totFacturado += $row['facturado'];
    $totIng += $row['total_ing'];
    $totEgr += $row['egresos'];
    $totCon += $row['consumo'];
    $totRes += $row['resultado'];
}
unset($row);

// === Render PDF ===
require_once 'tcpdf/tcpdf.php';

$pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8', false); // landscape: tabla ancha

$pdf->SetCreator('Cedimik');
$pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Estado de Resultado - ' . $presetLabel);
$pdf->SetSubject('Estado de Resultado diario consolidado particular/facturado');

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(10, 15, 10);
$pdf->SetAutoPageBreak(true, 15);
$pdf->SetFont('helvetica', '', 9);

$pdf->AddPage();

// Header
$logo = 'assets/images/logo/logo.png';
if (file_exists($logo)) {
    $pdf->Image($logo, 10, 8, 35, 18, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
}

$pdf->SetFont('helvetica', 'B', 16);
$pdf->SetXY(50, 10);
$pdf->Cell(0, 8, 'ESTADO DE RESULTADO', 0, 1, 'L');

$pdf->SetFont('helvetica', '', 10);
$pdf->SetXY(50, 19);
$pdf->Cell(0, 5, 'Periodo: ' . $presetLabel, 0, 1, 'L');

$pdf->SetXY(50, 24);
$pdf->SetFont('helvetica', '', 8);
$pdf->Cell(0, 4, 'Cedimik', 0, 1, 'L');

// Resumen
$pdf->Ln(5);
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(45, 6, 'TOTAL INGRESOS', 0, 0);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(50, 6, 'Bs ' . number_format($totIng, 2), 0, 0);

$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(55, 6, 'EGRESOS + CONSUMO', 0, 0);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(50, 6, 'Bs ' . number_format($totEgr + $totCon, 2), 0, 0);

$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(45, 6, 'RESULTADO NETO', 0, 0);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 6, ($totRes >= 0 ? '+' : '') . 'Bs ' . number_format($totRes, 2), 0, 1);

$pdf->Ln(3);

// Tabla
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(220, 220, 220);
$colWidths = [22, 32, 32, 32, 32, 32, 35];
$headers = ['Fecha', 'Ing. Particular', 'Ing. Facturado', 'Total Ingresos', 'Egresos', 'Consumo Stock', 'Resultado Neto'];
foreach ($headers as $i => $h) {
    $align = ($i === 0) ? 'L' : 'R';
    $pdf->Cell($colWidths[$i], 7, $h, 1, 0, $align, true);
}
$pdf->Ln();

$pdf->SetFont('helvetica', '', 8);
$fillRow = false;
foreach ($days as $d) {
    $empty = ($d['total_ing'] == 0 && $d['egresos'] == 0 && $d['consumo'] == 0);
    $pdf->SetFillColor(248, 248, 248);
    $pdf->Cell($colWidths[0], 6, date('d/m/Y', strtotime($d['date'])), 1, 0, 'L', $fillRow);
    $pdf->Cell($colWidths[1], 6, number_format($d['particular'], 2), 1, 0, 'R', $fillRow);
    $pdf->Cell($colWidths[2], 6, number_format($d['facturado'], 2), 1, 0, 'R', $fillRow);
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->Cell($colWidths[3], 6, number_format($d['total_ing'], 2), 1, 0, 'R', $fillRow);
    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell($colWidths[4], 6, number_format($d['egresos'], 2), 1, 0, 'R', $fillRow);
    $pdf->Cell($colWidths[5], 6, number_format($d['consumo'], 2), 1, 0, 'R', $fillRow);
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->Cell($colWidths[6], 6, ($d['resultado'] >= 0 ? '+' : '') . number_format($d['resultado'], 2), 1, 1, 'R', $fillRow);
    $pdf->SetFont('helvetica', '', 8);
    $fillRow = !$fillRow;
}

// Total al pie
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(230, 230, 230);
$pdf->Cell($colWidths[0], 7, 'TOTAL', 1, 0, 'L', true);
$pdf->Cell($colWidths[1], 7, number_format($totParticular, 2), 1, 0, 'R', true);
$pdf->Cell($colWidths[2], 7, number_format($totFacturado, 2), 1, 0, 'R', true);
$pdf->Cell($colWidths[3], 7, number_format($totIng, 2), 1, 0, 'R', true);
$pdf->Cell($colWidths[4], 7, number_format($totEgr, 2), 1, 0, 'R', true);
$pdf->Cell($colWidths[5], 7, number_format($totCon, 2), 1, 0, 'R', true);
$pdf->Cell($colWidths[6], 7, ($totRes >= 0 ? '+' : '') . number_format($totRes, 2), 1, 1, 'R', true);

// Footer
$pdf->Ln(5);
$pdf->SetFont('helvetica', 'I', 8);
$pdf->SetTextColor(120, 120, 120);
$pdf->Cell(0, 4, $generatedBy, 0, 1, 'R');
$pdf->SetTextColor(0, 0, 0);

$pdf->Output('estado_resultado_' . $from . '_' . $to . '.pdf', 'I');