<?php
require '../../include/dompdf/autoload.inc.php';

use Dompdf\Dompdf;
use Dompdf\Options;

// Recibir datos desde JS
$alumno_nombre = isset($_POST['alumno_nombre']) ? trim($_POST['alumno_nombre']) : '';
$apoderado_nombre = isset($_POST['apoderado_nombre']) ? trim($_POST['apoderado_nombre']) : '';
$alumno_run = isset($_POST['alumno_run']) ? trim($_POST['alumno_run']) : '';
$sesiones_json = isset($_POST['sesiones']) ? $_POST['sesiones'] : '[]';

$sesiones = json_decode($sesiones_json, true);
if (!is_array($sesiones)) {
    $sesiones = [];
}

// Agrupar sesiones por especialidad
$agrupadas = [];
foreach ($sesiones as $s) {
    $esp = $s['especialidad'];
    if (!isset($agrupadas[$esp])) {
        $agrupadas[$esp] = [];
    }
    $agrupadas[$esp][] = [
        "fecha" => $s['fecha'],
        "hora" => $s['hora']
    ];
}

// Generar HTML de listas
$contenidoSesiones = '';
if (!empty($agrupadas)) {
    foreach ($agrupadas as $especialidad => $items) {
        $contenidoSesiones .= "<p><strong>" . htmlspecialchars($especialidad) . ":</strong></p>\n";
        $contenidoSesiones .= "<ol>";
        foreach ($items as $i) {
            $contenidoSesiones .= "<li>" . htmlspecialchars($i['fecha']) . " - " . htmlspecialchars($i['hora']) . "</li>";
        }
        $contenidoSesiones .= "</ol><br>";
    }
} else {
    $contenidoSesiones = "<p><em>No hay sesiones registradas.</em></p>";
}

$resumen_json = $_POST['resumen'] ?? '{}';
$resumen = json_decode($resumen_json, true);
$total_general = $_POST['total_general'] ?? 0;

$listaResumen = '<strong>Honorarios por Especialidad:</strong>';
foreach ($resumen as $esp => $valor) {
    $listaResumen .= "<p><strong>$esp: </strong>$".number_format($valor, 0, ",", ".")."</p>";
}
$listaResumen .= "<p><strong>Total de Honorarios:</strong> $".number_format($total_general, 0, ",", ".")."</p>";


// Fecha en español
setlocale(LC_TIME, 'es_ES.UTF-8');
$fecha = ucfirst(strftime('%e de %B de %Y'));

// Configuración de DomPDF
$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);

// Generar HTML del PDF
$html = <<<HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<style>
@page {
    margin-top: 1cm;
    margin-bottom: 1.5cm;
    margin-left: 2.6cm;
    margin-right: 2.6cm;
}
body {
    font-family: Arial, sans-serif;
    font-size: 10pt;
    line-height: 1.4;
    padding-top: 3cm; /* Igual al height del header */
}
p {
    text-align: justify;
}
header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 3cm;
    display: flex;
    align-items: center;
    padding-left: 0 cm;
    background-color: white;
    z-index: 10;
}
header img {
    height: 120px; /* Ajusta según el tamaño ideal */
}
    footer {
        position: fixed;
        bottom: -2.5cm;
        left: 2.6cm;
        right: 2.6cm;
        height: 2.5cm;
        font-size: 8pt;
        color: #666;
        text-align: center;
        border-top: 1px solid #ccc;
        padding-top: 5px;
        background: white;
    }
    ol {
        margin: 5px 0 15px 20px;
    }
</style>
</head>
<body>
<header>
    <img src="http://{$_SERVER['HTTP_HOST']}/assets/img/go.png">
    <!-- <img src="http://localhost/Cadip/assets/img/go.png">-->
</header>

<div style="text-align:center; margin-bottom:20px;">
    <h3>Detalle de Sesiones</h3>
</div>

<p>Estimado(a), $apoderado_nombre</p>

<p>Junto con saludar, y con fecha $fecha, se envía el detalle de las sesiones realizadas por el alumno<strong> $alumno_nombre</strong>, con el objetivo de mantener un registro claro y actualizado de su participación en las actividades correspondientes. <!--(RUN: $alumno_run):--></p>

<p>Desglose fecha y hora de las sesiones:</p>

$contenidoSesiones

$listaResumen

<p><strong>Importante:</strong> Los honorarios se deben abonar al inicio de cada mes. 
Si el alumno no puede asistir, debe avisarse con anticipación para reagendar.</p>

<footer>
    <p>Centro Pedagógico CADIP</p>
    <p>Avenida El Porvenir #901, Valle Grande. Lampa</p>
    <p>farratia@cadip.cl</p>
</footer>
</body>
</html>
HTML;

$dompdf->loadHtml($html);
$dompdf->setPaper('letter');
$dompdf->render();

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="informe_' . $alumno_nombre . '.pdf"');
echo $dompdf->output();
exit;
