<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="Historia clínica de {{ $model->patient()->first()->firstname . ' ' . $model->patient()->first()->lastname }}">
  <meta name="author" content="{{ $model->user()->first()->profile ? $model->user()->first()->profile->firstname . ' ' . $model->user()->first()->profile->lastname : $model->user()->first()->name }}">
  <meta name="generator" content="Medical Center PDF Generator">
  <title>Historia Clínica - {{ $model->patient()->first()->firstname . " " . $model->patient()->first()->lastname }}</title>
  <style type="text/css">
    @page {
      margin: 1.8cm;
      size: A4;
    }
    
    body {
      font-family: 'Roboto', 'Helvetica Neue', 'Helvetica', sans-serif;
      color: #2c3e50;
      line-height: 1.6;
      margin: 0;
      padding: 0;
      background-color: white;
      font-size: 10pt;
    }
    
    /* Contenedor principal */
    .container {
      width: 100%;
      margin: 0;
      padding: 0;
    }
    
    /* Encabezado */
    .header {
      width: 100%;
      border-bottom: 3px solid #1976D2;
      padding-bottom: 15px;
      margin-bottom: 25px;
      display: table;
      background: linear-gradient(to right, #f8f9fa 0%, white 100%);
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
      border-radius: 8px 8px 0 0;
    }
    
    .header-logo {
      display: table-cell;
      width: 150px;
      text-align: center;
      vertical-align: middle;
      padding: 10px;
    }
    
    .header-info {
      display: table-cell;
      vertical-align: top;
      padding-left: 20px;
      border-left: 1px solid #eaeaea;
    }
    
    .header img {
      max-width: 120px;
      max-height: 80px;
      border-radius: 6px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.12);
    }
    
    h1, h2, h3, h4, h5 {
      margin-top: 0;
      color: #263238;
      font-weight: 600;
      letter-spacing: -0.02em;
    }
    
    .clinic-name {
      font-size: 20pt;
      font-weight: bold;
      color: #1976D2;
      margin-top: 0;
      margin-bottom: 5px;
      letter-spacing: 0.5px;
      text-shadow: 0 1px 1px rgba(0,0,0,0.05);
    }
    
    .clinic-specialty {
      font-style: italic;
      margin: 2px 0;
      color: #607D8B;
      font-size: 10pt;
    }
    
    .clinic-contact {
      font-size: 9pt;
      color: #607D8B;
      margin: 5px 0;
      line-height: 1.4;
    }
    
    .history-number {
      font-size: 11pt;
      font-weight: bold;
      margin-top: 10px;
      color: #2c3e50;
      border-top: 1px solid #ecf0f1;
      padding-top: 8px;
    }
    
    /* Datos del paciente */
    .patient-info {
      background-color: #F5F7FA;
      border-radius: 8px;
      margin-bottom: 25px;
      padding: 18px;
      border: 1px solid #E3E8F0;
      box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    /* Estilos generales para tablas */
    table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 20px;
      border-radius: 6px;
      overflow: hidden;
      box-shadow: 0 1px 6px rgba(0,0,0,0.05);
    }
    
    th, td {
      padding: 10px 12px;
      text-align: left;
      vertical-align: top;
      font-size: 10pt;
      border: 1px solid #E3E8F0;
    }
    
    .label {
      font-weight: 600;
      color: #455A64;
      width: 30%;
      background-color: #F5F7FA;
      border-right: 2px solid #E3E8F0;
    }
    
    .value {
      width: 70%;
      color: #37474F;
    }
    
    /* Secciones */
    .section {
      margin-bottom: 30px;
      break-inside: avoid;
    }
    
    .section-title {
      font-size: 13pt;
      font-weight: bold;
      text-transform: uppercase;
      background: linear-gradient(to right, #1976D2, #2196F3);
      color: white;
      padding: 10px 14px;
      margin-bottom: 15px;
      border-radius: 6px;
      letter-spacing: 1px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
      text-shadow: 0 1px 1px rgba(0,0,0,0.2);
    }
    
    .subsection {
      margin-bottom: 18px;
      break-inside: avoid;
      padding: 0 5px;
    }
    
    .subsection-title {
      font-size: 11pt;
      font-weight: bold;
      color: #1976D2;
      margin-bottom: 10px;
      border-bottom: 1px solid #E3E8F0;
      padding-bottom: 6px;
      letter-spacing: 0.3px;
    }
    
    /* Controles */
    .control {
      margin-bottom: 25px;
      page-break-inside: avoid !important;
      break-inside: avoid !important;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #E3E8F0;
    }
    
    .control-header {
      background-color: #f8f9fa;
      padding: 10px;
      border-bottom: 1px solid #e1e8ed;
      display: flex;
      justify-content: space-between;
    }
    
    .control-date {
      font-weight: bold;
      color: #3498db;
    }
    
    .control-doctor {
      color: #7f8c8d;
      font-style: italic;
    }
    
    .control-content {
      padding: 10px;
      background-color: white;
    }
    
    /* Tabla de Contenido */
    .toc {
      margin-bottom: 30px;
      background-color: #F5F7FA;
      padding: 20px;
      border-radius: 8px;
      border: 1px solid #E3E8F0;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
      page-break-inside: avoid;
    }
    
    .toc-title {
      font-size: 14pt;
      font-weight: bold;
      color: #1976D2;
      margin-bottom: 15px;
      text-align: center;
      border-bottom: 2px solid #1976D2;
      padding-bottom: 8px;
      text-transform: uppercase;
      letter-spacing: 1.5px;
    }
    
    .toc-entry {
      margin: 6px 0;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px dotted #E3E8F0;
      padding-bottom: 3px;
      font-size: 10pt;
    }
    
    .toc-section {
      font-weight: bold;
      color: #2c3e50;
    }
    
    .toc-page {
      font-weight: bold;
      color: #1976D2;
    }
    
    /* Mini-encabezado para páginas subsecuentes */
    .mini-header {
      font-size: 10pt;
      text-align: right;
      color: #607D8B;
      margin-bottom: 15px;
      padding-bottom: 8px;
      border-bottom: 1px solid #E3E8F0;
    }
    
    /* Salto de página */
    .page-break {
      page-break-before: always;
    }
    
    /* Diagnóstico */
    .diagnosis {
      background-color: #F5F7FA;
      border-left: 4px solid #1976D2;
      padding: 16px;
      margin-bottom: 25px;
      border-radius: 0 8px 8px 0;
      box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    }
    
    .diagnosis-content {
      color: #37474F;
      font-style: italic;
      line-height: 1.6;
    }
    
    /* Pie de página */
    .footer {
      position: relative;
      margin-top: 30px;
      padding: 10px 0;
      width: 100%;
      font-size: 8pt;
      text-align: center;
      color: #78909C;
      border-top: 1px solid #E3E8F0;
      background-color: #F5F7FA;
      border-radius: 4px;
    }
    
    .footer-spacer {
      height: 60px;
      clear: both;
      margin-bottom: 30px;
    }
    
    /* Estilos para elementos específicos */
    .doctor-name, .patient-name {
      font-weight: bold;
      color: #2c3e50;
    }
    
    .highlight {
      color: #3498db;
      font-weight: bold;
    }
    
    .page-number:before {
      content: "Página " counter(page);
    }
    
    /* Mejoras adicionales */
    .antecedent-item, .physical-exam-item {
      padding: 14px;
      margin-bottom: 15px;
      background-color: #ffffff;
      border-radius: 6px;
      box-shadow: 0 1px 4px rgba(0,0,0,0.05);
      border-left: 3px solid #1976D2;
      line-height: 1.6;
    }
    
    .watermark {
      position: fixed;
      bottom: 40%;
      width: 100%;
      text-align: center;
      opacity: 0.06;
      transform: rotate(-45deg);
      font-size: 60pt;
      z-index: -1;
      color: #3498db;
      text-transform: uppercase;
      font-weight: bold;
      letter-spacing: 10px;
    }
    
    /* Estilos profesionales adicionales */
    .professional-signature {
      margin-top: 40px;
      text-align: center;
      background-color: #F5F7FA;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    }

    .signature-line {
      border-top: 1px solid #455A64;
      width: 60%;
      margin: 0 auto;
      padding-top: 10px;
    }

    .signature-name {
      font-weight: bold;
      margin-bottom: 0;
      font-size: 11pt;
      color: #37474F;
    }

    .signature-title {
      font-style: italic;
      font-size: 9pt;
      color: #607D8B;
      margin-top: 4px;
    }
    
    .medical-license {
      font-size: 9pt;
      color: #607D8B;
      margin-top: 4px;
    }
    
    .secure-doc {
      margin-top: 10px;
      font-size: 7pt;
      color: #95a5a6;
      text-align: center;
    }
    
    .qr-code {
      text-align: right;
      margin-bottom: 10px;
    }
    
    /* Mejoras para títulos de secciones principales */
    .main-section-header {
      text-align: center;
      margin: 35px 0 25px;
      padding: 12px;
      background: linear-gradient(135deg, #1976D2, #2196F3);
      color: white;
      border-radius: 8px;
      box-shadow: 0 3px 10px rgba(0,0,0,0.1);
      font-size: 16pt;
      font-weight: bold;
      text-transform: uppercase;
      letter-spacing: 1.5px;
      position: relative;
      text-shadow: 0 1px 2px rgba(0,0,0,0.2);
    }
    
    .main-section-header:before {
      content: "";
      position: absolute;
      height: 3px;
      width: 100%;
      background: linear-gradient(to right, #1976D2, #2196F3);
      bottom: -3px;
      left: 0;
    }
    
    .section-spacer {
      border-top: 1px dashed #E3E8F0;
      margin: 30px 0;
      height: 1px;
    }

    /* Espaciado adicional para la primera página */
    .first-page-spacer {
      height: 60px;
      clear: both;
    }
    
    /* Mejorar espaciado entre elementos de la página */
    .patient-info {
      margin-bottom: 60px !important;
    }
    
    .diagnosis-section {
      margin-bottom: 60px !important;
    }
    
    .toc {
      margin-top: 60px !important;
      margin-bottom: 60px !important;
    }
    
    /* Estilos para controles y exámenes físicos de controles */
    .control-section-title {
      font-size: 11pt;
      font-weight: bold;
      color: #3498db;
      margin: 15px 0 10px;
      padding-bottom: 5px;
      border-bottom: 1px solid #e1e8ed;
    }
    
    .control-description {
      margin-bottom: 15px;
      line-height: 1.6;
    }
    
    .control-physical-exam {
      background-color: #f9f9f9;
      padding: 10px;
      border-radius: 5px;
      margin-top: 15px;
      border: 1px solid #e1e8ed;
    }
    
    .control-exam-table {
      border-collapse: collapse;
      margin: 10px 0;
    }
    
    .control-exam-table td {
      padding: 8px;
      border-bottom: 1px solid #e1e8ed;
    }
    
    .control-exam-label {
      font-weight: bold;
      color: #3498db;
      width: 30%;
      background-color: #f5f7f8;
    }
    
    .control-exam-value {
      width: 70%;
    }
    
    .control-diagnosis {
      margin-top: 15px;
      padding: 10px;
      background-color: #f8f9fa;
      border-left: 3px solid #3498db;
      border-radius: 0 4px 4px 0;
    }

    @media print {
      .controls-section {
        page-break-before: always;
      }
    }

    /* Estilos para elementos de score médico */
    .score-indicator {
      display: inline-flex;
      align-items: center;
      margin-left: 10px;
      vertical-align: middle;
    }
    
    .score-dots {
      display: inline-flex;
      gap: 3px;
    }
    
    .score-dot {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      display: inline-block;
    }
    
    .score-dot-empty {
      background-color: #E0E0E0;
      border: 1px solid #BDBDBD;
    }
    
    .score-dot-fill {
      background-color: #2196F3;
      border: 1px solid #1976D2;
      box-shadow: 0 0 3px rgba(33, 150, 243, 0.5);
    }
    
    .score-dot-warning {
      background-color: #FFC107;
      border: 1px solid #FFA000;
      box-shadow: 0 0 3px rgba(255, 193, 7, 0.5);
    }
    
    .score-dot-danger {
      background-color: #F44336;
      border: 1px solid #1976D2;
      box-shadow: 0 0 3px rgba(244, 67, 54, 0.5);
    }
    
    .score-label {
      font-size: 8pt;
      color: #757575;
      margin-left: 5px;
    }
    
    .score-bar {
      height: 8px;
      width: 100px;
      background-color: #E0E0E0;
      border-radius: 4px;
      margin-left: 5px;
      overflow: hidden;
      position: relative;
    }
    
    .score-fill {
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      border-radius: 4px;
    }
    
    .score-scale {
      display: inline-flex;
      align-items: center;
      margin-left: 10px;
    }
    
    .score-scale-label {
      font-size: 8pt;
      color: #757575;
      width: 35px;
      text-align: right;
      margin-right: 5px;
    }
    
    .score-scale-value {
      font-weight: bold;
      color: #455A64;
    }
    
    .score-progress {
      width: 120px;
      height: 10px;
      background-color: #f5f5f5;
      border-radius: 5px;
      position: relative;
      overflow: hidden;
      border: 1px solid #e0e0e0;
    }
    
    .score-progress-fill {
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      border-radius: 5px;
    }
    
    /* Indicador de nivel de riesgo */
    .risk-indicator {
      display: inline-flex;
      align-items: center;
      padding: 3px 8px;
      border-radius: 20px;
      font-size: 8pt;
      font-weight: bold;
      margin-left: 10px;
      color: white;
    }
    
    .risk-low {
      background-color: #4CAF50;
      box-shadow: 0 1px 3px rgba(76, 175, 80, 0.3);
    }
    
    .risk-medium {
      background-color: #FFC107;
      box-shadow: 0 1px 3px rgba(255, 193, 7, 0.3);
    }
    
    .risk-high {
      background-color: #F44336;
      box-shadow: 0 1px 3px rgba(244, 67, 54, 0.3);
    }
    
    /* Dashboard clínico */
    .clinical-dashboard {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 15px;
      margin-top: 20px;
      margin-bottom: 25px;
    }
    
    .dashboard-item {
      background-color: white;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
      display: flex;
      flex-direction: column;
      position: relative;
    }
    
    .dashboard-title {
      font-size: 9pt;
      color: #455A64;
      margin-bottom: 10px;
      font-weight: 600;
    }
    
    .dashboard-value {
      font-size: 16pt;
      font-weight: bold;
      color: #1976D2;
      margin-bottom: 5px;
    }
    
    .dashboard-subtitle {
      font-size: 8pt;
      color: #78909C;
    }
    
    .dashboard-indicator {
      position: absolute;
      top: 15px;
      right: 15px;
    }
    
    /* Mejora aspecto general */
    body {
      line-height: 1.6;
    }
  </style>
</head>
<body>
  <!-- Marca de agua (opcional) -->
  <!-- <div class="watermark">HISTORIA CLÍNICA</div> -->
  
  <div class="container">
    <!-- PÁGINA 1: PORTADA -->
    <header class="header">
      <div class="header-logo">
        @if(isset($identity) && $identity && isset($identity->logo_data_uri))
          <img src="{{ $identity->logo_data_uri }}" alt="Logo">
        @endif
      </div>
      <div class="header-info">
        @if(isset($identity) && $identity)
          <h1 class="clinic-name">{{ $identity->name }}</h1>
          @if(isset($identity->specialty) && $identity->specialty)
          <p class="clinic-specialty">{{ $identity->specialty }}</p>
          @endif
          <p class="clinic-contact">
            {{ $identity->address }}
            @if($identity->phone || $identity->email)
              <br>
              @if($identity->phone) Tel: {{ $identity->phone }} @endif
              @if($identity->phone && $identity->email) • @endif
              @if($identity->email) {{ $identity->email }} @endif
            @endif
          </p>
          <div class="history-number">
            <span class="highlight">{{ __("common-view.view.numberHistory") }}:</span> {{ $model->number_history }}
          </div>
        @else
          <h1 class="clinic-name">Centro Médico</h1>
          <div class="history-number">
            <span class="highlight">{{ __("common-view.view.numberHistory") }}:</span> {{ $model->number_history }}
          </div>
        @endif
      </div>
    </header>
    
    <div class="first-page-spacer"></div>
    
    <!-- DASHBOARD CLÍNICO -->
    <div class="clinical-dashboard">
      <div class="dashboard-item">
        <div class="dashboard-title">Edad</div>
        <div class="dashboard-value">{{ $model->patient()->first()->age }}</div>
        <div class="dashboard-subtitle">años</div>
        <div class="dashboard-indicator">
          <div class="score-indicator">
            <div class="score-dots">
              @php
                $ageScore = min(5, ceil($model->patient()->first()->age / 15));
              @endphp
              @for ($i = 1; $i <= 5; $i++)
                <div class="score-dot {{ $i <= $ageScore ? 'score-dot-fill' : 'score-dot-empty' }}"></div>
              @endfor
            </div>
          </div>
        </div>
      </div>
      
      @if(isset($model->getPhyscalExam()['tension']) && !empty($model->getPhyscalExam()['tension']))
      <div class="dashboard-item">
        <div class="dashboard-title">Tensión Arterial</div>
        <div class="dashboard-value">{{ $model->getPhyscalExam()['tension'] }}</div>
        <div class="dashboard-subtitle">mmHg</div>
        @php
          $tensionParts = explode('/', $model->getPhyscalExam()['tension']);
          $systolic = isset($tensionParts[0]) ? (int)$tensionParts[0] : 120;
          $diastolic = isset($tensionParts[1]) ? (int)$tensionParts[1] : 80;
          
          $tensionRisk = 'low';
          if ($systolic >= 140 || $diastolic >= 90) {
            $tensionRisk = 'high';
          } elseif ($systolic >= 130 || $diastolic >= 85) {
            $tensionRisk = 'medium';
          }
        @endphp
        <div class="dashboard-indicator">
          <div class="risk-indicator risk-{{ $tensionRisk }}">
            {{ $tensionRisk == 'low' ? 'Normal' : ($tensionRisk == 'medium' ? 'Elevada' : 'Alta') }}
          </div>
        </div>
      </div>
      @elseif(isset($model->getPhyscalExam()['tad']) && !empty($model->getPhyscalExam()['tad']))
      <div class="dashboard-item">
        <div class="dashboard-title">Tensión Arterial</div>
        <div class="dashboard-value">{{ $model->getPhyscalExam()['tad'] }}</div>
        <div class="dashboard-subtitle">mmHg</div>
        @php
          $tensionParts = explode('/', $model->getPhyscalExam()['tad']);
          $systolic = isset($tensionParts[0]) ? (int)$tensionParts[0] : 120;
          $diastolic = isset($tensionParts[1]) ? (int)$tensionParts[1] : 80;
          
          $tensionRisk = 'low';
          if ($systolic >= 140 || $diastolic >= 90) {
            $tensionRisk = 'high';
          } elseif ($systolic >= 130 || $diastolic >= 85) {
            $tensionRisk = 'medium';
          }
        @endphp
        <div class="dashboard-indicator">
          <div class="risk-indicator risk-{{ $tensionRisk }}">
            {{ $tensionRisk == 'low' ? 'Normal' : ($tensionRisk == 'medium' ? 'Elevada' : 'Alta') }}
          </div>
        </div>
      </div>
      @else
      <div class="dashboard-item">
        <div class="dashboard-title">Fecha Historia</div>
        <div class="dashboard-value">{{ \Carbon\Carbon::parse($model->created_at)->format('d/m/Y') }}</div>
        <div class="dashboard-subtitle">{{ \Carbon\Carbon::parse($model->created_at)->diffForHumans() }}</div>
      </div>
      @endif
      
      @if(isset($model->getPhyscalExam()['peso']) && !empty($model->getPhyscalExam()['peso']))
      <div class="dashboard-item">
        <div class="dashboard-title">Peso</div>
        <div class="dashboard-value">{{ $model->getPhyscalExam()['peso'] }}</div>
        <div class="dashboard-subtitle">Kg</div>
      </div>
      @else
      <div class="dashboard-item">
        <div class="dashboard-title">Num. Controles</div>
        <div class="dashboard-value">{{ count($controls) }}</div>
        <div class="dashboard-subtitle">visitas de seguimiento</div>
      </div>
      @endif
      
      @if(isset($model->getPhyscalExam()['fc']) && !empty($model->getPhyscalExam()['fc']))
      <div class="dashboard-item">
        <div class="dashboard-title">Frecuencia Cardíaca</div>
        <div class="dashboard-value">{{ $model->getPhyscalExam()['fc'] }}</div>
        <div class="dashboard-subtitle">lpm</div>
        @php
          $fcValue = (int)$model->getPhyscalExam()['fc'];
          $fcRisk = 'low';
          if ($fcValue > 100) {
            $fcRisk = 'high';
          } elseif ($fcValue > 90) {
            $fcRisk = 'medium';
          } elseif ($fcValue < 60) {
            $fcRisk = 'medium';
          }
          $fcPercent = min(100, max(0, ($fcValue - 40) * 100 / 140));
        @endphp
        <div class="dashboard-indicator">
          <div class="score-progress" style="width: 80px;">
            <div class="score-progress-fill" style="width: {{ $fcPercent }}%; background-color: {{ $fcRisk == 'low' ? '#4CAF50' : ($fcRisk == 'medium' ? '#FFC107' : '#F44336') }};"></div>
          </div>
        </div>
      </div>
      @else
      <div class="dashboard-item">
        <div class="dashboard-title">Estado</div>
        <div class="dashboard-value">Activo</div>
        <div class="dashboard-subtitle">seguimiento continuo</div>
        <div class="dashboard-indicator">
          <div class="risk-indicator risk-low">
            En tratamiento
          </div>
        </div>
      </div>
      @endif
    </div>
    
    <!-- INFORMACIÓN DEL PACIENTE -->
    <h2 class="main-section-header">Información del Paciente</h2>
    <section class="section patient-info">
      <div class="section-title" style="background: linear-gradient(135deg, #1976D2, #2196F3); text-shadow: 0 1px 2px rgba(0,0,0,0.2);">Información del Paciente</div>
      <table style="border-radius: 0 0 8px 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.08);">
        <tr>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("common-view.view.firstname") }}:
          </td>
          <td class="value" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0; font-weight: bold;">
            <span class="patient-name">{{ $model->patient()->first()->firstname . " " . $model->patient()->first()->lastname }}</span>
          </td>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("common-view.view.gender") }}:
          </td>
          <td class="value" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0;">
            {{ $model->patient()->first()->gender }}
          </td>
        </tr>
        <tr>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("common-view.view.age") }}:
          </td>
          <td class="value" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0;">
            {{ $model->patient()->first()->age }} años
          </td>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("common-view.view.birthday") }}:
          </td>
          <td class="value" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0;">
            {{ (new DateTime($model->patient()->first()->birthday))->format("d/m/Y") }}
          </td>
        </tr>
        <tr>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("detail-history.service") }}:
          </td>
          <td class="value" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0;">
            {{ $especialities[$model->especiality] }}
          </td>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("common-view.view.doctor") }}:
          </td>
          <td class="value" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0; font-weight: bold;">
            <span class="doctor-name">
              @if($model->user()->first()->profile)
                Dr(a). {{ $model->user()->first()->profile->firstname }} {{ $model->user()->first()->profile->lastname }}
              @else
                {{ $model->user()->first()->name }}
              @endif
            </span>
          </td>
        </tr>
        <tr>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("common-view.view.reason") }}:
          </td>
          <td class="value" colspan="3" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0;">
            {{ $model->title }}
          </td>
        </tr>
        @if(isset($model->cie_code) && !empty($model->cie_code))
        <tr>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("Cie") }}:
          </td>
          <td class="value" colspan="3" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0;">
            {{ $model->cie_code }}
          </td>
        </tr>
        @endif
        @if(isset($model->summary) && !empty($model->summary))
        <tr>
          <td class="label" style="font-weight: 600; color: #455A64; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0;">
            {{ __("common-view.view.currentIllnesses") }}:
          </td>
          <td class="value" colspan="3" style="color: #37474F; padding: 12px; border: 1px solid #E3E8F0;">
            {{ $model->summary }}
          </td>
        </tr>
        @endif
        
        <!-- DIAGNÓSTICO INTEGRADO -->
        @if(isset($model->diagnosis) && !empty($model->diagnosis))
        <tr>
          <td colspan="4" style="padding: 0; border: none;">
            <table style="width: 100%; border-collapse: collapse; margin: 0;">
              <tr>
                <td style="background-color: #1976D2; color: white; font-weight: bold; padding: 12px; border: 1px solid #1976D2; text-transform: uppercase; letter-spacing: 0.5px; text-shadow: 0 1px 2px rgba(0,0,0,0.2);">
                  Diagnóstico Médico
                  @php
                    $diagnosisLen = strlen($model->diagnosis);
                    $severityScore = 0;
                    
                    // Palabras clave que podrían indicar gravedad
                    $keywordsSevere = ['grave', 'severo', 'urgente', 'crítico', 'emergencia', 'inmediato', 'agudo'];
                    $keywordsMedium = ['moderado', 'significativo', 'notable', 'importante', 'considerable'];
                    
                    foreach ($keywordsSevere as $keyword) {
                      if (stripos($model->diagnosis, $keyword) !== false) {
                        $severityScore = 3;
                        break;
                      }
                    }
                    
                    if ($severityScore == 0) {
                      foreach ($keywordsMedium as $keyword) {
                        if (stripos($model->diagnosis, $keyword) !== false) {
                          $severityScore = 2;
                          break;
                        }
                      }
                    }
                    
                    if ($severityScore == 0) {
                      $severityScore = 1;
                    }
                  @endphp
                  <span class="risk-indicator {{ $severityScore == 3 ? 'risk-high' : ($severityScore == 2 ? 'risk-medium' : 'risk-low') }}" style="float: right; margin-top: -2px;">
                    {{ $severityScore == 3 ? 'Atención prioritaria' : ($severityScore == 2 ? 'Seguimiento regular' : 'Evaluación médica') }}
                  </span>
                </td>
              </tr>
              <tr>
                <td style="background-color: #EBF5FE; padding: 16px; border: 1px solid #BBDEFB; border-top: none; font-weight: 500; color: #37474F; line-height: 1.6;">
                  {{ $model->diagnosis }}
                </td>
              </tr>
            </table>
          </td>
        </tr>
        @endif
      </table>
    </section>
    
    <div class="first-page-spacer"></div>
    
    
    <!-- TABLA DE CONTENIDO -->
    <div class="section-spacer"></div>
    <div class="toc" style="background-color: #F5FAFF; border: 1px solid #BBDEFB; box-shadow: 0 2px 10px rgba(25, 118, 210, 0.1);">
      <div class="toc-title" style="background: linear-gradient(135deg, #1976D2, #2196F3); -webkit-background-clip: text; -webkit-text-fill-color: transparent; border-bottom: 2px solid #1976D2; font-weight: bold;">Índice de Contenido</div>
      
      <table class="toc-table" cellspacing="0" cellpadding="0" style="width: 100%; border-collapse: collapse; box-shadow: none; border: none;">
        <!-- Sección: Información general -->
        <tr class="toc-main-section">
          <td style="padding: 8px 0; font-weight: bold; color: #1976D2; font-size: 11pt; border: none;">1. Información General del Paciente</td>
          <td style="text-align: right; padding: 8px 0; font-weight: bold; color: #1976D2; font-size: 11pt; border: none;">1</td>
        </tr>
        
        <tr>
          <td style="padding: 5px 0 5px 20px; color: #455A64; border: none;">Datos Personales</td>
          <td style="text-align: right; padding: 5px 0; color: #455A64; border: none;">1</td>
        </tr>
        
        <!-- Diagnóstico -->
        @if(isset($model->diagnosis) && !empty($model->diagnosis))
        <tr>
          <td style="padding: 5px 0 5px 20px; color: #455A64; border: none;">Diagnóstico Médico</td>
          <td style="text-align: right; padding: 5px 0; color: #455A64; border: none;">1</td>
        </tr>
        @endif
        
        <!-- Sección: Antecedentes -->
        @if(count($model->getSectionHistory()) > 0)
        <tr class="toc-main-section">
          <td style="padding: 5px 0;">2. Antecedentes Médicos</td>
          <td style="text-align: right; padding: 5px 0;">2</td>
        </tr>
        
        @foreach($model->getSectionHistory() as $index => $sectionHistory)
        <tr>
          <td style="padding: 3px 0 3px 20px;">{{ $sectionHistory->title }}</td>
          <td style="text-align: right; padding: 3px 0;">2</td>
        </tr>
        @endforeach
        @endif
        
        <!-- Sección: Examen Físico -->
        @if(count($model->getPhyscalExam()) > 0)
        <tr class="toc-main-section">
          <td style="padding: 5px 0;">3. Examen Físico</td>
          <td style="text-align: right; padding: 5px 0;">3</td>
        </tr>
        
        @foreach($model->getPhyscalExam() as $key => $value)
        <tr>
          <td style="padding: 3px 0 3px 20px;">{{ __("com-form-history." . $key) }}</td>
          <td style="text-align: right; padding: 3px 0;">3</td>
        </tr>
        @endforeach
        @endif
        
        <!-- Sección: Controles -->
        @if(count($controls) > 0)
        <tr class="toc-main-section">
          <td style="padding: 5px 0;">4. Controles Médicos</td>
          <td style="text-align: right; padding: 5px 0;">4</td>
        </tr>
        
        @foreach($controls as $index => $control)
        <tr>
          <td style="padding: 3px 0 3px 20px;">
            {{ \Carbon\Carbon::parse($control->created_at)->format('d/m/Y') }} - 
            @if($control->user()->first()->profile)
              {{ $control->user()->first()->profile->firstname }} {{ $control->user()->first()->profile->lastname }}
            @else
              {{ $control->user()->first()->name }}
            @endif
          </td>
          <td style="text-align: right; padding: 3px 0;">4</td>
        </tr>
        @endforeach
        @endif
      </table>
    </div>

    <div class="first-page-spacer"></div>
    
    <!-- FIRMA DEL MÉDICO -->
    <div class="professional-signature">
      <div class="signature-line"></div>
      <p class="signature-name">
        @if($model->user()->first()->profile)
          Dr(a). {{ $model->user()->first()->profile->firstname }} {{ $model->user()->first()->profile->lastname }}
        @else
          {{ $model->user()->first()->name }}
        @endif
      </p>
      <p class="signature-title">Médico Tratante</p>
      <p class="medical-license">Registro Profesional: 
        @if($model->user()->first()->profile && !empty($model->user()->first()->profile->identification))
          {{ $model->user()->first()->profile->identification }}
        @else
          -------------
        @endif
      </p>
    </div>

    <!-- PIE DE PÁGINA PRIMERA HOJA -->
    <div class="footer-spacer"></div>
    <footer class="footer">
      @if(isset($identity) && $identity)
        <strong>{{ $identity->name }}</strong> • {{ $identity->address }}
        @if($identity->phone || $identity->email)
          • 
          @if($identity->phone) Tel: {{ $identity->phone }} @endif
          @if($identity->phone && $identity->email) • @endif
          @if($identity->email) {{ $identity->email }} @endif
        @endif
      @else
        <strong>Centro Médico</strong>
      @endif
      • <span style="color:#3498db;">Fecha:</span> {{ \Carbon\Carbon::now()->format('d/m/Y H:i') }}
      • <span style="color:#3498db;">Página 1</span>
    </footer>

    <!-- PÁGINA 2: ANTECEDENTES -->
    @if(count($model->getSectionHistory()) > 0)
    <div class="page-break"></div>
    
    <div class="mini-header">
      <strong>{{ $model->patient()->first()->firstname . " " . $model->patient()->first()->lastname }}</strong> - 
      {{ __("common-view.view.numberHistory") }}: {{ $model->number_history }}
    </div>
    
    <h2 class="main-section-header">Antecedentes Médicos</h2>
    <section class="section">
      <div class="section-title">Antecedentes Médicos</div>
      
      @foreach($model->getSectionHistory() as $sectionHistory)
      <div class="subsection">
        <h3 class="subsection-title">{{ $sectionHistory->title }}</h3>
        <div class="antecedent-item">{{ $sectionHistory->summary }}</div>
      </div>
      @endforeach
    </section>
    
    <!-- PIE DE PÁGINA DE ANTECEDENTES -->
    <div class="footer-spacer"></div>
    <footer class="footer">
      @if(isset($identity) && $identity)
        <strong>{{ $identity->name }}</strong> • {{ $identity->address }}
        @if($identity->phone || $identity->email)
          • 
          @if($identity->phone) Tel: {{ $identity->phone }} @endif
          @if($identity->phone && $identity->email) • @endif
          @if($identity->email) {{ $identity->email }} @endif
        @endif
      @else
        <strong>Centro Médico</strong>
      @endif
      • <span style="color:#3498db;">Fecha:</span> {{ \Carbon\Carbon::now()->format('d/m/Y H:i') }}
      • <span style="color:#3498db;">Página 2</span>
    </footer>
    @endif
    
    <!-- PÁGINA 3: EXAMEN FÍSICO -->
    @if(count($model->getPhyscalExam()) > 0)
    <div class="page-break"></div>
    
    <div class="mini-header">
      <strong>{{ $model->patient()->first()->firstname . " " . $model->patient()->first()->lastname }}</strong> - 
      {{ __("common-view.view.numberHistory") }}: {{ $model->number_history }}
    </div>
    
    <h2 class="main-section-header">Examen Físico</h2>
    <section class="section">
      <div class="section-title">Examen Físico</div>
      
      @foreach($model->getPhyscalExam() as $key => $value)
      <div class="subsection">
        <h3 class="subsection-title">{{ __("com-form-history." . $key) }}</h3>
        <div class="physical-exam-item">{{ $value }}</div>
      </div>
      @endforeach
    </section>
    
    <!-- PIE DE PÁGINA DE EXAMEN FÍSICO -->
    <div class="footer-spacer"></div>
    <footer class="footer">
      @if(isset($identity) && $identity)
        <strong>{{ $identity->name }}</strong> • {{ $identity->address }}
        @if($identity->phone || $identity->email)
          • 
          @if($identity->phone) Tel: {{ $identity->phone }} @endif
          @if($identity->phone && $identity->email) • @endif
          @if($identity->email) {{ $identity->email }} @endif
        @endif
      @else
        <strong>Centro Médico</strong>
      @endif
      • <span style="color:#3498db;">Fecha:</span> {{ \Carbon\Carbon::now()->format('d/m/Y H:i') }}
      • <span style="color:#3498db;">Página 3</span>
    </footer>
    @endif
    
    <!-- PÁGINA 4: CONTROLES -->
    @if(count($controls) > 0)
    @if(count($model->getPhyscalExam()) > 0 || count($model->getSectionHistory()) > 0)
    <div class="page-break"></div>
    @endif

    <div class="mini-header">
      <strong>{{ $model->patient()->first()->firstname . " " . $model->patient()->first()->lastname }}</strong> - 
      {{ __("common-view.view.numberHistory") }}: {{ $model->number_history }}
    </div>

    <div style="page-break-inside: avoid; display: block;">
      <!-- Título único para la sección de controles -->
      <h2 class="main-section-header" style="background: linear-gradient(135deg, #1976D2, #2196F3); margin-bottom: 30px; box-shadow: 0 4px 12px rgba(25, 118, 210, 0.15); text-shadow: 0 1px 2px rgba(0,0,0,0.2);">Controles Médicos</h2>
      
      @foreach($controls as $control)
      <div class="control" style="margin-bottom: 30px; page-break-inside: avoid !important; break-inside: avoid !important; border: 1px solid #E3E8F0; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.08);">
        <!-- Encabezado del control -->
        <div class="section-title" style="margin-bottom: 0; border-radius: 8px 8px 0 0; background: linear-gradient(135deg, #1976D2, #2196F3); text-shadow: 0 1px 2px rgba(0,0,0,0.2); font-weight: 600; letter-spacing: 0.5px;">
          {{ \Carbon\Carbon::parse($control->created_at)->format('d/m/Y') }} - 
          @if($control->user()->first()->profile)
            {{ $control->user()->first()->profile->firstname }} {{ $control->user()->first()->profile->lastname }}
          @else
            {{ $control->user()->first()->name }}
          @endif
        </div>

        <!-- Tabla para el contenido del control -->
        <table style="width: 100%; border-collapse: collapse; page-break-inside: avoid !important; margin-bottom: 0; box-shadow: none; border: none;">
          <!-- Fecha del control -->
          <tr>
            <td class="label" style="font-weight: 600; color: #455A64; width: 30%; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-left: none;">
              Fecha del Control:
            </td>
            <td class="value" style="width: 70%; color: #37474F; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-right: none;">
              {{ \Carbon\Carbon::parse($control->created_at)->format('d/m/Y H:i') }}
            </td>
          </tr>
          
          <!-- Médico del control -->
          <tr>
            <td class="label" style="font-weight: 600; color: #455A64; width: 30%; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-left: none;">
              Médico Tratante:
            </td>
            <td class="value" style="width: 70%; color: #37474F; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-right: none;">
              @if($control->user()->first()->profile)
                Dr(a). {{ $control->user()->first()->profile->firstname }} {{ $control->user()->first()->profile->lastname }}
              @else
                {{ $control->user()->first()->name }}
              @endif
            </td>
          </tr>
          
          <!-- Motivo de consulta si existe -->
          @if(isset($control->title) && !empty($control->title))
          <tr>
            <td class="label" style="font-weight: 600; color: #455A64; width: 30%; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-left: none;">
              {{ __("common-view.view.reason") }}:
            </td>
            <td class="value" style="width: 70%; color: #37474F; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-right: none;">
              {{ $control->title }}
            </td>
          </tr>
          @endif

          <!-- Enfermedad actual si existe -->
          @if(isset($control->summary) && !empty($control->summary))
          <tr>
            <td class="label" style="font-weight: 600; color: #455A64; width: 30%; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-left: none;">
              {{ __("common-view.view.currentIllnesses") }}:
            </td>
            <td class="value" style="width: 70%; color: #37474F; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-right: none;">
              {{ $control->summary }}
            </td>
          </tr>
          @endif

          <!-- Diagnóstico si existe -->
          @if(isset($control->diagnosis) && !empty($control->diagnosis))
          <tr>
            <td colspan="2" style="background-color: #FBE9E7; border: 1px solid #BBDEFB; padding: 0;">
              <table style="width: 100%; border-collapse: collapse; margin: 0; border: none;">
                <tr>
                  <td style="background-color: #FBE9E7; color: #D32F2F; font-weight: bold; width: 30%; padding: 12px; border: none; border-right: 1px solid #FFCCBC;">
                    Diagnóstico:
                  </td>
                  <td style="width: 70%; padding: 12px; background-color: #EBF5FE; border: none; font-weight: bold;">
                    {{ $control->diagnosis }}
                  </td>
                </tr>
              </table>
              <div style="padding: 0 12px 12px 12px; background-color: #EBF5FE;">
                <div class="score-indicator">
                  <div class="score-label">Nivel de atención:</div>
                  <div class="score-dots" style="margin-left: 5px;">
                    @php
                      // Palabras clave que podrían indicar gravedad
                      $keywordsSevere = ['grave', 'severo', 'urgente', 'crítico', 'emergencia', 'inmediato', 'agudo'];
                      $keywordsMedium = ['moderado', 'significativo', 'notable', 'importante', 'considerable'];
                      $severityScore = 0;
                      
                      foreach ($keywordsSevere as $keyword) {
                        if (stripos($control->diagnosis, $keyword) !== false) {
                          $severityScore = 3;
                          break;
                        }
                      }
                      
                      if ($severityScore == 0) {
                        foreach ($keywordsMedium as $keyword) {
                          if (stripos($control->diagnosis, $keyword) !== false) {
                            $severityScore = 2;
                            break;
                          }
                        }
                      }
                      
                      if ($severityScore == 0) {
                        $severityScore = 1;
                      }
                    @endphp
                    @for ($i = 1; $i <= 3; $i++)
                      <div class="score-dot {{ $i <= $severityScore ? ($i == 3 ? 'score-dot-danger' : ($i == 2 ? 'score-dot-warning' : 'score-dot-fill')) : 'score-dot-empty' }}"></div>
                    @endfor
                  </div>
                  <div class="score-label" style="margin-left: 5px;">
                    {{ $severityScore == 3 ? 'Prioritario' : ($severityScore == 2 ? 'Seguimiento' : 'Evaluaci�n') }}
                  </div>
                </div>
              </div>
            </td>
          </tr>
          @endif

          <!-- Descripción del control -->
          <tr>
            <td class="label" style="font-weight: 600; color: #34495e; width: 30%; background-color: #f5f7f8; padding: 10px; border: 1px solid #e1e8ed;">
              Descripción del Control:
            </td>
            <td class="value" style="width: 70%; color: #2c3e50; padding: 10px; border: 1px solid #e1e8ed;">
              {{ $control->description }}
            </td>
          </tr>

          <!-- Exámenes físicos si existen -->
          @if(count($control->getControlPhyscalExam()) > 0)
            @foreach($control->getControlPhyscalExam() as $key => $value)
            <tr>
              <td class="label" style="font-weight: 600; color: #455A64; width: 30%; background-color: #F5F7FA; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-left: none;">
                {{ __("com-form-history." . $key) }}:
              </td>
              <td class="value" style="width: 70%; color: #37474F; padding: 12px; border: 1px solid #E3E8F0; border-top: none; border-right: none;">
                {{ $value }}
                
                @php
                  // Añadir indicadores visuales para ciertos valores comunes
                  $showIndicator = false;
                  $percentValue = 0;
                  $indicatorColor = '#4CAF50';
                  $indicatorLabel = '';
                  
                  // Detectar tipo de valor
                  if ($key == 'peso' || $key == 'peso_kg') {
                    $numValue = (float) preg_replace('/[^\d.]/', '', $value);
                    if ($numValue > 0) {
                      $showIndicator = true;
                      $percentValue = min(100, max(0, ($numValue - 40) * 100 / 100));
                      if ($numValue < 50) {
                        $indicatorColor = '#FFC107';
                        $indicatorLabel = 'Bajo peso';
                      } elseif ($numValue > 90) {
                        $indicatorColor = '#F44336';
                        $indicatorLabel = 'Sobrepeso';
                      } else {
                        $indicatorLabel = 'Normal';
                      }
                    }
                  } elseif ($key == 'fc' || $key == 'fr_cardiaca' || $key == 'frecuencia_cardiaca') {
                    $numValue = (int) preg_replace('/[^\d]/', '', $value);
                    if ($numValue > 0) {
                      $showIndicator = true;
                      $percentValue = min(100, max(0, ($numValue - 40) * 100 / 120));
                      if ($numValue < 60) {
                        $indicatorColor = '#FFC107';
                        $indicatorLabel = 'Bradicardia';
                      } elseif ($numValue > 100) {
                        $indicatorColor = '#F44336';
                        $indicatorLabel = 'Taquicardia';
                      } else {
                        $indicatorLabel = 'Normal';
                      }
                    }
                  } elseif ($key == 'tension' || $key == 'tension_arterial' || $key == 'ta' || $key == 'tad') {
                    $showIndicator = true;
                    $tensionParts = explode('/', $value);
                    $systolic = isset($tensionParts[0]) ? (int)preg_replace('/[^\d]/', '', $tensionParts[0]) : 120;
                    $diastolic = isset($tensionParts[1]) ? (int)preg_replace('/[^\d]/', '', $tensionParts[1]) : 80;
                    
                    $percentValue = min(100, max(0, ($systolic - 90) * 100 / 80));
                    if ($systolic >= 140 || $diastolic >= 90) {
                      $indicatorColor = '#F44336';
                      $indicatorLabel = 'Hipertensión';
                    } elseif ($systolic >= 130 || $diastolic >= 85) {
                      $indicatorColor = '#FFC107';
                      $indicatorLabel = 'Pre-hipertensión';
                    } elseif ($systolic < 100 || $diastolic < 60) {
                      $indicatorColor = '#FFC107';
                      $indicatorLabel = 'Hipotensión';
                    } else {
                      $indicatorLabel = 'Normal';
                    }
                  } elseif ($key == 'temp' || $key == 'temperatura') {
                    $numValue = (float) preg_replace('/[^\d.]/', '', $value);
                    if ($numValue > 0) {
                      $showIndicator = true;
                      $percentValue = min(100, max(0, ($numValue - 35) * 100 / 5));
                      if ($numValue >= 38) {
                        $indicatorColor = '#F44336';
                        $indicatorLabel = 'Fiebre';
                      } elseif ($numValue >= 37.2) {
                        $indicatorColor = '#FFC107';
                        $indicatorLabel = 'Febrícula';
                      } elseif ($numValue < 36) {
                        $indicatorColor = '#FFC107';
                        $indicatorLabel = 'Hipotermia';
                      } else {
                        $indicatorLabel = 'Normal';
                      }
                    }
                  }
                @endphp
                
                @if($showIndicator)
                <div style="margin-top: 5px;">
                  <div class="score-indicator">
                    <div class="score-progress" style="width: 80px; height: 6px;">
                      <div class="score-progress-fill" style="width: {{ $percentValue }}%; background-color: {{ $indicatorColor }};"></div>
                    </div>
                    <div class="score-label" style="margin-left: 5px; font-size: 7pt;">{{ $indicatorLabel }}</div>
                  </div>
                </div>
                @endif
              </td>
            </tr>
            @endforeach
          @endif
        </table>
      </div>
      @endforeach
    </div>

    <!-- PIE DE PÁGINA DE CONTROLES -->
    <div class="footer-spacer"></div>
    <footer class="footer">
      @if(isset($identity) && $identity)
        <strong>{{ $identity->name }}</strong> • {{ $identity->address }}
        @if($identity->phone || $identity->email)
          • 
          @if($identity->phone) Tel: {{ $identity->phone }} @endif
          @if($identity->phone && $identity->email) • @endif
          @if($identity->email) {{ $identity->email }} @endif
        @endif
      @else
        <strong>Centro Médico</strong>
      @endif
      • <span style="color:#3498db;">Fecha:</span> {{ \Carbon\Carbon::now()->format('d/m/Y H:i') }}
      • <span style="color:#3498db;">Página 4</span>
    </footer>
    @endif
    
    <!-- MENSAJE DE SEGURIDAD -->
    <div class="secure-doc">
      Documento médico confidencial. Este documento contiene información médica protegida.
      Generado el {{ \Carbon\Carbon::now()->format('d/m/Y') }} a las {{ \Carbon\Carbon::now()->format('H:i:s') }}.
    </div>
    
    <!-- RESUMEN DE PROGRESIÓN DEL PACIENTE -->
    @if(count($controls) > 1)
    <div class="page-break"></div>
    
    <div class="mini-header">
      <strong>{{ $model->patient()->first()->firstname . " " . $model->patient()->first()->lastname }}</strong> - 
      {{ __("common-view.view.numberHistory") }}: {{ $model->number_history }}
    </div>
    
    <h2 class="main-section-header" style="background: linear-gradient(135deg, #1976D2, #2196F3); margin-bottom: 30px; box-shadow: 0 4px 12px rgba(25, 118, 210, 0.15); text-shadow: 0 1px 2px rgba(0,0,0,0.2);">
      Progresión del Paciente
    </h2>
    
    <div style="text-align: center; margin-bottom: 20px; color: #455A64; font-size: 11pt;">
      Evolución de los principales parámetros a lo largo del tiempo
    </div>
    
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px;">
      <div style="text-align: left; font-weight: bold; color: #1976D2;">
        Primera consulta: {{ \Carbon\Carbon::parse($model->created_at)->format('d/m/Y') }}
      </div>
      <div style="text-align: right; font-weight: bold; color: #1976D2;">
        Última consulta: {{ count($controls) > 0 ? \Carbon\Carbon::parse($controls[count($controls) - 1]->created_at)->format('d/m/Y') : 'N/A' }}
      </div>
    </div>
    
    <style>
      .progress-chart {
        position: relative;
        padding: 20px 40px;
        margin-bottom: 30px;
        background-color: white;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      }
      
      .progress-chart-title {
        font-size: 14pt;
        color: #455A64;
        font-weight: bold;
        margin-bottom: 15px;
        text-align: center;
      }
      
      .progress-chart-subtitle {
        font-size: 10pt;
        color: #78909C;
        text-align: center;
        margin-bottom: 20px;
      }
      
      .timeline {
        display: flex;
        height: 80px;
        position: relative;
        margin: 30px 0;
      }
      
      .timeline:before {
        content: "";
        position: absolute;
        top: 40px;
        left: 0;
        right: 0;
        height: 2px;
        background-color: #E0E0E0;
        z-index: 1;
      }
      
      .timeline-point {
        flex: 1;
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        z-index: 2;
      }
      
      .timeline-dot {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: white;
        border: 2px solid #1976D2;
        margin-bottom: 10px;
        margin-top: 30px;
        z-index: 2;
      }
      
      .timeline-label {
        font-size: 8pt;
        color: #455A64;
        text-align: center;
        margin-top: 5px;
        max-width: 80px;
      }
      
      .timeline-value {
        font-size: 10pt;
        font-weight: bold;
        color: #1976D2;
        position: absolute;
        top: 10px;
      }
      
      .value-trend {
        position: absolute;
        top: 40px;
        left: 0;
        right: 0;
        z-index: 1;
        overflow: hidden;
      }
      
      .trend-line {
        height: 2px;
        background: linear-gradient(to right, #1976D2, #2196F3);
        position: relative;
      }
      
      .evaluation-summary {
        background-color: #F5F7FA;
        border-radius: 8px;
        padding: 20px;
        margin-top: 30px;
        border-left: 4px solid #1976D2;
      }
      
      .evaluation-title {
        font-size: 12pt;
        font-weight: bold;
        color: #1976D2;
        margin-bottom: 10px;
      }
      
      .evaluation-text {
        color: #455A64;
        line-height: 1.6;
      }
    </style>
    
    <div class="progress-chart">
      <h3 class="progress-chart-title">Evolución de Signos Vitales</h3>
      <p class="progress-chart-subtitle">Seguimiento de {{ count($controls) }} controles médicos</p>
      
      <!-- Peso -->
      @php
        $hasWeight = false;
        $weightData = [];
        
        // Verificar si hay datos de peso en los controles
        foreach($controls as $controlIndex => $control) {
          foreach($control->getControlPhyscalExam() as $key => $value) {
            if ($key == 'peso' || $key == 'peso_kg') {
              $numValue = (float) preg_replace('/[^\d.]/', '', $value);
              if ($numValue > 0) {
                $hasWeight = true;
                $weightData[] = [
                  'date' => \Carbon\Carbon::parse($control->created_at)->format('d/m/Y'),
                  'value' => $numValue
                ];
              }
            }
          }
        }
      @endphp
      
      @if($hasWeight && count($weightData) > 1)
      <div style="margin-bottom: 30px;">
        <div style="font-weight: bold; color: #455A64; margin-bottom: 10px;">Peso (Kg)</div>
        <div class="timeline">
          @foreach($weightData as $index => $data)
            <div class="timeline-point">
              <div class="timeline-value">{{ $data['value'] }}</div>
              <div class="timeline-dot" style="background-color: {{ $index == 0 ? '#E1F5FE' : ($index == count($weightData) - 1 ? '#E8F5E9' : 'white') }};"></div>
              <div class="timeline-label">{{ $data['date'] }}</div>
            </div>
          @endforeach
        </div>
      </div>
      @endif
      
      <!-- Tensión Arterial -->
      @php
        $hasTension = false;
        $tensionData = [];
        
        // Verificar si hay datos de tensión en los controles
        foreach($controls as $controlIndex => $control) {
          foreach($control->getControlPhyscalExam() as $key => $value) {
            if ($key == 'tension' || $key == 'tension_arterial' || $key == 'ta' || $key == 'tad') {
              $tensionParts = explode('/', $value);
              if (count($tensionParts) >= 2) {
                $systolic = isset($tensionParts[0]) ? (int)preg_replace('/[^\d]/', '', $tensionParts[0]) : 0;
                $diastolic = isset($tensionParts[1]) ? (int)preg_replace('/[^\d]/', '', $tensionParts[1]) : 0;
                
                if ($systolic > 0 && $diastolic > 0) {
                  $hasTension = true;
                  $tensionData[] = [
                    'date' => \Carbon\Carbon::parse($control->created_at)->format('d/m/Y'),
                    'systolic' => $systolic,
                    'diastolic' => $diastolic,
                    'value' => $value
                  ];
                }
              }
            }
          }
        }
      @endphp
      
      @if($hasTension && count($tensionData) > 1)
      <div style="margin-bottom: 30px;">
        <div style="font-weight: bold; color: #455A64; margin-bottom: 10px;">Tensión Arterial (mmHg)</div>
        <div class="timeline">
          @foreach($tensionData as $index => $data)
            <div class="timeline-point">
              <div class="timeline-value">{{ $data['value'] }}</div>
              <div class="timeline-dot" style="background-color: {{ $data['systolic'] >= 140 || $data['diastolic'] >= 90 ? '#FFEBEE' : ($data['systolic'] >= 130 || $data['diastolic'] >= 85 ? '#FFF8E1' : '#E8F5E9') }};"></div>
              <div class="timeline-label">{{ $data['date'] }}</div>
            </div>
          @endforeach
        </div>
      </div>
      @endif
      
      <div class="evaluation-summary">
        <div class="evaluation-title">Resumen de la Evolución</div>
        <div class="evaluation-text">
          El paciente ha asistido a {{ count($controls) }} controles médicos desde la apertura de su historia. 
          @if($hasWeight && count($weightData) > 1)
            @php
              $firstWeight = $weightData[0]['value'];
              $lastWeight = $weightData[count($weightData) - 1]['value'];
              $weightDiff = $lastWeight - $firstWeight;
              $weightTrend = $weightDiff > 0 ? 'aumentado' : ($weightDiff < 0 ? 'disminuido' : 'mantenido');
              $absWeightDiff = abs($weightDiff);
            @endphp
            El peso ha {{ $weightTrend }} {{ number_format($absWeightDiff, 1) }} Kg durante el período de observación.
          @endif
          
          @if($hasTension && count($tensionData) > 1)
            @php
              $firstSystolic = $tensionData[0]['systolic'];
              $firstDiastolic = $tensionData[0]['diastolic'];
              $lastSystolic = $tensionData[count($tensionData) - 1]['systolic'];
              $lastDiastolic = $tensionData[count($tensionData) - 1]['diastolic'];
              
              $systolicDiff = $lastSystolic - $firstSystolic;
              $diastolicDiff = $lastDiastolic - $firstDiastolic;
              
              $tensionTrend = '';
              if ($systolicDiff > 5 || $diastolicDiff > 5) {
                $tensionTrend = 'aumentado';
              } elseif ($systolicDiff < -5 || $diastolicDiff < -5) {
                $tensionTrend = 'disminuido';
              } else {
                $tensionTrend = 'mantenido estable';
              }
            @endphp
            La tensión arterial ha {{ $tensionTrend }} durante el tratamiento.
          @endif
          
          El seguimiento continuo es fundamental para evaluar la respuesta al tratamiento y realizar ajustes necesarios.
        </div>
      </div>
    </div>
    
    <div class="footer-spacer"></div>
    <footer class="footer">
      @if(isset($identity) && $identity)
        <strong>{{ $identity->name }}</strong> • {{ $identity->address }}
        @if($identity->phone || $identity->email)
          • 
          @if($identity->phone) Tel: {{ $identity->phone }} @endif
          @if($identity->phone && $identity->email) • @endif
          @if($identity->email) {{ $identity->email }} @endif
        @endif
      @else
        <strong>Centro Médico</strong>
      @endif
      • <span style="color:#3498db;">Fecha:</span> {{ \Carbon\Carbon::now()->format('d/m/Y H:i') }}
      • <span style="color:#3498db;">Página 5</span>
    </footer>
    @endif
  </div>
</body>
</html>
