<?php
/**
 * HISTORIA CLÍNICA DE NUTRICIÓN - VERSIÓN ULTRA-PROFESIONAL (CONGRUENCIA SENIOR)
 */
?>
<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="NUTRICION">

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&display=swap');

        :root {
            --nutri-primary: #0d9488;
            --nutri-secondary: #0f172a;
            --nutri-accent: #f59e0b;
            --nutri-bg: #f8fafc;
            --nutri-card: #ffffff;
            --nutri-border: #e2e8f0;
            --nutri-text: #334155;
            --nutri-success: #22c55e;
            --nutri-danger: #ef4444;
        }

        .nutri-wrapper {
            font-family: 'Outfit', sans-serif;
            background-color: var(--nutri-bg);
            padding: 20px;
            color: var(--nutri-text);
        }

        /* Dashboard de Inteligencia */
        .smart-dashboard {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 15px;
            margin: 20px 0;
            padding: 20px;
            background: #f1f5f9;
            border-radius: 20px;
            border: 1px dashed var(--nutri-primary);
        }

        .smart-card {
            background: white;
            border: 1px solid var(--nutri-border);
            border-radius: 16px;
            padding: 15px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .smart-card i { font-size: 1.3rem; color: var(--nutri-primary); margin-bottom: 5px; }
        .smart-val { font-size: 1.6rem; font-weight: 700; color: var(--nutri-secondary); display: block; }
        .smart-label { font-size: 0.7rem; text-transform: uppercase; font-weight: 600; color: #64748b; }
        .smart-badge { font-size: 0.7rem; padding: 2px 8px; border-radius: 10px; font-weight: 700; margin-top: 5px; display: inline-block; }

        .nutri-section {
            background: var(--nutri-card);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 30px;
            border: 1px solid var(--nutri-border);
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .nutri-section-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 25px;
            border-bottom: 2px solid #f1f5f9;
            padding-bottom: 12px;
        }

        .nutri-section-header h3 { font-weight: 700; color: var(--nutri-secondary); margin: 0; font-size: 1.2rem; text-transform: uppercase; }
        .nutri-icon-circle { background: rgba(13, 148, 136, 0.1); color: var(--nutri-primary); width: 35px; height: 35px; border-radius: 10px; display: flex; align-items: center; justify-content: center; }

        .nutri-label { display: block; font-weight: 600; font-size: 0.85rem; color: #475569; margin-bottom: 6px; }
        .nutri-input, .nutri-select, .nutri-textarea {
            width: 100%; border: 1.5px solid var(--nutri-border); border-radius: 10px; padding: 10px 14px; font-size: 0.95rem; background: #fff; color: var(--nutri-text);
        }
        .nutri-input:focus { border-color: var(--nutri-primary); outline: none; box-shadow: 0 0 0 4px rgba(13, 148, 136, 0.1); }

        .nutri-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; }

        /* Calculadora Estilo Senior */
        .macro-calc-container {
            background: #f8fafc;
            border: 2px solid var(--nutri-secondary);
            border-radius: 20px;
            padding: 25px;
            margin-top: 20px;
        }
        .macro-input-pill {
            background: white;
            border: 1px solid #e2e8f0;
            padding: 15px;
            border-radius: 15px;
            text-align: center;
        }
        .macro-input-pill input {
            font-size: 1.5rem;
            font-weight: 700;
            text-align: center;
            border: none;
            width: 100%;
            color: var(--nutri-primary);
        }
        .macro-input-pill input:focus { outline: none; }

        .macro-results-bar {
            display: flex;
            justify-content: space-around;
            background: var(--nutri-secondary);
            padding: 15px;
            border-radius: 15px;
            margin-top: 15px;
            color: white;
        }
        .res-item { text-align: center; }
        .res-val { font-size: 1.2rem; font-weight: 700; display: block; }
        .res-lbl { font-size: 0.7rem; color: #94a3b8; text-transform: uppercase; }

        .nutri-check-group { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; padding: 15px; background: #f8fafc; border-radius: 12px; }
        .nutri-check-item { display: flex; align-items: center; gap: 8px; font-size: 0.85rem; }
        .nutri-check-item input { width: 16px; height: 16px; accent-color: var(--nutri-primary); }

        .recordatorio-table { width: 100%; border-collapse: collapse; }
        .recordatorio-table td { padding: 10px; border-bottom: 1px solid #f1f5f9; }
    </style>

    <div class="nutri-wrapper">
        
        <?php include __DIR__ . '/partials/patient_header.php'; ?>

        <div style="margin: 20px 0;">
            <h2 style="font-weight: 800; color: var(--nutri-secondary); margin: 0;">Historia Clínica de Nutrición</h2>
        </div>

        <!-- SECCIÓN I: ANTECEDENTES -->
        <div class="nutri-section">
            <div class="nutri-section-header">
                <div class="nutri-icon-circle"><i class="fa fa-history"></i></div>
                <h3>I. Antecedentes Clínicos</h3>
            </div>
            <div class="nutri-grid">
                <div class="nutri-form-group">
                    <label class="nutri-label">Ocupación</label>
                    <input type="text" class="nutri-input" name="ant_ocupacion">
                </div>
                <div class="nutri-form-group">
                    <label class="nutri-label">Estado Civil</label>
                    <select class="nutri-select" name="ant_estado_civil">
                        <option value="SOLTERO">Soltero/a</option>
                        <option value="CASADO">Casado/a</option>
                        <option value="UNION_LIBRE">Unión Libre</option>
                    </select>
                </div>
            </div>
            
            <label class="nutri-label" style="margin-top: 15px;">Antecedentes Patológicos (APP)</label>
            <div class="nutri-check-group">
                <label class="nutri-check-item"><input type="checkbox" name="app_diabetes"> Diabetes</label>
                <label class="nutri-check-item"><input type="checkbox" name="app_hta"> Hipertensión</label>
                <label class="nutri-check-item"><input type="checkbox" name="app_obesidad"> Obesidad</label>
                <label class="nutri-check-item"><input type="checkbox" name="app_higado"> Hepático</label>
                <label class="nutri-check-item"><input type="checkbox" name="app_renal"> Renal</label>
            </div>

            <label class="nutri-label" style="margin-top: 15px;">Síntomas Gastrointestinales</label>
            <div class="nutri-check-group">
                <label class="nutri-check-item"><input type="checkbox" name="gi_acidez"> Acidez</label>
                <label class="nutri-check-item"><input type="checkbox" name="gi_gastritis"> Gastritis</label>
                <label class="nutri-check-item"><input type="checkbox" name="gi_reflujo"> Reflujo</label>
                <label class="nutri-check-item"><input type="checkbox" name="gi_constipacion"> Estreñimiento</label>
            </div>
        </div>

        <!-- SECCIÓN II: ESTILO DE VIDA -->
        <div class="nutri-section">
            <div class="nutri-section-header">
                <div class="nutri-icon-circle"><i class="fa fa-leaf"></i></div>
                <h3>II. Estilo de Vida</h3>
            </div>
            <div class="nutri-grid">
                <div class="nutri-form-group">
                    <label class="nutri-label">Horas Sueño</label>
                    <input type="number" class="nutri-input" name="hab_sueño">
                </div>
                <div class="nutri-form-group">
                    <label class="nutri-label">Agua (Lts)</label>
                    <input type="number" step="0.1" class="nutri-input" name="hab_agua_real">
                </div>
                <div class="nutri-form-group">
                    <label class="nutri-label">Actividad Física (veces/sem)</label>
                    <input type="number" class="nutri-input" id="hab_ejercicio_frec" name="hab_ejercicio_frec">
                </div>
            </div>
        </div>

        <!-- SECCIÓN III: ANTROPOMETRÍA + DASHBOARD (CONGRUENCIA) -->
        <div class="nutri-section" style="border-left: 5px solid var(--nutri-primary);">
            <div class="nutri-section-header">
                <div class="nutri-icon-circle"><i class="fa fa-user"></i></div>
                <h3>III. Evaluación Antropométrica</h3>
            </div>
            <div class="nutri-grid">
                <div class="nutri-form-group">
                    <label class="nutri-label">Peso Actual (Kg)</label>
                    <input type="number" step="0.1" class="nutri-input calc-trigger" id="eval_peso_actual" name="eval_peso_actual">
                </div>
                <div class="nutri-form-group">
                    <label class="nutri-label">Talla (cm)</label>
                    <input type="number" step="0.1" class="nutri-input calc-trigger" id="eval_talla" name="eval_talla">
                </div>
                <div class="nutri-form-group">
                    <label class="nutri-label">Cintura (cm)</label>
                    <input type="number" step="0.1" class="nutri-input calc-trigger" id="eval_cintura" name="eval_cintura">
                </div>
                <div class="nutri-form-group">
                    <label class="nutri-label">Cadera (cm)</label>
                    <input type="number" step="0.1" class="nutri-input calc-trigger" id="eval_cadera" name="eval_cadera">
                </div>
            </div>

            <!-- DASHBOARD AQUÍ ABAJO (DONDE OCURRE LA MAGIA) -->
            <div class="smart-dashboard">
                <div class="smart-card">
                    <i class="fa fa-heartbeat"></i>
                    <span class="smart-label">IMC</span>
                    <span class="smart-val" id="smart_imc">--</span>
                    <span class="smart-badge" id="smart_imc_tag">--</span>
                    <input type="hidden" name="calc_imc" id="h_imc">
                </div>
                <div class="smart-card">
                    <i class="fa fa-balance-scale"></i>
                    <span class="smart-label">Peso Ideal</span>
                    <span class="smart-val" id="smart_ideal">--</span>
                    <span class="smart-badge">Kg</span>
                    <input type="hidden" name="calc_peso_ideal" id="h_peso_ideal">
                </div>
                <div class="smart-card">
                    <i class="fa fa-bolt"></i>
                    <span class="smart-label">Gasto Total (GET)</span>
                    <span class="smart-val" id="smart_get">--</span>
                    <span class="smart-badge">kcal</span>
                    <input type="hidden" name="calc_get" id="h_get">
                </div>
                <div class="smart-card">
                    <i class="fa fa-tint"></i>
                    <span class="smart-label">Agua Rec.</span>
                    <span class="smart-val" id="smart_agua">--</span>
                    <span class="smart-badge">Litros</span>
                    <input type="hidden" name="calc_agua" id="h_agua">
                </div>
                <div class="smart-card" id="card_rcc">
                    <i class="fa fa-warning"></i>
                    <span class="smart-label">Riesgo (RCC)</span>
                    <span class="smart-val" id="smart_rcc">--</span>
                    <span class="smart-badge" id="smart_rcc_tag">--</span>
                    <input type="hidden" name="calc_rcc" id="h_rcc">
                </div>
            </div>
        </div>

        <!-- SECCIÓN IV: BIOQUÍMICOS -->
        <div class="nutri-section">
            <div class="nutri-section-header">
                <div class="nutri-icon-circle"><i class="fa fa-flask"></i></div>
                <h3>IV. Exámenes de Laboratorio</h3>
            </div>
            <div class="nutri-grid">
                <div class="nutri-form-group">
                    <label class="nutri-label">Glucosa</label>
                    <input type="number" class="nutri-input" name="lab_glucosa">
                </div>
                <div class="nutri-form-group">
                    <label class="nutri-label">Colesterol</label>
                    <input type="number" class="nutri-input" name="lab_col_total">
                </div>
                <div class="nutri-form-group">
                    <label class="nutri-label">Triglicéridos</label>
                    <input type="number" class="nutri-input" name="lab_trigli">
                </div>
            </div>
        </div>

        <!-- SECCIÓN V: PLAN Y CALCULADORA (VISIBILIDAD PERFECTA) -->
        <div class="nutri-section">
            <div class="nutri-section-header">
                <div class="nutri-icon-circle"><i class="fa fa-pencil"></i></div>
                <h3>V. Plan Nutricional</h3>
            </div>
            
            <label class="nutri-label">Diagnóstico / Objetivos</label>
            <textarea class="nutri-textarea" name="nutri_objetivos" rows="3"></textarea>

            <div class="macro-calc-container">
                <h4 style="margin: 0 0 15px 0; color: var(--nutri-secondary); font-weight: 700;">Calculadora de Macronutrientes</h4>
                <div class="nutri-grid">
                    <div class="macro-input-pill">
                        <label class="nutri-label">Calorías Meta</label>
                        <input type="number" id="plan_kcal" name="plan_kcal" placeholder="0">
                        <span style="font-size: 0.7rem; color: #64748b;">kcal</span>
                    </div>
                    <div class="macro-input-pill">
                        <label class="nutri-label">% CHO</label>
                        <input type="number" id="plan_cho_perc" name="plan_cho_perc" class="calc-macro" placeholder="0">
                        <span style="font-size: 0.7rem; color: #64748b;">Carbohidratos</span>
                    </div>
                    <div class="macro-input-pill">
                        <label class="nutri-label">% PRO</label>
                        <input type="number" id="plan_pro_perc" name="plan_pro_perc" class="calc-macro" placeholder="0">
                        <span style="font-size: 0.7rem; color: #64748b;">Proteínas</span>
                    </div>
                    <div class="macro-input-pill">
                        <label class="nutri-label">% FAT</label>
                        <input type="number" id="plan_fat_perc" name="plan_fat_perc" class="calc-macro" placeholder="0">
                        <span style="font-size: 0.7rem; color: #64748b;">Grasas</span>
                    </div>
                </div>

                <div class="macro-results-bar">
                    <div class="res-item">
                        <span class="res-val" id="macro_cho_gr">0g</span>
                        <span class="res-lbl">CHO</span>
                    </div>
                    <div class="res-item">
                        <span class="res-val" id="macro_pro_gr">0g</span>
                        <span class="res-lbl">PRO</span>
                    </div>
                    <div class="res-item">
                        <span class="res-val" id="macro_fat_gr">0g</span>
                        <span class="res-lbl">FAT</span>
                    </div>
                    <div class="res-item">
                        <span class="res-val" id="macro_total_perc" style="color: #f87171;">0%</span>
                        <span class="res-lbl">Total %</span>
                    </div>
                </div>
                <input type="hidden" name="plan_cho_gr" id="h_plan_cho_gr">
                <input type="hidden" name="plan_pro_gr" id="h_plan_pro_gr">
                <input type="hidden" name="plan_fat_gr" id="h_plan_fat_gr">
            </div>
            
            <div class="nutri-grid" style="margin-top: 20px;">
                <div class="nutri-form-group">
                    <label class="nutri-label">Próxima Cita</label>
                    <input type="date" class="nutri-input" name="nutri_proxima_cita">
                </div>
            </div>
        </div>

    </div>
</form>

<script>
(function() {
    const getV = (id) => {
        const el = document.getElementById(id);
        return el ? (parseFloat(el.value) || 0) : 0;
    };
    const setT = (id, val) => { if(document.getElementById(id)) document.getElementById(id).innerText = val; };
    const setV = (id, val) => { if(document.getElementById(id)) document.getElementById(id).value = val; };

    function updateCalculos() {
        const peso = getV('eval_peso_actual');
        const talla = getV('eval_talla');
        const cintura = getV('eval_cintura');
        const cadera = getV('eval_cadera');
        
        // Obtener datos del paciente si están disponibles en el header del sistema
        const sexo = (document.getElementById('lbl_sexo')) ? document.getElementById('lbl_sexo').innerText : 'M';
        const edadText = (document.getElementById('lbl_edad')) ? document.getElementById('lbl_edad').innerText : '30';
        const edad = parseInt(edadText.replace(/\D/g,'')) || 30;

        if (peso > 0 && talla > 0) {
            // IMC
            const imc = (peso / ((talla/100)**2)).toFixed(2);
            setT('smart_imc', imc);
            setV('h_imc', imc);
            
            const tag = document.getElementById('smart_imc_tag');
            if (imc < 18.5) { tag.innerText = "Bajo Peso"; tag.className="smart-badge"; tag.style.background="#e0f2fe"; tag.style.color="#0369a1"; }
            else if (imc < 25) { tag.innerText = "Normal"; tag.className="smart-badge"; tag.style.background="#dcfce7"; tag.style.color="#166534"; }
            else if (imc < 30) { tag.innerText = "Sobrepeso"; tag.className="smart-badge"; tag.style.background="#fef3c7"; tag.style.color="#92400e"; }
            else { tag.innerText = "Obesidad"; tag.className="smart-badge"; tag.style.background="#fee2e2"; tag.style.color="#b91c1c"; }

            // Peso Ideal
            const pulg = (talla - 152.4) / 2.54;
            let ideal = (sexo.toUpperCase().includes('M')) ? 48 + (2.7 * pulg) : 45.5 + (2.2 * pulg);
            setT('smart_ideal', ideal.toFixed(1));
            setV('h_peso_ideal', ideal.toFixed(1));

            // GET
            let s = (sexo.toUpperCase().includes('M')) ? 5 : -161;
            const geb = (10 * peso) + (6.25 * talla) - (5 * edad) + s;
            const fa = 1.2 + (getV('hab_ejercicio_frec') * 0.1); // Estimación simple
            const getVal = Math.round(geb * fa);
            setT('smart_get', getVal);
            setV('h_get', getVal);
            if(getV('plan_kcal') === 0) setV('plan_kcal', getVal);

            // Agua
            setT('smart_agua', (peso * 0.035).toFixed(1));
        }

        if (cintura > 0 && cadera > 0) {
            const rcc = (cintura / cadera).toFixed(2);
            setT('smart_rcc', rcc);
            const tagR = document.getElementById('smart_rcc_tag');
            let lim = (sexo.toUpperCase().includes('M')) ? 0.94 : 0.85;
            tagR.innerText = (rcc > lim) ? "ALTO RIESGO" : "BAJO RIESGO";
            tagR.style.color = (rcc > lim) ? "#b91c1c" : "#166534";
        }
    }

    function updateMacros() {
        const kcal = getV('plan_kcal');
        const pCho = getV('plan_cho_perc');
        const pPro = getV('plan_pro_perc');
        const pFat = getV('plan_fat_perc');
        const total = pCho + pPro + pFat;

        setT('macro_total_perc', total + '%');
        document.getElementById('macro_total_perc').style.color = (total === 100) ? '#22c55e' : '#f87171';

        if (kcal > 0) {
            const gCho = Math.round((kcal * (pCho/100)) / 4);
            const gPro = Math.round((kcal * (pPro/100)) / 4);
            const gFat = Math.round((kcal * (pFat/100)) / 9);
            setT('macro_cho_gr', gCho + 'g');
            setT('macro_pro_gr', gPro + 'g');
            setT('macro_fat_gr', gFat + 'g');
        }
    }

    function init() {
        ['eval_peso_actual', 'eval_talla', 'eval_cintura', 'eval_cadera', 'hab_ejercicio_frec'].forEach(id => {
            if(document.getElementById(id)) document.getElementById(id).addEventListener('input', updateCalculos);
        });
        ['plan_kcal', 'plan_cho_perc', 'plan_pro_perc', 'plan_fat_perc'].forEach(id => {
            if(document.getElementById(id)) document.getElementById(id).addEventListener('input', updateMacros);
        });
        updateCalculos();
    }
    setTimeout(init, 800);
})();
</script>
