<?php 
ob_start();
session_start();

if(!isset($_SESSION['user_type']) || $_SESSION['user_type'] != 'ciudadano'){
    header('location: ../login.php');
    exit;
}

require '../../backend/fpdf/fpdf.php';
date_default_timezone_set('America/Bogota');

// Función auxiliar para convertir UTF-8 a ISO-8859-1
function convertText($text) {
    if(empty($text)) return '';
    return mb_convert_encoding($text, 'ISO-8859-1', 'UTF-8');
}

class PDF extends FPDF
{
    function Header()
    {
        $this->Image('../../backend/img/ico.png',15,5,25);
        $this->Image('../../backend/img/neu.png',170,5,25);
        
        $this->SetFont('Arial', 'B', 14);
        $this->Cell(0, 10, convertText('PROGRAMA PERSONA MAYOR'), 0, 1, 'C');
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(0, 5, convertText('HISTORIA CLÍNICA'), 0, 1, 'C');
        $this->SetFont('Arial', '', 9);
        $this->Cell(0, 5, convertText('Municipio de Sibate - Cundinamarca'), 0, 1, 'C');
        $this->Cell(0, 5, convertText('Tel: 3229060608'), 0, 1, 'C');
        $this->Ln(3);
    }

    function Footer()
    {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(95,5,convertText('Página ').$this->PageNo().' / {nb}',0,0,'L');
        $this->Cell(95,5,date('d/m/Y | g:i:a'),0,1,'R');
        $this->Cell(0,5,convertText('© Todos los derechos reservados.'),0,0,'C');
    }
    
    function SectionTitle($title) {
        $this->SetFont('Arial', 'B', 11);
        $this->SetFillColor(102, 126, 234);
        $this->SetTextColor(255, 255, 255);
        $this->Cell(0, 8, convertText($title), 0, 1, 'L', true);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(2);
    }
}

$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();

$pdf->SetAutoPageBreak(true, 20);
$pdf->SetTopMargin(15);
$pdf->SetLeftMargin(10);
$pdf->SetRightMargin(10);

require '../../backend/bd/Conexion.php';

// Obtener el documento del ciudadano desde la sesión
$documento = $_SESSION['email'];

// Buscar el ID del paciente
$stmtId = $connect->prepare("SELECT idpa FROM patients WHERE numhs = :documento");
$stmtId->execute([':documento' => $documento]);
$patientId = $stmtId->fetch(PDO::FETCH_ASSOC);

if(!$patientId) {
    die('No se encontró información del paciente');
}

$id = $patientId['idpa'];

// ========== DATOS DEL USUARIO ==========
$pdf->SectionTitle('DATOS PERSONALES');

$stmt = $connect->prepare("SELECT * FROM patients WHERE idpa = :id");
$stmt->execute([':id' => $id]);
$patient = $stmt->fetch(PDO::FETCH_ASSOC);

