<?php
/**
 * VALORACIÓN GERIÁTRICA INTEGRAL (MSP 057A 2021) - VERSIÓN PREMIUM DEFINITIVA
 * Arquitectura de alta fidelidad con cálculos en tiempo real.
 */
?>
<style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
    
    .premium-form-container { font-family: 'Inter', sans-serif; color: #1e293b; background-color: #f8fafc; padding: 15px; border-radius: 8px; }
    .premium-panel { background: #ffffff; border-radius: 10px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); margin-bottom: 25px; border: 1px solid #e2e8f0; overflow: hidden; }
    .premium-header { color: white; padding: 12px 20px; font-weight: 600; font-size: 15px; display: flex; align-items: center; }
    .premium-header.blue { background: linear-gradient(135deg, #0ea5e9 0%, #0369a1 100%); }
    .premium-header.green { background: linear-gradient(135deg, #10b981 0%, #047857 100%); }
    .premium-header.purple { background: linear-gradient(135deg, #8b5cf6 0%, #5b21b6 100%); }
    .premium-header.orange { background: linear-gradient(135deg, #f59e0b 0%, #b45309 100%); }
    .premium-header.teal { background: linear-gradient(135deg, #14b8a6 0%, #0f766e 100%); }
    .premium-header.rose { background: linear-gradient(135deg, #f43f5e 0%, #be123c 100%); }
    .premium-header.slate { background: linear-gradient(135deg, #475569 0%, #1e293b 100%); }
    .premium-header i { margin-right: 10px; font-size: 18px; }
    
    .premium-body { padding: 20px; }
    .premium-label { font-weight: 600; color: #475569; font-size: 12px; margin-bottom: 6px; display: block; text-transform: uppercase; }
    .premium-select, .premium-input { border-radius: 6px; border: 1px solid #cbd5e1; padding: 8px 12px; width: 100%; transition: all 0.2s; background-color: #f1f5f9; color: #1e293b; font-size: 13px; }
    .premium-select:focus, .premium-input:focus { border-color: #0ea5e9; box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.15); background-color: #ffffff; outline: none; }
    
    .item-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border-bottom: 1px solid #f1f5f9; background: #fff; border-radius: 4px; }
    .item-row:hover { background: #f8fafc; }
    .item-label { flex: 1; font-size: 13px; color: #334155; font-weight: 500; }
    .item-control { width: 180px; }
    .item-control-sm { width: 100px; }
    
    .score-box { background-color: #f8fafc; border: 2px dashed #cbd5e1; padding: 15px; border-radius: 8px; text-align: center; margin-top: 15px; }
    .score-value { font-size: 24px; font-weight: 700; color: #0f172a; margin-bottom: 5px; }
    .score-desc { font-weight: 600; font-size: 14px; padding: 6px 12px; border-radius: 4px; display: inline-block; }
    
    /* Semantic Colors */
    .bg-green { background-color: #dcfce7; color: #166534; }
    .bg-yellow { background-color: #fef9c3; color: #854d0e; }
    .bg-red { background-color: #fee2e2; color: #991b1b; }
    .bg-gray { background-color: #e2e8f0; color: #475569; }
</style>

<div class="premium-form-container">
    <form id="formulariop" name="formulariop" method="POST">
        <input type="hidden" name="idatencion" id="idatencionp" value="<?php echo $_POST['idatencion'] ?? ($idatencion ?? ''); ?>">
        <input type="hidden" name="tipo_formato" value="GERIATRIA">

        <!-- DATOS DEL PACIENTE -->
        <div class="premium-panel">
            <div class="premium-header slate">
                <i class="fa fa-user-circle"></i> DATOS DEL PACIENTE - FORMULARIO 057A
            </div>
            <div class="premium-body" style="padding: 15px 25px; background: #fff;">
                <?php include __DIR__ . '/partials/patient_header.php'; ?>
            </div>
        </div>

        <div class="row">
            <!-- 1. TAMIZAJE RÁPIDO -->
            <div class="col-md-6">
                <div class="premium-panel">
                    <div class="premium-header blue">
                        <i class="fa fa-search"></i> 1. TAMIZAJE RÁPIDO
                    </div>
                    <div class="premium-body">
                        <?php 
                        $tamizaje = [
                            'tam_visual' => 'Dificultad visual', 'tam_auditiva' => 'Dificultad auditiva',
                            'tam_anda' => 'Prueba de levántate y anda > 15 seg', 'tam_orina' => 'Pérdida involuntaria de orina',
                            'tam_peso' => 'Pérdida de peso > 4.5Kg en 6 meses', 'tam_memoria' => 'Pérdida de memoria reciente',
                            'tam_triste' => 'Se siente triste o deprimido', 'tam_bano' => 'Puede bañarse solo',
                            'tam_compras' => 'Sale de compras solo', 'tam_vive' => 'Vive solo'
                        ];
                        foreach($tamizaje as $key => $label): ?>
                            <div class="item-row">
                                <div class="item-label"><?php echo $label; ?></div>
                                <div class="item-control-sm">
                                    <select name="<?php echo $key; ?>" class="premium-select calc-tam">
                                        <option value="">--</option>
                                        <option value="1">SÍ (1)</option>
                                        <option value="0">NO (0)</option>
                                    </select>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <div class="score-box">
                            <div class="premium-label">TOTAL TAMIZAJE:</div>
                            <input type="text" id="tam_total" name="tam_total" class="premium-input text-center score-value bg-gray" readonly placeholder="0">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 2. ACTIVIDAD INSTRUMENTAL -->
            <div class="col-md-6">
                <div class="premium-panel">
                    <div class="premium-header green">
                        <i class="fa fa-tasks"></i> 2. ACTIVIDAD INSTRUMENTAL (LAWTON)
                    </div>
                    <div class="premium-body">
                        <?php 
                        $inst = [
                            'inst_casa' => ['Cuida la casa', [1=>'Cuida sin ayuda', 2=>'Lo hace sin ayuda', 3=>'Tareas ligeras', 4=>'Necesita ayuda para todo']],
                            'inst_telefono' => ['Uso del Teléfono', [1=>'Usa sin problemas', 2=>'Todo menos trabajo pesado', 3=>'Contesta pero no llama', 4=>'Incapaz de utilizarlo']],
                            'inst_trans' => ['Usa Transporte', [1=>'Viaja solo/conduce', 2=>'Solo lugares familiares', 3=>'Necesita acompañamiento', 4=>'Incapaz de usarlo']],
                            'inst_comida' => ['Prepara Comida', [1=>'Planea/prepara solo', 2=>'Si le dan ingredientes', 3=>'Platos precocinados', 4=>'Le dan hecha']],
                            'inst_ropa' => ['Lava la ropa', [1=>'Personalmente', 2=>'Pequeñas prendas', 3=>'Incapaz']],
                            'inst_compras' => ['Va de compras', [1=>'Sin ayuda', 2=>'Pequeñas compras', 3=>'Acompañado', 4=>'Incapaz']],
                            'inst_dinero' => ['Maneja dinero', [1=>'Lleva cuentas', 2=>'Cuentas sencillas', 3=>'Incapaz']],
                            'inst_med' => ['Maneja medicamentos', [1=>'Responsable', 2=>'Hay que preparárselos', 3=>'Incapaz']]
                        ];
                        foreach($inst as $key => $data): ?>
                            <div class="item-row">
                                <div class="item-label"><?php echo $data[0]; ?></div>
                                <div class="item-control">
                                    <select name="<?php echo $key; ?>" class="premium-select calc-inst">
                                        <option value="">Seleccione...</option>
                                        <?php foreach($data[1] as $val => $opt): ?>
                                            <option value="<?php echo $val; ?>"><?php echo $opt; ?> (<?php echo $val; ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <div class="score-box">
                            <div class="premium-label">TOTAL INSTRUMENTAL:</div>
                            <input type="text" id="inst_total" name="inst_total" class="premium-input text-center score-value bg-gray" readonly placeholder="0">
                            <div id="inst_desc" class="score-desc bg-gray mt-2">--</div>
                            <input type="hidden" name="inst_desc" id="inst_desc_val">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 3. DEPRESIÓN (YESAVAGE) -->
            <div class="col-md-6">
                <div class="premium-panel">
                    <div class="premium-header purple">
                        <i class="fa fa-sad-tear"></i> 3. DEPRESIÓN (YESAVAGE)
                    </div>
                    <div class="premium-body" style="height: 600px; overflow-y: auto;">
                        <?php 
                        $dep = [
                            'dep_1' => ['Satisfecho con su vida', 0, 1], 'dep_2' => ['Dejó actividades de interés', 1, 0],
                            'dep_3' => ['Siente su vida vacía', 1, 0], 'dep_4' => ['Se aburre frecuencia', 1, 0],
                            'dep_5' => ['Buen ánimo mayor parte del tiempo', 0, 1], 'dep_6' => ['Preocupado algo malo sucederá', 1, 0],
                            'dep_7' => ['Feliz la mayor parte del tiempo', 0, 1], 'dep_8' => ['A menudo desamparado', 1, 0],
                            'dep_9' => ['Prefiere casa a salir', 1, 0], 'dep_10' => ['Problemas memoria > demás', 1, 0],
                            'dep_11' => ['Maravilloso estar vivo', 0, 1], 'dep_12' => ['Se siente inútil', 1, 0],
                            'dep_13' => ['Lleno de energía', 0, 1], 'dep_14' => ['Sin esperanza actual', 1, 0],
                            'dep_15' => ['Gente mejor que usted', 1, 0]
                        ];
                        foreach($dep as $key => $d): ?>
                            <div class="item-row">
                                <div class="item-label"><?php echo $d[0]; ?></div>
                                <div class="item-control-sm">
                                    <select name="<?php echo $key; ?>" class="premium-select calc-dep">
                                        <option value="">--</option>
                                        <option value="<?php echo $d[1]; ?>">SÍ (<?php echo $d[1]; ?>)</option>
                                        <option value="<?php echo $d[2]; ?>">NO (<?php echo $d[2]; ?>)</option>
                                    </select>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <div class="score-box" style="position: sticky; bottom: 0; z-index: 10;">
                            <div class="premium-label">TOTAL DEPRESIÓN:</div>
                            <input type="text" id="dep_total" name="dep_total" class="premium-input text-center score-value bg-gray" readonly placeholder="0">
                            <div id="dep_desc" class="score-desc bg-gray mt-2">--</div>
                            <input type="hidden" name="dep_desc" id="dep_desc_val">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 4. COGNITIVO -->
            <div class="col-md-6">
                <div class="premium-panel">
                    <div class="premium-header orange">
                        <i class="fa fa-brain"></i> 4. COGNITIVO
                    </div>
                    <div class="premium-body">
                        <?php 
                        $cog = [
                            'cog_fecha' => ['Fecha: Día, Mes, Año, Semana', [4=>'Año, Mes, Día, Sem.', 3=>'Año, Mes, Día', 2=>'Año, Mes', 1=>'Año', 0=>'No puede']],
                            'cog_obj' => ['Aprende 3 objetos', [3=>'3 objetos', 2=>'2 objetos', 1=>'1 objeto', 0=>'Ninguno']],
                            'cog_num' => ['Repite revés: 1,3,5,7,9', [5=>'5 núm', 4=>'4 núm', 3=>'3 núm', 2=>'2 núm', 1=>'1 núm', 0=>'Ninguno']],
                            'cog_papel' => ['Toma, dobla y coloca papel', [3=>'Toma, dobla, coloca', 2=>'Toma y dobla', 1=>'Toma', 0=>'No puede']],
                            'cog_pal' => ['Repite 3 palabras', [3=>'3 pal', 2=>'2 pal', 1=>'1 pal', 0=>'Ninguna']],
                            'cog_circ' => ['Copia 2 círculos cruzados', [1=>'Sí puede', 0=>'No puede']]
                        ];
                        foreach($cog as $key => $c): ?>
                            <div class="item-row">
                                <div class="item-label"><?php echo $c[0]; ?></div>
                                <div class="item-control">
                                    <select name="<?php echo $key; ?>" class="premium-select calc-cog">
                                        <option value="">Seleccione...</option>
                                        <?php foreach($c[1] as $val => $opt): ?>
                                            <option value="<?php echo $val; ?>"><?php echo $opt; ?> (<?php echo $val; ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <div class="score-box">
                            <div class="premium-label">TOTAL COGNITIVO:</div>
                            <input type="text" id="cog_total" name="cog_total" class="premium-input text-center score-value bg-gray" readonly placeholder="0">
                            <div id="cog_desc" class="score-desc bg-gray mt-2">--</div>
                            <input type="hidden" name="cog_desc" id="cog_desc_val">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 5. ACTIVIDADES BÁSICAS -->
            <div class="col-md-4">
                <div class="premium-panel">
                    <div class="premium-header teal">
                        <i class="fa fa-running"></i> 5. BASICAS
                    </div>
                    <div class="premium-body">
                        <?php 
                        $bas = ['bas_bana'=>'Se baña', 'bas_viste'=>'Viste/desviste', 'bas_apa'=>'Apariencia', 'bas_ino'=>'Inodoro', 'bas_esf'=>'Esfínteres', 'bas_tras'=>'Traslada', 'bas_camina'=>'Camina', 'bas_alim'=>'Alimenta'];
                        foreach($bas as $key => $label): ?>
                            <div class="item-row" style="padding: 4px 8px;">
                                <div class="item-label" style="font-size: 11px;"><?php echo $label; ?></div>
                                <div class="item-control-sm">
                                    <select name="<?php echo $key; ?>" class="premium-select calc-bas" style="padding: 4px; font-size: 11px;">
                                        <option value="">--</option>
                                        <option value="2">Indep(2)</option><option value="1">Ayuda(1)</option><option value="0">Depen(0)</option>
                                    </select>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <div class="score-box">
                            <div class="premium-label">TOTAL BÁSICAS:</div>
                            <input type="text" id="bas_total" name="bas_total" class="premium-input text-center score-value bg-gray" readonly placeholder="0">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 6. NUTRICIONAL -->
            <div class="col-md-4">
                <div class="premium-panel">
                    <div class="premium-header rose">
                        <i class="fa fa-utensils"></i> 6. NUTRICIONAL
                    </div>
                    <div class="premium-body">
                        <?php 
                        $nut = [
                            'nut_ingesta' => ['Disminución ingesta', [0=>'Severa(0)', 1=>'Moderada(1)', 2=>'Ausente(2)']],
                            'nut_peso' => ['Pérdida peso', [0=>'>3Kg (0)', 1=>'No sabe (1)', 2=>'1-3Kg (2)', 3=>'No pierde (3)']],
                            'nut_imc' => ['IMC', [0=>'<19 (0)', 1=>'19-20 (1)', 2=>'21-22 (2)', 3=>'23+ (3)']],
                            'nut_mov' => ['Movilidad', [0=>'Cama/Silla(0)', 1=>'No sale(1)', 2=>'Afuera(2)']],
                            'nut_psi' => ['Enf. Aguda/Psic.', [0=>'Sí (0)', 2=>'No (2)']],
                            'nut_dem' => ['Demencia/Depresión', [0=>'Severa (0)', 1=>'Moderada(1)', 2=>'Ausente(2)']]
                        ];
                        foreach($nut as $key => $n): ?>
                            <div class="item-row" style="padding: 4px 8px;">
                                <div class="item-label" style="font-size: 11px;"><?php echo $n[0]; ?></div>
                                <div class="item-control-sm">
                                    <select name="<?php echo $key; ?>" class="premium-select calc-nut" style="padding: 4px; font-size: 11px;">
                                        <option value="">--</option>
                                        <?php foreach($n[1] as $v => $lbl): ?><option value="<?php echo $v; ?>"><?php echo $lbl; ?></option><?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <div class="score-box">
                            <div class="premium-label">RIESGO NUTRICIÓN:</div>
                            <input type="text" id="nut_total" name="nut_total" class="premium-input text-center score-value bg-gray" readonly placeholder="0">
                            <div id="nut_desc" class="score-desc bg-gray mt-2">--</div>
                            <input type="hidden" name="nut_desc" id="nut_desc_val">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 7. RECURSO SOCIAL -->
            <div class="col-md-4">
                <div class="premium-panel">
                    <div class="premium-header slate">
                        <i class="fa fa-users"></i> 7. SOCIAL
                    </div>
                    <div class="premium-body">
                        <?php 
                        $soc = [
                            'soc_fam' => ['Familiar', [1=>'Familiar', 2=>'No Familiar', 3=>'Solo', 4=>'Institución', 5=>'Desatendido']],
                            'soc_rel' => ['Relaciones', [1=>'Fam/Pareja sin conf.', 2=>'Pareja edad', 3=>'Pareja con conf.', 4=>'Familia no cubre', 5=>'Nadie']],
                            'soc_apoyo' => ['Apoyo Red', [1=>'Todos sale', 2=>'Fam/Vec sale', 3=>'Fam sale', 4=>'Fam/Vis no sale', 5=>'Nadie no sale']],
                            'soc_edad' => ['Edad', [1=>'65-74', 2=>'75-84', 3=>'85-94', 4=>'95+']]
                        ];
                        foreach($soc as $key => $s): ?>
                            <div class="item-row" style="padding: 4px 8px;">
                                <div class="item-label" style="font-size: 11px;"><?php echo $s[0]; ?></div>
                                <div class="item-control-sm">
                                    <select name="<?php echo $key; ?>" class="premium-select calc-soc" style="padding: 4px; font-size: 11px;">
                                        <option value="">--</option>
                                        <?php foreach($s[1] as $v => $lbl): ?><option value="<?php echo $v; ?>"><?php echo $lbl; ?></option><?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <div class="score-box">
                            <div class="premium-label">RIESGO SOCIAL:</div>
                            <input type="text" id="soc_total" name="soc_total" class="premium-input text-center score-value bg-gray" readonly placeholder="0">
                            <div id="soc_desc" class="score-desc bg-gray mt-2">--</div>
                            <input type="hidden" name="soc_desc" id="soc_desc_val">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- DIAGNÓSTICO SINDROMÁTICO Y PLAN -->
        <div class="premium-panel">
            <div class="premium-header slate">
                <i class="fa fa-stethoscope"></i> CONCLUSIONES Y PLAN
            </div>
            <div class="premium-body">
                <div class="row">
                    <div class="col-md-6">
                        <label class="premium-label">DIAGNÓSTICO SINDROMÁTICO INTEGRAL</label>
                        <textarea name="geri_diag" class="premium-input" rows="4" placeholder="Integración de resultados geriátricos..."></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="premium-label">PLAN DE INTERVENCIÓN</label>
                        <textarea name="geri_plan" class="premium-input" rows="4" placeholder="Plan de tratamiento integral..."></textarea>
                    </div>
                </div>
                <div class="row" style="margin-top: 15px;">
                    <div class="col-md-4">
                        <label class="premium-label"><i class="fa fa-calendar"></i> PRÓXIMA CITA VGI</label>
                        <input type="date" name="geri_proxima_cita" class="premium-input">
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
$(document).ready(function() {
    function setScore(id, total, descId, rules) {
        $(id).val(total);
        let cl = 'bg-gray', txt = '--';
        for (let r of rules) {
            if (eval(total + r.op)) { cl = r.cl; txt = r.tx; break; }
        }
        $(descId).text(txt).removeClass('bg-gray bg-green bg-yellow bg-red').addClass(cl);
        $(descId + '_val').val(txt);
        $(id).removeClass('bg-gray bg-green bg-yellow bg-red').addClass(cl);
    }

    $('.calc-tam').change(function() {
        let sum = 0; $('.calc-tam').each(function() { sum += Number($(this).val() || 0); });
        $('#tam_total').val(sum).removeClass('bg-gray bg-green bg-yellow bg-red').addClass(sum > 0 ? 'bg-yellow' : 'bg-green');
    });

    $('.calc-inst').change(function() {
        let sum = 0; $('.calc-inst').each(function() { sum += Number($(this).val() || 0); });
        setScore('#inst_total', sum, '#inst_desc', [{op:'<=8', cl:'bg-green', tx:'Independiente'}, {op:'<=20', cl:'bg-yellow', tx:'Cierta ayuda'}, {op:'>20', cl:'bg-red', tx:'Mucha ayuda'}]);
    });

    $('.calc-dep').change(function() {
        let sum = 0; $('.calc-dep').each(function() { sum += Number($(this).val() || 0); });
        setScore('#dep_total', sum, '#dep_desc', [{op:'<=5', cl:'bg-green', tx:'Normal'}, {op:'<=10', cl:'bg-yellow', tx:'Depresión Moderada'}, {op:'>10', cl:'bg-red', tx:'Depresión Severa'}]);
    });

    $('.calc-cog').change(function() {
        let sum = 0; $('.calc-cog').each(function() { sum += Number($(this).val() || 0); });
        setScore('#cog_total', sum, '#cog_desc', [{op:'>=14', cl:'bg-green', tx:'Ausente (Normal)'}, {op:'<14', cl:'bg-red', tx:'Deterioro Presente'}]);
    });

    $('.calc-bas').change(function() {
        let sum = 0; $('.calc-bas').each(function() { sum += Number($(this).val() || 0); });
        $('#bas_total').val(sum).removeClass('bg-gray bg-green bg-yellow bg-red').addClass(sum >= 14 ? 'bg-green' : (sum >= 8 ? 'bg-yellow' : 'bg-red'));
    });

    $('.calc-nut').change(function() {
        let sum = 0; $('.calc-nut').each(function() { sum += Number($(this).val() || 0); });
        setScore('#nut_total', sum, '#nut_desc', [{op:'>=12', cl:'bg-green', tx:'Riesgo Ausente'}, {op:'<12', cl:'bg-red', tx:'Riesgo Presente'}]);
    });

    $('.calc-soc').change(function() {
        let sum = 0; $('.calc-soc').each(function() { sum += Number($(this).val() || 0); });
        setScore('#soc_total', sum, '#soc_desc', [{op:'<=5', cl:'bg-green', tx:'Riesgo Bajo'}, {op:'<=9', cl:'bg-yellow', tx:'Riesgo Aceptable'}, {op:'>9', cl:'bg-red', tx:'Riesgo Alto'}]);
    });
});
</script>
