<?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 ---
/**
 * consumo-report-pdf.php — Reporte Mensual de Consumo
 *
 * Parámetros GET:
 *   month  — YYYY-MM (default: mes actual)
 *   type   — medication | device | other (opcional, filtro por tipo de inventario)
 */

include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/UserData.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');

// Parámetros
$monthParam = $_GET['month'] ?? null;
$typeFilter = $_GET['type'] ?? null;

// Validar month
if (!$monthParam || !preg_match('/^\d{4}-\d{2}$/', $monthParam)) {
    $monthParam = date('Y-m');
}

// month_start y month_end
$monthStart = $monthParam . '-01 00:00:00';
$monthEnd = date('Y-m-t 23:59:59', strtotime($monthParam . '-01'));

// Nombre del mes
setlocale(LC_TIME, 'es_ES.UTF-8', 'Spanish_Spain', 'esp');
$monthName = strftime('%B', strtotime($monthParam . '-01'));
if (!$monthName || $monthName === $monthParam . '-01') {
    $monthName = date('F', strtotime($monthParam . '-01'));
}
$monthLabel = ucfirst($monthName) . ' ' . date('Y', strtotime($monthParam . '-01'));

// Validar type
$validTypes = ['medication', 'device', 'other'];
if ($typeFilter && !in_array($typeFilter, $validTypes, true)) {
    $typeFilter = null;
}

// Tablas de inventario
$invTables = [
    'medication' => 'inventory_medication',
    'device'      => 'inventory_device',
    'other'      => 'inventory_other',
];

$con = Database::getCon();

// ============================================================
// 1. KPIs
// ============================================================
$kpiWhere = "
    im.movement_type = 'exit'
    AND im.medication_administration_id IS NOT NULL
    AND im.created_at BETWEEN '" . $con->real_escape_string($monthStart) . "'
                          AND '" . $con->real_escape_string($monthEnd) . "'
";
if ($typeFilter) {
    $kpiWhere .= " AND inv_table = '" . $con->real_escape_string($invTables[$typeFilter]) . "'";
}

// Total de salidas (count)
$sqlKpiCount = "SELECT COUNT(*) AS total_salidas FROM inventory_movement im WHERE $kpiWhere";
$rsCount = $con->query($sqlKpiCount)->fetch_assoc();
$totalSalidas = (int)($rsCount['total_salidas'] ?? 0);

// Items distintos consumidos
$sqlKpiItems = "SELECT COUNT(DISTINCT CONCAT(im.inv_table, '-', im.item_id)) AS items_distintos
                FROM inventory_movement im WHERE $kpiWhere";
$rsItems = $con->query($sqlKpiItems)->fetch_assoc();
$itemsDistintos = (int)($rsItems['items_distintos'] ?? 0);

// Costo total estimado
$sqlKpiCost = "SELECT SUM(im.quantity * inv.last_cost) AS costo_total
               FROM inventory_movement im
               LEFT JOIN inventory_medication inv ON im.inv_table = 'inventory_medication' AND im.item_id = inv.id
               LEFT JOIN inventory_device invd ON im.inv_table = 'inventory_device' AND im.item_id = invd.id
               LEFT JOIN inventory_other invo ON im.inv_table = 'inventory_other' AND im.item_id = invo.id
               WHERE $kpiWhere";
$rsCost = $con->query($sqlKpiCost)->fetch_assoc();
$costoTotal = (float)($rsCost['costo_total'] ?? 0);

// Pacientes únicos
$sqlKpiPacs = "SELECT COUNT(DISTINCT ma.pacient_id) AS pacientes_unicos
               FROM inventory_movement im
               JOIN medication_administration ma ON im.medication_administration_id = ma.id
               WHERE $kpiWhere";
$rsPacs = $con->query($sqlKpiPacs)->fetch_assoc();
$pacientesUnicos = (int)($rsPacs['pacientes_unicos'] ?? 0);

// ============================================================
// 2. Top medicamentos más consumidos (TOP 25)
// ============================================================
$topWhere = $kpiWhere;
if ($typeFilter) {
    $topWhere .= " AND im.inv_table = '" . $con->real_escape_string($invTables[$typeFilter]) . "'";
} else {
    // Todos los tipos de inventario
    $topWhere .= " AND im.inv_table IN ('inventory_medication','inventory_device','inventory_other')";
}

