<?php
/**
 * OTIS Health Command Center
 * Premium SAAS Dashboard
 */
$activeTab = $activeTab ?? 'medical';

// BMI Calculation
$bmi = 0; $bmiClass = ''; $bmiText = '';
if($profile && $profile->height > 0 && $profile->current_weight > 0) {
    $h = $profile->height / 100;
    $bmi = $profile->current_weight / ($h * $h);
    if($bmi < 18.5) { $bmiClass = 'text-warning'; $bmiText = 'نحافة'; }
    elseif($bmi < 25) { $bmiClass = 'text-success'; $bmiText = 'وزن مثالي'; }
    elseif($bmi < 30) { $bmiClass = 'text-warning'; $bmiText = 'وزن زائد'; }
    else { $bmiClass = 'text-danger'; $bmiText = 'سمنة'; }
}

// Chart.js Preparation for Weights
$weightLabels = [];
$weightData = [];
$rWeights = array_reverse($weights ?? []);
foreach($rWeights as $w) {
    if(!is_object($w)) continue;
    $weightLabels[] = date('M d', strtotime($w->logged_at));
    $weightData[] = (float)$w->weight;
}

// Fasting Variables for JavaScript
$hasActiveFast = $activeFast ? true : false;
$fastStartJs = $activeFast ? (new DateTime($activeFast->start_time))->format('c') : '';
$fastPlanHours = $activeFast ? $activeFast->plan_hours : ($profile->fasting_plan ?? 16);
?>

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

:root {
    --bg-health-main: #f1f5f9;
    --card-bg: #ffffff;
    --primary: #0284c7;
    --primary-subtle: #e0f2fe;
    --success: #10b981;
    --success-subtle: #d1fae5;
    --danger: #ef4444;
    --danger-subtle: #fee2e2;
    --warning: #f59e0b;
    --warning-subtle: #fef3c7;
    --dark: #0f172a;
    --muted: #64748b;
}

.health-dashboard-wrapper { 
    background-color: var(--bg-health-main); 
    font-family: 'Cairo', sans-serif; 
    color: var(--dark); 
    padding: 1.5rem 0;
    min-height: calc(100vh - 100px);
}

/* Glass & Saas Elements */
.card-saas {
    border-radius: 20px; border: none;
    background: var(--card-bg);
    box-shadow: 0 4px 15px rgba(0,0,0,0.03), 0 1px 3px rgba(0,0,0,0.02);
    transition: all 0.3s ease;
    overflow: hidden;
}
.card-saas:hover { box-shadow: 0 10px 30px rgba(0,0,0,0.06); }

/* Animations */
@keyframes fadeSlideUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }
.animate-slide-up { animation: fadeSlideUp 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; opacity: 0; }
.delay-1 { animation-delay: 0.1s; } .delay-2 { animation-delay: 0.2s; } .delay-3 { animation-delay: 0.3s; }

/* Dashboard Top Header */
.dashboard-header { background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); border-radius: 24px; padding: 2rem; color: #fff; position: relative; overflow: hidden; }
.header-blob { position: absolute; top: -50px; right: -50px; width: 200px; height: 200px; background: rgba(56, 189, 248, 0.2); filter: blur(40px); border-radius: 50%; }