if($patient) {
    $pdf->SetFont('Arial','B',9);
    $pdf->SetFillColor(230, 230, 230);
    $pdf->Cell(40, 7, convertText('Documento'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['numhs']),1,0,'L');
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(30, 7, convertText('Modalidad'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['modalidad']),1,1,'L');
    
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(40, 7, convertText('Nombres'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['nompa']),1,0,'L');
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(30, 7, convertText('Apellidos'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['apepa']),1,1,'L');
    
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(40, 7, convertText('Fecha Nacimiento'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['cump']),1,0,'L');
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(30, 7, convertText('Sexo'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['sex']),1,1,'L');
    
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(40, 7, convertText('Grupo Sanguíneo'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['grup']),1,0,'L');
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(30, 7, convertText('EPS'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['eps']),1,1,'L');
    
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(40, 7, convertText('Teléfono'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['phon']),1,0,'L');
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(30, 7, convertText('Correo'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(60, 7, convertText($patient['correo']),1,1,'L');
    
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(40, 7, convertText('Dirección'),1,0,'L',true);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(150, 7, convertText($patient['direc']),1,1,'L');
    
    $pdf->Ln(5);
}

// ========== CONSULTAS MÉDICAS ==========
$pdf->SectionTitle('CONSULTAS MÉDICAS');

try {
    $consultas = $connect->prepare("SELECT * FROM consult WHERE idpa = :id ORDER BY fere DESC LIMIT 5");
    $consultas->execute([':id' => $id]);
    $dataConsultas = $consultas->fetchAll(PDO::FETCH_ASSOC);

    if(count($dataConsultas) > 0) {
        foreach($dataConsultas as $c) {
            $pdf->SetFillColor(245, 245, 245);
            $pdf->SetFont('Arial','B',8);
            $pdf->Cell(190, 5, convertText('Consulta del: ' . date('d/m/Y H:i', strtotime($c['fere']))), 0, 1, 'L', true);
            $pdf->Ln(1);
            
            $pdf->SetFont('Arial','',9);
            $pdf->MultiCell(190, 5, convertText($c['mtcl']), 1, 'L');
            $pdf->Ln(2);
        }
        $pdf->Ln(3);
    } else {
        $pdf->SetFont('Arial','I',9);
        $pdf->Cell(0, 6, convertText('No hay consultas médicas registradas'),0,1,'L');
        $pdf->Ln(3);
    }
} catch(PDOException $e) {
    $pdf->SetFont('Arial','I',9);
    $pdf->Cell(0, 6, convertText('No hay consultas médicas registradas'),0,1,'L');
    $pdf->Ln(3);
}

// ========== MEDICAMENTOS ==========
$pdf->SectionTitle('MEDICAMENTOS ACTUALES');

try {
    $medicamentos = $connect->prepare("SELECT * FROM medicamentos WHERE idpa = :id ORDER BY fere DESC");
    $medicamentos->execute([':id' => $id]);
    $dataMeds = $medicamentos->fetchAll(PDO::FETCH_ASSOC);

    if(count($dataMeds) > 0) {
    foreach($dataMeds as $m) {
        $pdf->SetFillColor(245, 245, 245);
        $pdf->SetFont('Arial','B',8);
        $pdf->Cell(190, 5, convertText('Registro del: ' . date('d/m/Y H:i', strtotime($m['fere']))), 0, 1, 'L', true);
        $pdf->Ln(1);
        
        $pdf->SetFont('Arial','B',9);
        $pdf->SetFillColor(230, 230, 230);
        $pdf->Cell(50, 6, convertText('Medicamento'),1,0,'L',true);
        $pdf->SetFont('Arial','',9);
        $pdf->Cell(140, 6, convertText($m['medicamento']),1,1,'L');
        
        $pdf->SetFont('Arial','B',9);
        $pdf->Cell(50, 6, convertText('Dosis'),1,0,'L',true);
        $pdf->SetFont('Arial','',9);
        $pdf->Cell(140, 6, convertText($m['dosis']),1,1,'L');
        
        $pdf->SetFont('Arial','B',9);
        $pdf->Cell(50, 6, convertText('Frecuencia'),1,0,'L',true);
        $pdf->SetFont('Arial','',9);
        $pdf->Cell(140, 6, convertText($m['frecuencia']),1,1,'L');
        
        $pdf->SetFont('Arial','B',9);
        $pdf->Cell(50, 6, convertText('Vía Administración'),1,0,'L',true);
        $pdf->SetFont('Arial','',9);
        $pdf->Cell(140, 6, convertText($m['via']),1,1,'L');
        
        $pdf->Ln(2);
    }
    $pdf->Ln(3);
    } else {
        $pdf->SetFont('Arial','I',9);
        $pdf->Cell(0, 6, convertText('No hay medicamentos registrados'),0,1,'L');
        $pdf->Ln(3);
    }
} catch(PDOException $e) {
    $pdf->SetFont('Arial','I',9);
    $pdf->Cell(0, 6, convertText('No hay medicamentos registrados'),0,1,'L');
    $pdf->Ln(3);
}

// ========== TRATAMIENTOS ==========
$pdf->SectionTitle('TRATAMIENTOS');

try {
    $tratamientos = $connect->prepare("SELECT * FROM treatment WHERE idpa = :id ORDER BY fere DESC");
    $tratamientos->execute([':id' => $id]);
    $dataTrat = $tratamientos->fetchAll(PDO::FETCH_ASSOC);

    if(count($dataTrat) > 0) {
        foreach($dataTrat as $t) {
            $pdf->SetFillColor(245, 245, 245);
            $pdf->SetFont('Arial','B',8);
            $pdf->Cell(190, 5, convertText('Registro del: ' . date('d/m/Y H:i', strtotime($t['fere']))), 0, 1, 'L', true);
            $pdf->Ln(1);
            
            $pdf->SetFont('Arial','',9);
            $pdf->MultiCell(190, 5, convertText($t['nomtra']), 1, 'L');
            $pdf->Ln(2);
        }
        $pdf->Ln(3);
    } else {
        $pdf->SetFont('Arial','I',9);
        $pdf->Cell(0, 6, convertText('No hay tratamientos registrados'),0,1,'L');
        $pdf->Ln(3);
    }
} catch(PDOException $e) {
    $pdf->SetFont('Arial','I',9);
    $pdf->Cell(0, 6, convertText('No hay tratamientos registrados'),0,1,'L');
    $pdf->Ln(3);
}

// ========== NOTA FINAL ==========
$pdf->Ln(5);
$pdf->SetFont('Arial','I',8);
$pdf->SetTextColor(100, 100, 100);
$pdf->MultiCell(0, 4, convertText('NOTA: Este documento contiene información general de su historia clínica. Para información más detallada o específica, por favor consulte con el personal médico del programa.'), 0, 'L');

ob_end_clean();
$pdf->Output('I', 'Historia_Clinica_' . $documento . '.pdf');
?>