$sqlTop = "
    SELECT
        im.inv_table,
        im.item_id,
        SUM(im.quantity) AS qty_total,
        COUNT(DISTINCT im.medication_administration_id) AS admin_count
    FROM inventory_movement im
    WHERE $topWhere
    GROUP BY im.inv_table, im.item_id
    ORDER BY qty_total DESC
    LIMIT 25
";
$rsTop = $con->query($sqlTop);

// Resolver nombres, códigos, costos y stock
$topItems = [];
$itemIds = [];
while ($row = $rsTop->fetch_assoc()) {
    $key = $row['inv_table'] . '-' . $row['item_id'];
    $itemIds[$key] = $row;
}

if ($itemIds) {
    foreach ($itemIds as $key => $row) {
        $tbl = $row['inv_table'];
        $id = $row['item_id'];
        $info = null;

        if ($tbl === 'inventory_medication') {
            $q = $con->query("SELECT code, name, presentation, last_cost, current_stock FROM inventory_medication WHERE id = $id");
            $info = $q->fetch_assoc();
            $tipo = 'Medicamento';
        } elseif ($tbl === 'inventory_device') {
            $q = $con->query("SELECT code, name, presentation, last_cost, current_stock FROM inventory_device WHERE id = $id");
            $info = $q->fetch_assoc();
            $tipo = 'Dispositivo';
        } elseif ($tbl === 'inventory_other') {
            $q = $con->query("SELECT code, name, presentation, last_cost, current_stock FROM inventory_other WHERE id = $id");
            $info = $q->fetch_assoc();
            $tipo = 'Otro';
        }

        if ($info) {
            $row['tipo'] = $tipo;
            $row['code'] = $info['code'] ?? 'S/C';
            $row['name'] = $info['name'] ?? 'Sin nombre';
            $row['presentation'] = $info['presentation'] ?? '';
            $row['last_cost'] = (float)($info['last_cost'] ?? 0);
            $row['current_stock'] = (float)($info['current_stock'] ?? 0);
            $row['costo_estimado'] = $row['qty_total'] * $row['last_cost'];
            $row['promedio_por_admin'] = $row['admin_count'] > 0
                ? $row['qty_total'] / $row['admin_count']
                : 0;
            $topItems[] = $row;
        }
    }
}

// Ordenar por qty_total DESC (el query ya lo hace, pero por si acaso)
usort($topItems, fn($a, $b) => $b['qty_total'] <=> $a['qty_total']);

// ============================================================
// 3. Pacientes top consumidores (TOP 10)
// ============================================================
$sqlPacs = "
    SELECT
        ma.pacient_id,
        p.name AS patient_name,
        p.lastname AS patient_lastname,
        COUNT(DISTINCT ma.id) AS total_admins,
        COUNT(DISTINCT CONCAT(im.inv_table, '-', im.item_id)) AS items_distintos,
        SUM(im.quantity) AS cantidad_total
    FROM inventory_movement im
    JOIN medication_administration ma ON im.medication_administration_id = ma.id
    LEFT JOIN pacient p ON ma.pacient_id = p.id
    WHERE $kpiWhere
    GROUP BY ma.pacient_id
    ORDER BY cantidad_total DESC
    LIMIT 10
";
$rsPacsTop = $con->query($sqlPacs);
$topPacientes = [];
while ($row = $rsPacsTop->fetch_assoc()) {
    $topPacientes[] = $row;
}

// ============================================================
// 4. Timeline — consumos por día
// ============================================================
$sqlTimeline = "
    SELECT
        DATE(im.created_at) AS dia,
        COUNT(*) AS eventos,
        SUM(im.quantity) AS cantidad
    FROM inventory_movement im
    WHERE $kpiWhere
    GROUP BY DATE(im.created_at)
    ORDER BY dia ASC
";
$rsTimeline = $con->query($sqlTimeline);
$timelineData = [];
while ($row = $rsTimeline->fetch_assoc()) {
    $timelineData[$row['dia']] = $row;
}

// Llenar todos los días del mes
$daysInMonth = (int)date('t', strtotime($monthParam . '-01'));
$timelineFull = [];
for ($d = 1; $d <= $daysInMonth; $d++) {
    $dayStr = sprintf('%s-%02d', $monthParam, $d);
    if (isset($timelineData[$dayStr])) {
        $timelineFull[] = $timelineData[$dayStr];
    } else {
        $timelineFull[] = ['dia' => $dayStr, 'eventos' => 0, 'cantidad' => 0];
    }
}