/* Vitality Ring */
.vitality-ring-container { position: relative; width: 140px; height: 140px; }
.vitality-ring-bg { fill: none; stroke: rgba(255,255,255,0.1); stroke-width: 6; }
.vitality-ring { fill: none; stroke: var(--success); stroke-width: 6; stroke-linecap: round; stroke-dasharray: 0 100; transition: stroke 0.5s; animation: ringFill 1.5s ease-out forwards; }
@keyframes ringFill { 0% { stroke-dasharray: 0 100; } }
.vitality-ring.score-high { stroke: #10b981; }
.vitality-ring.score-med { stroke: #f59e0b; }
.vitality-ring.score-low { stroke: #ef4444; }

/* Quick Actions */
.quick-action-btn { background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); color: #fff; border-radius: 12px; padding: 0.75rem 1rem; transition: all 0.2s; font-weight: 600; display: flex; align-items: center; gap: 8px; backdrop-filter: blur(5px); }
.quick-action-btn:hover { background: rgba(255,255,255,0.2); transform: translateY(-3px); color: #fff; }

/* Tabs */
.cmd-tabs { background: #e2e8f0; border-radius: 16px; padding: 6px; display: inline-flex; gap: 5px; flex-wrap: wrap; }
.cmd-tabs .nav-link { border: none; background: transparent; color: var(--muted); font-weight: 700; border-radius: 12px; padding: 0.75rem 1.5rem; transition: 0.3s; }
.cmd-tabs .nav-link:hover { color: var(--dark); background: rgba(255,255,255,0.5); }
.cmd-tabs .nav-link.active { background: #fff; color: var(--primary); box-shadow: 0 2px 10px rgba(0,0,0,0.05); }

/* Fasting Engine */
.fasting-engine-ui { background: radial-gradient(circle at center, #ffffff 0%, #f8fafc 100%); border: 2px solid var(--success-subtle); position: relative; }
@keyframes breathe { 0%, 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); } 50% { box-shadow: 0 0 0 15px rgba(16, 185, 129, 0); } }
.fasting-active-pulse { animation: breathe 3s infinite; }
.fast-arc-container { position: relative; width: 220px; height: 220px; margin: 0 auto; }
.fast-timer-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; }
.fast-stage-badge { position: absolute; bottom: -15px; left: 50%; transform: translateX(-50%); background: #fff; border-radius: 20px; padding: 4px 12px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); font-weight: bold; font-size: 0.8rem; border: 1px solid var(--success-subtle); color: var(--success); white-space: nowrap; }

/* Unified Timeline */
.timeline-item { border-right: 3px solid #e2e8f0; padding-right: 1rem; position: relative; margin-bottom: 1.5rem; }
.timeline-item::before { content: ""; position: absolute; width: 12px; height: 12px; border-radius: 50%; background: #cbd5e1; right: -7.5px; top: 5px; border: 2px solid #fff; }
.timeline-item.t-meal::before { background: var(--warning); }
.timeline-item.t-fast::before { background: var(--success); }
.timeline-item.t-lab::before { background: var(--primary); }
.timeline-item.t-med::before { background: var(--danger); }

/* Modals */
.modal-content { border-radius: 24px; border: none; overflow: hidden; }
.btn-premium { border-radius: 12px; font-weight: 700; padding: 0.6rem 1.5rem; }
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div class="health-dashboard-wrapper">
<div class="container-fluid py-4">

    <?= display_flash_message('health') ?>

    <!-- 1. TOP HEADER (Vitality Command Center) -->
    <div class="dashboard-header mb-4 shadow-sm animate-slide-up">
        <div class="header-blob"></div>
        <div class="row align-items-center position-relative z-1">
            <div class="col-md-7 d-flex align-items-center gap-4">
                <div class="vitality-ring-container">
                    <svg width="140" height="140" viewBox="0 0 36 36">
                        <path class="vitality-ring-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                        <path class="vitality-ring <?= $vitality['score'] >= 80 ? 'score-high' : ($vitality['score'] >= 50 ? 'score-med' : 'score-low') ?>" stroke-dasharray="<?= $vitality['score'] ?>, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                    </svg>
                    <div style="position: absolute; top:50%; left:50%; transform:translate(-50%, -50%); text-align:center;">
                        <span class="d-block fw-bold display-5 lh-1 mb-0"><?= $vitality['score'] ?></span>
                    </div>
                    <div class="fast-stage-badge" style="bottom: 0px; <?= $vitality['score'] >= 80 ? 'color:#10b981; border-color:#d1fae5;' : ($vitality['score'] >= 50 ? 'color:#f59e0b; border-color:#fef3c7;' : 'color:#ef4444; border-color:#fee2e2;') ?>">
                        <i class="fa-solid <?= $vitality['status']['icon'] ?>"></i> <?= $vitality['status']['text'] ?>
                    </div>
                </div>
                <div>
                    <h1 class="fw-bold mb-1 fs-3">مركز القيادة الحيوية</h1>
                    <p class="text-white-50 mb-0">نظام المراقبة والاستراتيجية الجسدية</p>
                </div>
            </div>
            <div class="col-md-5 mt-4 mt-md-0 d-flex flex-wrap justify-content-md-end gap-2">
                <button class="quick-action-btn" data-bs-toggle="modal" data-bs-target="#addMealModal"><i class="fa-solid fa-utensils text-warning"></i> توثيق وجبة</button>
                <button class="quick-action-btn" onclick="logWater(this, false, <?= $profile->water_goal ?? 8 ?>)"><i class="fa-solid fa-glass-water text-info"></i> كوب ماء</button>
                <button class="quick-action-btn" data-bs-toggle="modal" data-bs-target="#addSymptomModal"><i class="fa-solid fa-head-side-cough text-danger"></i> عرض صحي</button>
                <button class="quick-action-btn" data-bs-toggle="modal" data-bs-target="#profileModal"><i class="fa-solid fa-sliders text-muted"></i> التكوين</button>
            </div>
        </div>
    </div>

    <!-- MAIN GRID -->
    <div class="row g-4">
        
        <!-- LEFT COLUMN (Main Engines) -->
        <div class="col-xl-8">
            <div class="animate-slide-up delay-1 mb-4 d-flex justify-content-center justify-content-xl-start">
                <ul class="nav nav-tabs cmd-tabs" role="tablist">
                    <li class="nav-item"><button class="nav-link <?= $activeTab=='vitality'?'active':'' ?>" data-bs-toggle="tab" data-bs-target="#vitality"><i class="fa-solid fa-heart-pulse me-2"></i> الحيوية والأعراض</button></li>
                    <li class="nav-item"><button class="nav-link <?= $activeTab=='nutrition'?'active':'' ?>" data-bs-toggle="tab" data-bs-target="#nutrition"><i class="fa-solid fa-leaf me-2"></i> التغذية والصيام</button></li>
                    <li class="nav-item"><button class="nav-link <?= $activeTab=='medical'?'active':'' ?>" data-bs-toggle="tab" data-bs-target="#medical"><i class="fa-solid fa-notes-medical me-2"></i> المركز الطبي</button></li>
                </ul>
            </div>

            <div class="tab-content">
                
                <!-- TAB 1: MEDICAL HUB -->
                <div class="tab-pane fade <?= $activeTab=='medical'?'show active':'' ?>" id="medical">
                    <!-- Medications -->
                    <div class="card card-saas mb-4 animate-slide-up delay-1">
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h5 class="fw-bold mb-0 text-dark"><i class="fa-solid fa-capsules text-primary me-2"></i> جدول الأدوية والمكملات</h5>
                                <button class="btn btn-sm btn-outline-primary fw-bold rounded-pill shadow-sm" data-bs-toggle="modal" data-bs-target="#addMedModal">إضافة علاج <i class="fa-solid fa-plus ms-1"></i></button>
                            </div>
                            <?php if(empty($medications)): ?>
                                <p class="text-muted text-center py-3">لا توجد أدوية مسجلة حالياً.</p>
                            <?php else: ?>
                                <div class="d-flex flex-column gap-3">
                                <?php foreach($medications as $med): 
                                    $isTaken = in_array($med->id, $takenMeds);
                                ?>
                                    <div class="p-3 border-0 rounded-4 <?= $isTaken ? 'bg-success-subtle opacity-75' : 'bg-light' ?> position-relative d-flex justify-content-between align-items-center shadow-sm med-row-container transition">
                                        <div class="form-check form-switch mb-0 d-flex align-items-center">
                                           <input class="form-check-input ms-3 med-checkbox" style="width: 2.5rem; height: 1.25rem; cursor:pointer;" type="checkbox" role="switch" <?= $isTaken ? 'checked' : '' ?> onclick="takeMed(<?= $med->id ?>, this, <?= $isTaken ? 'true' : 'false' ?>)">
                                           <div>
                                               <h6 class="mb-0 fw-bold text-dark <?= $isTaken ? 'text-decoration-line-through text-success' : '' ?>"><?= htmlspecialchars($med->med_name) ?></h6>
                                               <small class="text-secondary fw-semibold"><?= htmlspecialchars($med->dose) ?> | <?= htmlspecialchars($med->frequency) ?></small>
                                           </div>
                                        </div>
                                        <a href="<?= BASE_URL ?>/health/delete/health_medications/<?= $med->id ?>" class="text-danger opacity-50"><i class="fa-solid fa-trash"></i></a>
                                    </div>
                                <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Labs & Prescriptions Row -->
                    <div class="row g-4 animate-slide-up delay-2">
                        <div class="col-md-6">
                            <div class="card card-saas h-100 border-top border-4 border-primary">
                                <div class="card-body p-4">
                                     <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h6 class="fw-bold mb-0 text-dark"><i class="fa-solid fa-vial-circle-check text-primary me-2"></i> التحاليل الطبية</h6>
                                        <button class="btn btn-sm btn-light text-primary" data-bs-toggle="modal" data-bs-target="#smartUploadModal"><i class="fa-solid fa-upload"></i> تحليل ذكي</button>
                                    </div>
                                    <div class="d-flex flex-column gap-2 mt-3">
                                        <?php if(empty($labs)): ?>
                                            <p class="text-muted small">لا توجد سجلات.</p>
                                        <?php else: ?>
                                            <?php foreach(array_slice($labs, 0, 4) as $l): ?>
                                                <div class="d-flex justify-content-between align-items-center p-2 bg-light rounded-3">
                                                    <div>
                                                        <span class="d-block fw-bold text-dark fs-7"><?= htmlspecialchars($l->test_name) ?></span>
                                                        <span class="small text-muted"><?= date('M d', strtotime($l->test_date)) ?></span>
                                                    </div>
                                                    <span class="badge <?= $l->is_abnormal ? 'bg-danger-subtle text-danger' : 'bg-success-subtle text-success' ?> fs-7"><?= htmlspecialchars($l->result_value) ?></span>
                                                </div>
                                            <?php endforeach; ?>
                                            <a href="?tab=labs" class="btn btn-sm btn-light w-100 fw-bold mt-2 text-primary">عرض كل التحاليل <i class="fa-solid fa-arrow-left ms-1"></i></a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                             <div class="card card-saas h-100 border-top border-4 border-info">
                                <div class="card-body p-4">
                                     <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h6 class="fw-bold mb-0 text-dark"><i class="fa-solid fa-file-prescription text-info me-2"></i> الروشتات (Rx)</h6>
                                        <button class="btn btn-sm btn-light text-info" data-bs-toggle="modal" data-bs-target="#addPrescriptionModal"><i class="fa-solid fa-plus"></i> إضافة</button>
                                    </div>
                                    <div class="d-flex flex-column gap-2 mt-3">
                                        <?php if(empty($prescriptions)): ?>
                                            <p class="text-muted small">لا توجد روشتات مسجلة.</p>
                                        <?php else: ?>
                                            <?php foreach(array_slice($prescriptions, 0, 4) as $rx): ?>
                                                <div class="d-flex justify-content-between align-items-center p-2 bg-light rounded-3">
                                                    <div>
                                                        <span class="d-block fw-bold text-dark fs-7"><i class="fa-solid fa-user-doctor me-1 text-muted"></i> <?= htmlspecialchars($rx->doctor_type) ?></span>
                                                        <span class="small text-muted"><?= date('M d, Y', strtotime($rx->visit_date)) ?></span>
                                                    </div>
                                                    <a href="<?= BASE_URL ?>/health/prescriptionDetail/<?= $rx->id ?>" class="btn btn-sm btn-info text-white px-2 py-0 fs-7">التفاصيل</a>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- TAB 2: NUTRITION & FASTING -->
                <div class="tab-pane fade <?= $activeTab=='nutrition'?'show active':'' ?>" id="nutrition">
                    <div class="row g-4">
                        <!-- Fasting Engine -->
                        <div class="col-md-6 animate-slide-up delay-1">
                            <div class="card card-saas fasting-engine-ui p-4 h-100 text-center shadow">
                                <h5 class="fw-bold mb-4 text-success"><i class="fa-solid fa-fire me-2"></i> محرك الصيام الذكي</h5>
                                <?php if($hasActiveFast): ?>
                                    <div class="fast-arc-container mb-4 <?= $hasActiveFast ? 'fasting-active-pulse rounded-circle' : '' ?>">
                                        <svg width="220" height="220" viewBox="0 0 36 36">
                                            <path class="vitality-ring-bg" stroke="#e0f2fe" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                                            <path id="fastProgressCircle" class="vitality-ring" stroke="#10b981" stroke-dasharray="0, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                                        </svg>
                                        <div class="fast-timer-text">
                                            <div id="fastElapsed" class="display-5 fw-bold text-dark lh-1" style="font-family: monospace;">00:00:00</div>
                                            <span class="text-secondary small fw-bold d-block mt-1" id="fastProgressText">0% مكتمل</span>
                                        </div>
                                        <div id="fastStageBadge" class="fast-stage-badge">جاري الحساب...</div>
                                    </div>
                                    <p class="text-muted fw-bold small">البروتوكول: <?= $fastPlanHours ?> ساعة</p>
                                    <form id="fastToggleForm" onsubmit="event.preventDefault(); toggleFasting(this);">
                                        <?= csrf_field() ?>
                                        <button type="submit" class="btn btn-danger btn-premium w-100 mt-2 shadow-sm"><i class="fa-solid fa-utensils me-2"></i> إنهاء الصيام الآن</button>
                                    </form>
                                <?php else: ?>
                                    <div class="py-5">
                                        <i class="fa-solid fa-mug-hot fa-4x text-muted opacity-25 mb-3"></i>
                                        <h4 class="fw-bold mb-2">في نافذة الإفطار</h4>
                                        <p class="text-secondary small mb-4">أنت حالياً لا تصوم. قم ببدء الدورة من هنا.</p>
                                        
                                        <form id="fastToggleForm" class="text-start" onsubmit="event.preventDefault(); toggleFasting(this);">
                                            <?= csrf_field() ?>
                                            <div class="input-group mb-3 shadow-sm">
                                                <span class="input-group-text bg-white border-0 fw-bold"><i class="fa-solid fa-clock text-primary me-2"></i></span>
                                                <select name="plan_hours" class="form-select border-0 fw-bold text-dark">
                                                    <option value="12" <?= $profile->fasting_plan==12 ? 'selected':'' ?>>12 ساعة (مبتدئ)</option>
                                                    <option value="16" <?= $profile->fasting_plan==16 ? 'selected':'' ?>>16:8 (المعياري)</option>
                                                    <option value="18" <?= $profile->fasting_plan==18 ? 'selected':'' ?>>18:6 (متقدم)</option>
                                                    <option value="20" <?= $profile->fasting_plan==20 ? 'selected':'' ?>>20:4 (المحارب)</option>
                                                    <option value="24" <?= $profile->fasting_plan==24 ? 'selected':'' ?>>24h OMAD</option>
                                                </select>
                                            </div>
                                            <input type="hidden" name="start_date" value="<?= date('Y-m-d') ?>">
                                            <input type="hidden" name="start_time" value="<?= date('H:i') ?>">
                                            <button type="submit" class="btn btn-success btn-premium w-100 shadow-sm"><i class="fa-solid fa-play me-2"></i> إطلاق الصيام</button>
                                        </form>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Meals & Water -->
                        <div class="col-md-6 animate-slide-up delay-2">
                            <!-- Water tracker -->
                            <div class="card card-saas mb-4 p-3 bg-info-subtle border-0">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <h6 class="fw-bold text-info mb-0"><i class="fa-solid fa-droplet me-2"></i> تتبع الترطيب</h6>
                                    <span class="badge bg-white text-info fw-bold"><span id="waterCupsDisplay"><?= $waterCups ?></span> / <?= $profile->water_goal ?? 8 ?> أكواب</span>
                                </div>
                                <div class="progress bg-white rounded-pill shadow-sm mb-3" style="height: 10px;">
                                    <?php $wPercent = min(100, ($waterCups / max(1, $profile->water_goal ?? 8)) * 100); ?>
                                    <div class="progress-bar bg-info" id="waterProgress" style="width: <?= $wPercent ?>%"></div>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <button class="btn btn-sm btn-outline-info rounded-pill fw-bold px-3" onclick="logWater(this, false, <?= $profile->water_goal ?? 8 ?>)"><i class="fa-solid fa-plus me-1"></i> إضافة كوب</button>
                                    <button class="btn btn-sm btn-link text-muted text-decoration-none" onclick="logWater(null, true, <?= $profile->water_goal ?? 8 ?>)"><i class="fa-solid fa-rotate-left"></i> تراجع</button>
                                </div>
                            </div>

                            <!-- Meals -->
                            <div class="card card-saas h-100">
                                <div class="card-body p-4">
                                     <div class="d-flex justify-content-between align-items-center mb-4">
                                        <h6 class="fw-bold mb-0 text-dark"><i class="fa-solid fa-plate-wheat text-warning me-2"></i> الوجبات الغذائية</h6>
                                        <button class="btn btn-sm btn-outline-warning text-dark fw-bold rounded-pill" data-bs-toggle="modal" data-bs-target="#addMealModal"><i class="fa-solid fa-plus"></i></button>
                                    </div>
                                    <div class="timeline mt-3">
                                        <?php if(empty($meals)): ?>
                                            <div class="text-center text-muted small"><i class="fa-solid fa-utensils d-block fs-3 mb-2 opacity-50"></i> لم يتم تسجيل وجبات.</div>
                                        <?php else: ?>
                                            <?php foreach($meals as $m): ?>
                                                <div class="d-flex mb-3 align-items-center p-2 rounded-3 bg-light shadow-sm">
                                                    <div class="bg-warning-subtle text-warning p-2 rounded-circle me-3"><i class="fa-solid fa-bowl-food px-1"></i></div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="fw-bold text-dark mb-0 fs-7 d-flex justify-content-between">
                                                            <span><?= htmlspecialchars($m->meal_type) ?> <?php if($m->feeling) echo "<span class='badge bg-white text-muted fw-normal ms-1'>{$m->feeling}</span>"; ?></span>
                                                            <span class="small text-muted fw-normal"><?= date('h:ia', strtotime($m->eaten_at)) ?></span>
                                                        </h6>
                                                        <span class="small text-secondary fw-semibold"><?= htmlspecialchars($m->description) ?></span>
                                                    </div>
                                                    <a href="<?= BASE_URL ?>/health/delete/health_meals/<?= $m->id ?>" class="ms-3 text-danger opacity-50 hover-opacity-100"><i class="fa-solid fa-trash fs-7"></i></a>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- TAB 3: VITALITY & SYMPTOMS -->
                <div class="tab-pane fade <?= $activeTab=='vitality'?'show active':'' ?>" id="vitality">
                     <div class="row g-4">
                        <!-- Weight & Sugar -->
                        <div class="col-md-6 animate-slide-up delay-1">
                             <div class="card card-saas h-100 p-4">
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <h6 class="fw-bold mb-0 text-dark"><i class="fa-solid fa-scale-balanced text-primary me-2"></i> تطور الوزن</h6>
                                    <button class="btn btn-sm btn-outline-primary fw-bold" data-bs-toggle="modal" data-bs-target="#addWeightModal"><i class="fa-solid fa-plus ms-1"></i> تحديث</button>
                                </div>
                                <div style="height: 150px; position: relative;">
                                    <canvas id="weightChart"></canvas>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6 animate-slide-up delay-2">
                            <div class="card card-saas h-100 p-4">
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <h6 class="fw-bold mb-0 text-dark"><i class="fa-solid fa-droplet text-danger me-2"></i> قراءات السكر</h6>
                                    <button class="btn btn-sm btn-outline-danger fw-bold" data-bs-toggle="modal" data-bs-target="#addSugarModal"><i class="fa-solid fa-plus ms-1"></i> قياس</button>
                                </div>
                                <div class="d-flex flex-column gap-2 overflow-auto" style="max-height: 150px;">
                                    <?php if(empty($bloodSugars)) echo "<p class='text-muted small text-center mt-3'>لا توجد قراءات حديثة</p>"; ?>
                                    <?php foreach($bloodSugars as $bs): 
                                        $val = $bs->level;
                                        $color = ($val >= 140 || $val < 70) ? 'danger' : (($val >= 100) ? 'warning' : 'success');
                                    ?>
                                    <div class="d-flex justify-content-between align-items-center p-2 rounded-3 bg-light">
                                        <div><span class="text-<?= $color ?> fw-bold fs-6"><?= $val ?> mg/dl</span> <span class="small text-muted ms-2 px-1 text-decoration-underline"><?= $bs->is_after_meal ? 'بعد الأكل' : 'صائم' ?></span></div>
                                        <span class="small text-muted"><?= date('M d', strtotime($bs->date)) ?></span>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Active Symptoms -->
                        <div class="col-12 animate-slide-up delay-3">
                             <div class="card card-saas p-4 border-end border-4 border-danger">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6 class="fw-bold mb-0 text-dark"><i class="fa-solid fa-shield-virus text-danger me-2"></i> تتبع الأعراض</h6>
                                    <button class="btn btn-sm btn-outline-dark fw-bold rounded-pill" data-bs-toggle="modal" data-bs-target="#addSymptomModal"><i class="fa-solid fa-plus me-1"></i></button>
                                </div>
                                <?php 
                                    $activeSymptoms = array_filter($symptoms, fn($s) => is_null($s->end_date));
                                ?>
                                <?php if(empty($activeSymptoms)): ?>
                                    <div class="text-success small fw-bold bg-success-subtle p-2 rounded-3 text-center"><i class="fa-solid fa-circle-check me-1"></i> لا توجد أعراض نشطة. صحتك جيدة!</div>
                                <?php else: ?>
                                    <div class="row g-3">
                                        <?php foreach($activeSymptoms as $sym): ?>
                                            <div class="col-md-6">
                                                <div class="p-3 bg-light rounded-4 shadow-sm h-100 position-relative">
                                                    <h6 class="fw-bold text-dark fs-6"><?= htmlspecialchars($sym->symptom_name) ?> <span class="badge bg-danger-subtle text-danger ms-2"><?= $sym->severity ?>/10</span></h6>
                                                    <p class="small text-secondary fw-semibold mb-3">مستمر منذ: <?= date('M d', strtotime($sym->start_date)) ?></p>
                                                    <div class="d-flex justify-content-between border-top pt-2">
                                                        <form action="<?= BASE_URL ?>/health/recoverSymptom" method="POST">
                                                            <?= csrf_field() ?>
                                                            <input type="hidden" name="id" value="<?= $sym->id ?>">
                                                            <button type="submit" class="btn btn-sm btn-link text-success text-decoration-none fw-bold p-0"><i class="fa-solid fa-check"></i> تعافيت</button>
                                                        </form>
                                                        <a href="<?= BASE_URL ?>/health/delete/health_symptoms_log/<?= $sym->id ?>" class="text-danger small opacity-50"><i class="fa-solid fa-trash"></i></a>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                    </div>
                </div>

            </div>
        </div>

        <!-- RIGHT SIDEBAR (Insights & Timeline) -->
        <div class="col-xl-4 animate-slide-up delay-2">
            
            <!-- Contextual Actions -->
            <?php if(!empty($vitality['actions'])): ?>
                <?php foreach($vitality['actions'] as $action): 
                    $color = $action['priority'] == 'critical' ? 'danger' : ($action['priority'] == 'high' ? 'warning' : 'primary');
                ?>
                <div class="card card-saas mb-3 bg-<?= $color ?>-subtle border-0">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <i class="fa-solid fa-bell text-<?= $color ?> fs-4"></i>
                        <span class="fw-bold text-dark small"><?= htmlspecialchars($action['text']) ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>

            <!-- Smart Insights Core -->
            <div class="card card-saas border-0 bg-dark text-white shadow mb-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-info mb-3"><i class="fa-solid fa-brain me-2"></i> الذكاء المدمج (Insights)</h6>
                    <div class="d-flex flex-column gap-2 text-white-50 small fw-semibold">
                        <?php if(!empty($smartInsights)): ?>
                            <div class="pb-2 border-bottom border-secondary border-opacity-25"><i class="fa-solid fa-vial text-warning me-2"></i> <?= $smartInsights ?></div>
                        <?php endif; ?>
                        <?php if(!empty($vitalityTrends)): foreach($vitalityTrends as $trend): ?>
                            <div class="pb-2 border-bottom border-secondary border-opacity-25"><i class="fa-solid fa-arrow-trend-up text-primary me-2"></i> <?= htmlspecialchars($trend['text']) ?></div>
                        <?php endforeach; endif; ?>
                        <?php if(empty($smartInsights) && empty($vitalityTrends)): ?>
                            <p class="mb-0 text-center text-muted">قم بإدخال بيانات (تحاليل، يوميات) لتوليد رؤى تنبؤية متقدمة.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Unified Health Timeline -->
            <div class="card card-saas mb-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark mb-4 border-bottom pb-3"><i class="fa-solid fa-clock-rotate-left mr-2 text-secondary"></i> السجل الزمني الجسدي (اليوم)</h6>
                    <div class="px-2" style="max-height: 480px; overflow-y:auto; padding-right:10px;">
                        <?php if(empty($unifiedTimeline)): ?>
                            <div class="text-center py-5 text-muted small"><i class="fa-solid fa-file-waveform d-block fs-3 mb-2 opacity-25"></i>لا يوجد أحداث جسدية مسجلة اليوم.</div>
                        <?php else: ?>
                            <?php foreach($unifiedTimeline as $event): 
                                $tClass = 't-lab';
                                if($event['type'] == 'meal') $tClass = 't-meal';
                                if($event['type'] == 'fast') $tClass = 't-fast';
                                if($event['type'] == 'sugar') $tClass = 't-med';
                            ?>
                            <div class="timeline-item <?= $tClass ?>">
                                <div class="d-flex justify-content-between">
                                    <h6 class="fw-bold text-dark mb-1 fs-7"><?= htmlspecialchars($event['title']) ?></h6>
                                    <span class="small text-muted fw-bold"><?= date('h:i A', strtotime($event['time'])) ?></span>
                                </div>
                                <span class="text-secondary small fw-semibold"><?= htmlspecialchars($event['description']) ?></span>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

</div>

<!-- ================= MODALS INCLUDE ================= -->

<!-- Profile Modal -->
<div class="modal fade" id="profileModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">الإعدادات الصحية (التكوين)</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="<?= BASE_URL ?>/health/storeProfile" method="POST">
                    <?= csrf_field() ?>
                    <div class="row g-3">
                        <div class="col-6"><label>العمر</label><input type="number" name="age" class="form-control" value="<?= $profile->age ?? '' ?>"></div>
                        <div class="col-6"><label>الطول (cm)</label><input type="number" name="height" class="form-control" value="<?= $profile->height ?? '' ?>"></div>
                        <div class="col-6"><label>الوزن الحالي</label><input type="number" step="0.1" name="current_weight" class="form-control" value="<?= $profile->current_weight ?? '' ?>"></div>
                        <div class="col-6"><label>الوزن المستهدف</label><input type="number" step="0.1" name="target_weight" class="form-control" value="<?= $profile->target_weight ?? '' ?>"></div>
                        <div class="col-6">
                            <label>فصيلة الدم</label>
                            <select name="blood_type" class="form-select">
                                <option value="A+" <?= ($profile->blood_type??'')=='A+'?'selected':'' ?>>A+</option>
                                <option value="A-" <?= ($profile->blood_type??'')=='A-'?'selected':'' ?>>A-</option>
                                <option value="B+" <?= ($profile->blood_type??'')=='B+'?'selected':'' ?>>B+</option>
                                <option value="B-" <?= ($profile->blood_type??'')=='B-'?'selected':'' ?>>B-</option>
                                <option value="O+" <?= ($profile->blood_type??'')=='O+'?'selected':'' ?>>O+</option>
                                <option value="O-" <?= ($profile->blood_type??'')=='O-'?'selected':'' ?>>O-</option>
                                <option value="AB+" <?= ($profile->blood_type??'')=='AB+'?'selected':'' ?>>AB+</option>
                                <option value="AB-" <?= ($profile->blood_type??'')=='AB-'?'selected':'' ?>>AB-</option>
                            </select>
                        </div>
                        <div class="col-6"><label>هدف الماء (أكواب)</label><input type="number" name="water_goal" class="form-control" value="<?= $profile->water_goal ?? 8 ?>"></div>
                        <div class="col-12"><label>بروتوكول الصيام (ساعات)</label><input type="number" name="fasting_plan" class="form-control" value="<?= $profile->fasting_plan ?? 16 ?>"></div>
                        <div class="col-12"><label>الأمراض / التاريخ الطبي</label><textarea name="diseases" class="form-control"><?= $profile->diseases ?? '' ?></textarea></div>
                    </div>
                    <button type="submit" class="btn btn-primary w-100 mt-4 rounded-pill fw-bold">حفظ التكوين</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Add Meal Modal -->
<div class="modal fade" id="addMealModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-warning"><i class="fa-solid fa-utensils me-2"></i> توثيق وجبة أو سناك</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="<?= BASE_URL ?>/health/storeMeal" method="POST">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label>نوع الوجبة</label>
                        <select name="meal_type" class="form-select">
                            <option value="إفطار">إفطار</option>
                            <option value="غداء">غداء</option>
                            <option value="عشاء">عشاء</option>
                            <option value="سناك">سناك سريع</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label>وصف الوجبة / الأصناف</label>
                        <input type="text" name="custom_meal" class="form-control" placeholder="مثال: دجاج مشوي مع سلطة خضراء" required>
                    </div>
                    <div class="mb-3">
                        <label>الشعور بعد الوجبة (اختياري)</label>
                        <input type="text" name="feeling" class="form-control" placeholder="مثال: شبع، ثقل، نشاط">
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="broke_fast" value="1" id="broke_fast_check">
                        <label class="form-check-label fw-bold opacity-75" for="broke_fast_check">الوجبة كسرت الصيام</label>
                    </div>
                    <button type="submit" class="btn btn-warning text-dark w-100 fw-bold rounded-pill">توثيق الأن</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Add Symptom Modal -->
<div class="modal fade" id="addSymptomModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-danger"><i class="fa-solid fa-head-side-cough me-2"></i> تسجيل عرض صحي جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="<?= BASE_URL ?>/health/storeSymptom" method="POST">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label>وصف العرض / المرض</label>
                        <input type="text" name="symptom_name" class="form-control" placeholder="مثال: صداع نصفي قوي، ألم في الظهر..." required>
                    </div>
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-1">
                            <label>شدة الألم (1 إلى 10)</label>
                            <span class="badge bg-danger fs-6" id="sevValue">5</span>
                        </div>
                        <input type="range" name="severity" class="form-range" min="1" max="10" value="5" oninput="document.getElementById('sevValue').innerText = this.value">
                    </div>
                    <div class="mb-3">
                        <label>تاريخ الشعور بالعرض</label>
                        <input type="date" name="start_date" class="form-control" value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="mb-3">
                        <label>ملاحظات إضافية (أين، متى بدأ، إلخ)</label>
                        <textarea name="notes" class="form-control" rows="2"></textarea>
                    </div>
                    <button type="submit" class="btn btn-danger w-100 fw-bold rounded-pill">تسجيل للمتابعة</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Smart OCR Upload Modal -->
<div class="modal fade" id="smartUploadModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-primary"><i class="fa-solid fa-microchip me-2"></i> تحليل طبي ذكي (OCR)</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4 text-center">
                 <i class="fa-solid fa-file-pdf text-primary display-3 opacity-75 mb-3"></i>
                <p class="text-muted fw-bold">قم برفع ورقة التحليل (PDF/Image) وسيقوم النظام باستخراج وفهم القراءات تلقائياً.</p>
                <form id="ocrForm" onsubmit="event.preventDefault(); submitOCR(this);">
                    <input type="file" name="lab_file" class="form-control mb-3" accept=".pdf,image/*" required>
                    <button type="submit" class="btn btn-primary w-100 fw-bold rounded-pill shadow-sm" id="ocrBtn"><i class="fa-solid fa-cloud-arrow-up me-2"></i> رفع واستخراج ذكي</button>
                    <div id="ocrResult" class="mt-3 text-start small fw-bold"></div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Add Prescription Modal -->
<div class="modal fade" id="addPrescriptionModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-info"><i class="fa-solid fa-file-prescription me-2"></i> إضافة روشتة طبية جديدة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="<?= BASE_URL ?>/health/storePrescription" method="POST">
                    <?= csrf_field() ?>
                    <div class="row g-3">
                        <div class="col-md-6"><label>تخصص الطبيب / الاسم</label><input type="text" name="doctor_type" class="form-control" required placeholder="مثال: باطنة - د. أحمد"></div>
                        <div class="col-md-6"><label>العيادة / المستشفى</label><input type="text" name="clinic_name" class="form-control" placeholder="اسم المستشفى"></div>
                        <div class="col-md-6"><label>تاريخ الكشف</label><input type="date" name="visit_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
                        <div class="col-md-6"><label>التشخيص / ملاحظات</label><textarea name="notes" class="form-control" rows="1" placeholder="أهم تعليمات الطبيب..."></textarea></div>
                    </div>
                    
                    <hr class="my-3 opacity-25">
                    <h6 class="fw-bold mb-3 text-primary"><i class="fa-solid fa-capsules me-2"></i> الأدوية الموصوفة</h6>
                    <div id="medsContainer">
                        <div class="row g-2 mb-2 med-item bg-light p-2 rounded-3 align-items-center border">
                            <div class="col-md-4"><input type="text" name="med_name[]" class="form-control form-control-sm" placeholder="اسم الدواء"></div>
                            <div class="col-md-3"><input type="text" name="med_dose[]" class="form-control form-control-sm" placeholder="التركيز/الجرعة"></div>
                            <div class="col-md-4"><input type="text" name="med_freq[]" class="form-control form-control-sm" placeholder="التكرار (مثال: مرتين يومياً)"></div>
                            <div class="col-md-1"><button type="button" class="btn btn-sm btn-outline-danger w-100" onclick="this.closest('.med-item').remove()"><i class="fa-solid fa-times"></i></button></div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm btn-light fw-bold text-primary mb-4" onclick="addMedRow()"><i class="fa-solid fa-plus me-1"></i> إضافة دواء آخر بالقائمة</button>
                    <button type="submit" class="btn btn-info text-white w-100 fw-bold rounded-pill">حفظ الروشتة والأدوية</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Add Medication Manual Modal -->
<div class="modal fade" id="addMedModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-primary"><i class="fa-solid fa-pills me-2"></i> إضافة علاج أو مكمل للجدول</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="<?= BASE_URL ?>/health/storeMedication" method="POST">
                    <?= csrf_field() ?>
                    <div class="mb-3"><label>اسم الدواء / المكمل</label><input type="text" name="med_name" class="form-control" required placeholder="مثال: فيتامين د3"></div>
                    <div class="mb-3"><label>الجرعة والتركيز</label><input type="text" name="dose" class="form-control" placeholder="مثال: 5000 IU" required></div>
                    <div class="mb-3"><label>التكرار وطريقة الأخذ</label><input type="text" name="frequency" class="form-control" placeholder="مثال: حبة واحدة أسبوعياً مع وجبة دسمة" required></div>
                    <button type="submit" class="btn btn-primary w-100 fw-bold rounded-pill">أضف لجدول الأدوية</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Add Weight Modal -->
<div class="modal fade" id="addWeightModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-primary"><i class="fa-solid fa-scale-balanced me-2"></i> تحديث قراءة الوزن</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="<?= BASE_URL ?>/health/storeWeight" method="POST">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label>الوزن بالكيلوجرام (kg)</label>
                        <input type="number" step="0.1" name="weight" class="form-control form-control-lg text-center fw-bold fs-4" value="<?= $profile->current_weight ?? '' ?>" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100 fw-bold rounded-pill">حفظ</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Add Sugar Modal -->
<div class="modal fade" id="addSugarModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-danger"><i class="fa-solid fa-droplet me-2"></i> قياس السكر الدم</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="<?= BASE_URL ?>/health/storeBloodSugar" method="POST">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label>نوع القياس</label>
                        <select name="measurement_type" class="form-select fw-bold">
                            <option value="first">القياس الأول (صباحاً/صائم)</option>
                            <option value="second">القياس الثاني</option>
                            <option value="third">القياس الثالث</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label>النسبة (mg/dL)</label>
                        <input type="number" name="level" class="form-control form-control-lg text-center text-danger fw-bold fs-3" placeholder="---" required>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input border-danger" type="checkbox" name="is_after_meal" value="1" id="sugarAfterMeal">
                        <label class="form-check-label fw-bold text-danger opacity-75" for="sugarAfterMeal">القياس كان بعد الأكل (فاطر)</label>
                    </div>
                    <button type="submit" class="btn btn-outline-danger w-100 fw-bold rounded-pill">أرشفة القياس</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Javascript Addons for Modals -->
<script>
function addMedRow() {
    const html = `<div class="row g-2 mb-2 med-item bg-light p-2 rounded-3 align-items-center border">
        <div class="col-md-4"><input type="text" name="med_name[]" class="form-control form-control-sm" placeholder="اسم الدواء"></div>
        <div class="col-md-3"><input type="text" name="med_dose[]" class="form-control form-control-sm" placeholder="التركيز/الجرعة"></div>
        <div class="col-md-4"><input type="text" name="med_freq[]" class="form-control form-control-sm" placeholder="التكرار (مثال: مرتين يومياً)"></div>
        <div class="col-md-1"><button type="button" class="btn btn-sm btn-outline-danger w-100" onclick="this.closest('.med-item').remove()"><i class="fa-solid fa-times"></i></button></div>
    </div>`;
    document.getElementById('medsContainer').insertAdjacentHTML('beforeend', html);
}

async function submitOCR(form) {
    const btn = document.getElementById('ocrBtn');
    const resDiv = document.getElementById('ocrResult');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> جاري استخراج البيانات... برجاء الانتظار';
    resDiv.innerHTML = '';
    try {
        const formData = new FormData(form);
        const res = await fetch("<?= BASE_URL ?>/health/uploadLabDocument", { method: 'POST', body: formData });
        const data = await res.json();
        
        if (data.success && data.data && data.data.tests) {
            resDiv.innerHTML = '<span class="text-success"><i class="fa-solid fa-check w-10"></i> تم الاستخراج بنجاح! جاري الدمج والأرشفة...</span>';
            
            // Auto submit to storeParsedLabs
            const saveRes = await fetch("<?= BASE_URL ?>/health/storeParsedLabs", {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ tests: data.data.tests, uploaded_file: data.uploaded_file })
            });
            const saveData = await saveRes.json();
            if (saveData.success) {
                location.href = saveData.redirect;
            } else {
                resDiv.innerHTML = `<span class="text-danger"><i class="fa-solid fa-triangle-exclamation"></i> خطأ بالدمج: ${saveData.error}</span>`;
            }
        } else {
            resDiv.innerHTML = `<span class="text-danger"><i class="fa-solid fa-triangle-exclamation"></i> ${data.error || 'فشل الاستخراج'}</span>`;
        }
    } catch(e) {
        resDiv.innerHTML = '<span class="text-danger"><i class="fa-solid fa-triangle-exclamation"></i> حدث خطأ في الاتصال بالخدمة الذكية.</span>';
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="fa-solid fa-cloud-arrow-up me-2"></i> رفع واستخراج ذكي';
    }
}
</script>

<!-- SCRIPTS -->
<script>
// Weight Chart
const ctz = document.getElementById('weightChart');
if(ctz && <?= !empty($weightData) ? 'true' : 'false' ?>) {
    new Chart(ctz.getContext('2d'), {
        type: 'line',
        data: {
            labels: <?= json_encode($weightLabels) ?>,
            datasets: [{ label: 'الوزن', data: <?= json_encode($weightData) ?>, borderColor: '#0d6efd', backgroundColor: 'rgba(13, 110, 253, 0.1)', borderWidth: 3, tension: 0.4, fill: true, pointRadius: 4 }]
        },
        options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { display: false }, x: { display: false } } }
    });
}

// Interactive Fasting Engine
const hasActiveFast = <?= $hasActiveFast ? 'true' : 'false' ?>;
const fastStartStr = "<?= $fastStartJs ?>";
const planHours = <?= $fastPlanHours ?>;

if (hasActiveFast && fastStartStr) {
    const startTime = new Date(fastStartStr).getTime();
    const targetMs = planHours * 3600 * 1000;
    
    function updateFasting() {
        const now = new Date().getTime();
        const diffMs = now - startTime;
        
        // Time logic
        let h = Math.floor(diffMs / (1000 * 60 * 60));
        let m = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
        let s = Math.floor((diffMs % (1000 * 60)) / 1000);
        
        document.getElementById('fastElapsed').innerText = 
            `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
        
        // Progress logic
        let percent = Math.min(100, (diffMs / targetMs) * 100);
        document.getElementById('fastProgressCircle').style.strokeDasharray = `${percent}, 100`;
        document.getElementById('fastProgressText').innerText = `${Math.floor(percent)}% مكتمل من 목표 (${planHours}س)`;
        
        // Stage logic (Fasting Stages)
        let stageText = "انخفاض سكر الدم";
        let stageColor = "#3b82f6"; // blue
        if (h >= 16) { stageText = "الالتهام الذاتي (Autophagy) نشط!"; stageColor = "#8b5cf6"; }
        else if (h >= 12) { stageText = "حرق الدهون (Ketosis)"; stageColor = "#10b981"; }
        else if (h >= 4) { stageText = "هضم وراحة"; stageColor = "#f59e0b"; }

        const badge = document.getElementById('fastStageBadge');
        if(percent >= 100) { stageText = "اكتمل الهدف🔥"; stageColor = "#ef4444"; }
        
        badge.innerText = stageText;
        badge.style.color = stageColor;
        badge.style.borderColor = stageColor + '40'; // opacity
    }
    
    updateFasting();
    setInterval(updateFasting, 1000);
}

// Standard OTIS Ajax overrides for buttons
async function takeMed(id, el, isTaken = false) {
    el.disabled = true;
    const res = await OTIS.post('/health/takeMedication/' + id, { undo: isTaken });
    if(res.success) {
        if(!isTaken) {
            el.closest('.med-row-container').classList.add('bg-success-subtle', 'opacity-75');
            el.closest('.med-row-container').classList.remove('bg-light');
            el.nextElementSibling.querySelector('h6').classList.add('text-decoration-line-through', 'text-success');
            el.setAttribute('onclick', `takeMed(${id}, this, true)`);
            el.checked = true;
        } else {
            el.closest('.med-row-container').classList.remove('bg-success-subtle', 'opacity-75');
            el.closest('.med-row-container').classList.add('bg-light');
            el.nextElementSibling.querySelector('h6').classList.remove('text-decoration-line-through', 'text-success');
            el.setAttribute('onclick', `takeMed(${id}, this, false)`);
            el.checked = false;
        }
    }
    el.disabled = false;
}

async function logWater(btn, undo = false, totalGoal = 8) {
    if(btn) btn.disabled = true;
    const res = await OTIS.post('/health/logWater', { undo: undo });
    if(res.success) {
        let span = document.getElementById('waterCupsDisplay');
        let c = parseInt(span.innerText);
        if(!undo) c++; else if(c>0) c--;
        span.innerText = c;
        
        let pct = Math.min(100, (c / totalGoal) * 100);
        document.getElementById('waterProgress').style.width = pct + '%';
    }
    if(btn) btn.disabled = false;
}

async function toggleFasting(form) {
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    const res = await OTIS.post('/health/toggleFast', data);
    if(res.success) location.reload();
}
</script>