// ============================================================
// GENERACIÓN DEL PDF
// ============================================================
require_once __DIR__ . '/tcpdf/tcpdf.php';

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('Cedimik');
$pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Consumo Mensual - ' . $monthLabel);
$pdf->SetPrintHeader(true);
$pdf->SetPrintFooter(true);
$pdf->SetHeaderFont(['helvetica', '', 8]);
$pdf->SetFooterFont(['helvetica', '', 7]);
$pdf->SetMargins(15, 20, 15);
$pdf->SetHeaderMargin(8);
$pdf->SetFooterMargin(10);
$pdf->SetAutoPageBreak(true, 20);

// Header custom
$pdf->headerCallback = function ($pdf) {
    $pdf->Image(__DIR__ . '/assets/images/logo/logo.png', 160, 10, 25, 12, 'PNG');
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->SetY(10);
    $pdf->Cell(140, 7, 'CONSUMO MENSUAL', 0, 0, 'L');
    $pdf->Ln(6);
    $pdf->SetFont('helvetica', '', 9);
    $pdf->Cell(140, 5, 'Cedimik', 0, 1, 'L');
    $pdf->Ln(2);
};

$pdf->AddPage();
$pdf->SetFont('helvetica', '', 9);

// Título del mes
$pdf->SetFont('helvetica', 'B', 13);
$pdf->SetFillColor(102, 126, 234);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 9, '  CONSUMO MENSUAL — ' . strtoupper($monthLabel), 0, 1, 'C', true);
$pdf->SetTextColor(0, 0, 0);
$pdf->Ln(3);

// ============================================================
// KPIs
// ============================================================
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(0, 6, 'Resumen del periodo', 0, 1, 'L');
$pdf->Ln(1);

$kpiW = 46;
$kpiH = 22;
$x = $pdf->GetX();
$y = $pdf->GetY();

$kpis = [
    ['label' => 'Total Salidas', 'value' => number_format($totalSalidas), 'color' => [102, 126, 234], 'bg' => [237, 234, 252]],
    ['label' => 'Items Distintos', 'value' => number_format($itemsDistintos), 'color' => [102, 126, 234], 'bg' => [237, 234, 252]],
    ['label' => 'Costo Total Est.', 'value' => number_format($costoTotal, 2) . ' Bs', 'color' => [102, 126, 234], 'bg' => [237, 234, 252]],
    ['label' => 'Pacientes Unicos', 'value' => number_format($pacientesUnicos), 'color' => [102, 126, 234], 'bg' => [237, 234, 252]],
];

foreach ($kpis as $i => $kpi) {
    $kx = $x + $i * ($kpiW + 2);
    $pdf->SetXY($kx, $y);
    $pdf->SetFillColor($kpi['bg'][0], $kpi['bg'][1], $kpi['bg'][2]);
    $pdf->SetDrawColor($kpi['color'][0], $kpi['color'][1], $kpi['color'][2]);
    $pdf->Rect($kx, $y, $kpiW, $kpiH, 'DF');
    $pdf->SetXY($kx, $y + 3);
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetTextColor($kpi['color'][0], $kpi['color'][1], $kpi['color'][2]);
    $pdf->Cell($kpiW, 4, $kpi['label'], 0, 1, 'C');
    $pdf->SetX($kx);
    $pdf->SetFont('helvetica', 'B', 11);
    $pdf->Cell($kpiW, 8, $kpi['value'], 0, 1, 'C');
}
$pdf->SetTextColor(0, 0, 0);
$pdf->Ln($kpiH + 5);

// ============================================================
// TABLA PRINCIPAL — Top medicamentos
// ============================================================
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(0, 6, 'Top Medicamentos/Items Mas Consumidos', 0, 1, 'L');
$pdf->Ln(1);

if (count($topItems) === 0) {
    $pdf->SetFont('helvetica', 'I', 9);
    $pdf->Cell(0, 6, 'No hay consumo registrado en este periodo.', 0, 1, 'C');
    $pdf->Ln(3);
} else {
    $colW = [8, 20, 22, 42, 32, 18, 18, 20, 18];
    $totalW = array_sum($colW);

    // Header
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetFillColor(102, 126, 234);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetDrawColor(102, 126, 234);
    $headers = ['#', 'Tipo', 'Codigo', 'Nombre', 'Presentacion', 'Cantidad', 'Veces', 'Costo Est.', 'Stock'];
    foreach ($headers as $i => $h) {
        $pdf->Cell($colW[$i], 6, $h, 1, 0, 'C', true);
    }
    $pdf->Ln();

    // Rows
    $pdf->SetFont('helvetica', '', 7);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetDrawColor(200, 200, 200);
    $fill = false;
    foreach ($topItems as $idx => $item) {
        $pdf->SetFillColor($fill ? 245 : 250, $fill ? 245 : 250, $fill ? 245 : 250);
        $row = [
            $idx + 1,
            substr($item['tipo'], 0, 8),
            $item['code'] ?? 'S/C',
            substr($item['name'] ?? '', 0, 25),
            substr($item['presentation'] ?? '', 0, 22),
            number_format($item['qty_total'], 2),
            $item['admin_count'],
            number_format($item['costo_estimado'], 2),
            number_format($item['current_stock'], 2),
        ];
        foreach ($row as $ci => $cell) {
            $align = $ci === 2 || $ci === 3 ? 'L' : 'C';
            $pdf->Cell($colW[$ci], 5, $cell, 1, 0, $align, true);
        }
        $pdf->Ln();
        $fill = !$fill;
    }
    $pdf->Ln(5);
}

// ============================================================
// TABLA SECUNDARIA — Pacientes top
// ============================================================
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(0, 6, 'Top Pacientes Consumidores', 0, 1, 'L');
$pdf->Ln(1);

if (count($topPacientes) === 0) {
    $pdf->SetFont('helvetica', 'I', 9);
    $pdf->Cell(0, 6, 'No hay pacientes con administraciones en este periodo.', 0, 1, 'C');
    $pdf->Ln(3);
} else {
    $colW2 = [12, 60, 30, 30, 40];
    $headers2 = ['ID', 'Paciente', 'Total Admins', 'Items Dist.', 'Cantidad Total'];
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetFillColor(102, 126, 234);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetDrawColor(102, 126, 234);
    foreach ($headers2 as $i => $h) {
        $pdf->Cell($colW2[$i], 6, $h, 1, 0, 'C', true);
    }
    $pdf->Ln();

    $pdf->SetFont('helvetica', '', 7);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetDrawColor(200, 200, 200);
    $fill = false;
    foreach ($topPacientes as $p) {
        $pdf->SetFillColor($fill ? 245 : 250, $fill ? 245 : 250, $fill ? 245 : 250);
        $patientName = trim(($p['patient_name'] ?? '') . ' ' . ($p['patient_lastname'] ?? ''));
        if (empty($patientName)) {
            $patientName = 'Paciente #' . $p['pacient_id'];
        }
        $row = [
            $p['pacient_id'],
            substr($patientName, 0, 35),
            $p['total_admins'],
            $p['items_distintos'],
            number_format($p['cantidad_total'], 2),
        ];
        foreach ($row as $ci => $cell) {
            $align = $ci === 1 ? 'L' : 'C';
            $pdf->Cell($colW2[$ci], 5, $cell, 1, 0, $align, true);
        }
        $pdf->Ln();
        $fill = !$fill;
    }
    $pdf->Ln(5);
}

// ============================================================
// LINEA DE TIEMPO — consumos por dia
// ============================================================
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(0, 6, 'Linea de Tiempo — Consumos por Dia', 0, 1, 'L');
$pdf->Ln(1);

// Header de tabla de timeline
$colW3 = [28, 28, 38];
$headers3 = ['Fecha', 'Eventos', 'Cantidad Total'];
$pdf->SetFont('helvetica', 'B', 7);
$pdf->SetFillColor(102, 126, 234);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetDrawColor(102, 126, 234);
foreach ($headers3 as $i => $h) {
    $pdf->Cell($colW3[$i], 6, $h, 1, 0, 'C', true);
}
$pdf->Ln();

$pdf->SetFont('helvetica', '', 7);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetDrawColor(200, 200, 200);
$fill = false;
foreach ($timelineFull as $day) {
    $pdf->SetFillColor($fill ? 245 : 250, $fill ? 245 : 250, $fill ? 245 : 250);
    $fechaFormated = date('d/m/Y', strtotime($day['dia']));
    $row = [
        $fechaFormated,
        $day['eventos'],
        number_format($day['cantidad'], 2),
    ];
    foreach ($row as $ci => $cell) {
        $pdf->Cell($colW3[$ci], 5, $cell, 1, 0, 'C', true);
    }
    $pdf->Ln();
    $fill = !$fill;
}

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

$pdf->SetTextColor(0, 0, 0);

$pdf->Output('consumo-' . $monthParam . '.pdf', 'I');
