<?php
namespace App\Modules\Health\Controllers;

class HealthController extends \Core\Controller {
    


    public function index() {
        $model = $this->model('Health/Models/HealthModel');
        $activeTab = isset($_GET['tab']) ? sanitize_input($_GET['tab']) : 'vitality'; // Default to vitality

        $profile = $model->getProfile($this->userId);
        if (!$profile) {
            // Failsafe initialization
            $model->query("INSERT IGNORE INTO health_profile (user_id) VALUES (?)", [$this->userId]);
            $profile = $model->getProfile($this->userId);
        }

        $model->expireOldPrescriptionMeds($this->userId); // Auto-expire daily

        // Core Data
        $weights = $model->getWeightLogs($this->userId);
        $bloodSugars = $model->getBloodSugar($this->userId);
        $activeFast = $model->getActiveFast($this->userId);
        $recentFasts = $model->getRecentFasts($this->userId);
        $meals = $model->getTodayMeals($this->userId);
        $medications = $model->getMedications($this->userId);
        $takenMeds = $model->getTodayTakenMeds($this->userId);
        $waterCups = $model->getTodayWater($this->userId);
        $activities = $model->getTodayActivities($this->userId);

        // Labs
        $labDateFrom = isset($_GET['lab_from']) ? sanitize_input($_GET['lab_from']) : null;
        $labDateTo   = isset($_GET['lab_to'])   ? sanitize_input($_GET['lab_to'])   : null;
        $labPage     = isset($_GET['lab_page']) ? (int)$_GET['lab_page'] : 1;
        $labsPaginated = $model->getLabs($this->userId, $labPage, 10, $labDateFrom, $labDateTo);
        $prescriptions = $model->getPrescriptions($this->userId);
        $symptoms = $model->getSymptoms($this->userId);
        $mealItems = $model->getMealItems();

        $latestInsight = $model->getLatestInsight($this->userId);
        $smartInsights = $latestInsight ? $latestInsight->insight_text : null;
        
        // Vitality Engine Integration
        require_once __DIR__ . '/../../../../core/Services/VitalityService.php';
        $vitalitySvc = new \Core\Services\VitalityService();
        $vitality = $vitalitySvc->calculateDailyVitality($this->userId);
        $unifiedTimeline = $vitalitySvc->generateUnifiedTimeline($this->userId);
        $vitalityTrends  = $vitalitySvc->getPredictiveInsights($this->userId);
        $vitalitySvc->syncGoalsToMonthlyPlan($this->userId);

        $this->view('Health/Views/dashboard', [
            'title'             => 'محرك الذكاء الحيوي | OTIS Life System',
            'activeTab'         => $activeTab,
            'profile'           => $profile,
            'weights'           => $weights,
            'bloodSugars'       => $bloodSugars,
            'activeFast'        => $activeFast,
            'recentFasts'       => $recentFasts,
            'meals'             => $meals,
            'medications'       => $medications,
            'takenMeds'         => $takenMeds,
            'waterCups'         => $waterCups,
            'activities'        => $activities,
            'labs'              => $labsPaginated['data'],
            'labsPagination'    => $labsPaginated['pagination'],
            'labDateFrom'       => $labDateFrom,
            'labDateTo'         => $labDateTo,
            'prescriptions'     => $prescriptions,
            'symptoms'          => $symptoms,
            'mealItems'         => $mealItems,
            'smartInsights'     => $smartInsights,
            'vitality'          => $vitality,
            'unifiedTimeline'   => $unifiedTimeline,
            'vitalityTrends'    => $vitalityTrends
        ]);
    }

    public function storeProfile() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $model = $this->model('Health/Models/HealthModel');
            
            $data = [
                'age' => get_secure_post('age'),
                'height' => get_secure_post('height'),
                'current_weight' => get_secure_post('current_weight'),
                'target_weight' => get_secure_post('target_weight'),
                'blood_type' => get_secure_post('blood_type'),
                'diseases' => get_secure_post('diseases'),
                'water_goal' => get_secure_post('water_goal'),
                'fasting_plan' => get_secure_post('fasting_plan')
            ];
            
            $model->updateProfile($this->userId, $data);
            set_flash_message('health', 'تم تحديث الملف الصحي بنجاح!', 'success');
            redirect('/health');
        }
    }

    public function storeWeight() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $this->model('Health/Models/HealthModel')->addWeight($this->userId, get_secure_post('weight'));
            set_flash_message('health', 'تم تسجيل الوزن بنجاح.', 'success');
            redirect('/health?tab=vitals');
        }
    }

    public function storeBloodSugar() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $meas_type = get_secure_post('measurement_type');
            $level = get_secure_post('level');
            $is_after_meal = isset($_POST['is_after_meal']) ? 1 : 0;
            $meal_id = $is_after_meal ? get_secure_post('meal_id') : null;
            if (!$meal_id) $is_after_meal = 0;

            $success = $this->model('Health/Models/HealthModel')->addBloodSugar($this->userId, $meas_type, $level, $is_after_meal, $meal_id);
            if ($success) {
                set_flash_message('health', 'تم تسجيل مستوى السكر بنجاح.', 'success');
            } else {
                $typeName = ($meas_type == 'first') ? 'القياس الأول' : (($meas_type == 'second') ? 'القياس الثاني' : 'القياس الثالث');
                set_flash_message('health', "عذراً، $typeName مسجل مسبقاً اليوم!", 'danger');
            }
            redirect('/health?tab=vitals');
        }
    }

    // --- Fasting ---
    public function toggleFast() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
            if (!$isAjax && isset($_POST['csrf_token'])) verify_csrf_token($_POST['csrf_token']);
            
            $input = $isAjax ? json_decode(file_get_contents('php://input'), true) : $_POST;

            $model = $this->model('Health/Models/HealthModel');
            $active = $model->getActiveFast($this->userId);
            
            if ($active) {
                $model->endFast($this->userId);
                if($isAjax) { echo json_encode(['success' => true, 'state' => 'ended']); exit; }
                set_flash_message('health', 'تم إنهاء الصيام. عمل رائع!', 'success');
            } else {
                $plan = $input['plan_hours'] ?? 16;
                $startDate = $input['start_date'] ?? date('Y-m-d');
                $startTime = $input['start_time'] ?? date('H:i:s');
                // Ensure time has seconds for DB
                if (strlen($startTime) == 5) $startTime .= ':00';
                $fullStart = $startDate . ' ' . $startTime;
                
                $model->startFast($this->userId, $plan, $fullStart);
                if($isAjax) { echo json_encode(['success' => true, 'state' => 'started']); exit; }
                set_flash_message('health', 'تم إطلاق متتبع الصيام. حافظ على تركيزك!', 'info');
            }
            redirect('/health?tab=fasting');
        }
    }

    public function storeMeal() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $brokeFast = isset($_POST['broke_fast']) ? 1 : 0;
            
            $items = $_POST['meal_items'] ?? [];
            $custom = trim($_POST['custom_meal'] ?? '');
            
            $description = '';
            if(!empty($items)) {
                $description = implode(' + ', $items);
            }
            if(!empty($custom)) {
                $description .= ($description ? ' + ' : '') . $custom;
            }
            
            $feeling = get_secure_post('feeling');

            $this->model('Health/Models/HealthModel')->addMeal(
                $this->userId, 
                get_secure_post('meal_type'), 
                $description ?: 'وجبة غير محددة',
                $feeling, 
                $brokeFast
            );
            set_flash_message('health', 'تم تسجيل الوجبة بنجاح.', 'success');
            redirect('/health?tab=fasting');
        }
    }

    // --- Water ---
    public function logWater() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
            $input = json_decode(file_get_contents('php://input'), true) ?? [];
            $undo = !empty($input['undo']);
            
            if($undo) {
                $this->model('Health/Models/HealthModel')->removeWater($this->userId, 1);
            } else {
                $this->model('Health/Models/HealthModel')->addWater($this->userId, 1);
            }
            
            if($isAjax) {
                echo json_encode(['success' => true, 'undo' => $undo]); exit;
            }
            
            verify_csrf_token($_POST['csrf_token']);
            redirect('/health?tab=meds');
        }
    }

    // --- Activity ---
    public function storeActivity() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $this->model('Health/Models/HealthModel')->addActivity(
                $this->userId, 
                get_secure_post('activity_type'), 
                get_secure_post('duration_minutes'), 
                get_secure_post('intensity')
            );
            set_flash_message('health', 'تم تسجيل النشاط الحركي!', 'success');
            redirect('/health?tab=goals'); // Activities tab might merge
        }
    }

    // --- Meds & Labs ---
    public function storeMedication() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $this->model('Health/Models/HealthModel')->addMedication(
                $this->userId, 
                get_secure_post('med_name'), 
                get_secure_post('dose'), 
                get_secure_post('frequency')
            );
            set_flash_message('health', 'تم إضافة العلاج بجدولك.', 'success');
            redirect('/health?tab=meds');
        }
    }

    public function takeMedication($medId) {
        $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
        $input = json_decode(file_get_contents('php://input'), true) ?? [];
        $undo = !empty($input['undo']);
        
        $model = $this->model('Health/Models/HealthModel');
        if($undo) {
            $model->unlogMedTaken($this->userId, $medId);
        } else {
            $model->logMedTaken($this->userId, $medId);
        }
        
        if($isAjax) {
            echo json_encode(['success' => true, 'undo' => $undo]); exit;
        }
        
        set_flash_message('health', 'تم إثبات تناول الجرعة!', 'success');
        redirect('/health?tab=meds');
    }

    public function storeLab() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $is_ab = isset($_POST['is_abnormal']) ? 1 : 0;
            
            $name = sanitize_input(get_secure_post('test_name'));
            $val = sanitize_input(get_secure_post('result_value'));
            $range = sanitize_input(get_secure_post('normal_range'));
            
            require_once __DIR__ . '/../../../../core/Services/LabAnalysisService.php';
            $analysisService = new \Core\Services\LabAnalysisService();
            $analysis = $analysisService->analyzeSingleTest($name, $val, $range, $is_ab);

            $model = $this->model('Health/Models/HealthModel');
            
            $historyRecords = $model->getLabHistory($this->userId, $name, 3);
            $historyList = array_map(function($h) { return is_object($h) ? $h->result_value : $h['result_value']; }, $historyRecords);
            $trendStatus = $analysisService->calculateTrend($val, $historyList);

            $model->addLab(
                $this->userId, 
                $name, 
                $val, 
                sanitize_input(get_secure_post('unit')), 
                $range, 
                $is_ab,
                $analysis['status'],
                $analysis['interpretation'],
                $analysis['recommendation'],
                $analysis['severity_level'],
                $trendStatus,
                $analysis['action_level'],
                $analysis['confidence_level']
            );

            // Regenerate Insight
            $allLabs = $model->getLabs($this->userId, 20);
            $abnormalLabs = array_filter($allLabs, function($l) { return $l->is_abnormal == 1; });
            $symptoms = $model->getSymptoms($this->userId);
            $activeSymptoms = array_filter($symptoms, function($s) { return is_null($s->end_date); });
            
            $historyMap = [];
            foreach($abnormalLabs as $abLab) {
                $lName = is_object($abLab) ? $abLab->test_name : $abLab['test_name'];
                if(!isset($historyMap[$lName])) {
                    $historyMap[$lName] = $model->getLabHistory($this->userId, $lName, 3);
                }
            }
            
            $insightObj = $analysisService->generateGroupInsight($abnormalLabs, $activeSymptoms, $historyMap);
            if ($insightObj) {
                $model->saveGroupInsight($this->userId, $insightObj['text'], $insightObj['priority_issue']);
            }

            set_flash_message('health', 'تم أرشفة نتيجة التحليل وتقييمها بذكاء.', 'success');
            redirect('/health?tab=labs');
        }
    }

    // goals logic removed as requested

    // --- Generic Soft Delete ---
    private function getTabByTable($table) {
        $map = [
            'health_weight_logs' => 'vitals',
            'health_blood_sugar' => 'vitals',
            'health_fasts' => 'fasting',
            'health_meals' => 'fasting',
            'health_medications' => 'meds',
            'health_med_logs' => 'meds',
            'health_water_logs' => 'meds',
            'health_activities' => 'goals',
            'health_goals' => 'goals',
            'health_labs' => 'labs',
            'health_symptoms_log' => 'symptoms'
        ];
        return $map[$table] ?? 'vitals';
    }

    public function delete($table, $id) {
        $model = $this->model('Health/Models/HealthModel');
        if($model->deleteItem($table, $id, $this->userId)) {
            set_flash_message('health', 'تم الحذف والأرشفة بنجاح.', 'success');
        } else {
            set_flash_message('health', 'حدث خطأ بالحذف.', 'danger');
        }
        redirect('/health?tab=' . $this->getTabByTable($table));
    }

    // --- Prescriptions ---
    public function storePrescription() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') redirect('/health?tab=prescriptions');
        verify_csrf_token($_POST['csrf_token'] ?? '');

        $model = $this->model('Health/Models/HealthModel');
        $data = [
            'doctor_type' => get_secure_post('doctor_type'),
            'clinic_name' => get_secure_post('clinic_name'),
            'visit_date'  => get_secure_post('visit_date') ?: date('Y-m-d'),
            'notes'       => get_secure_post('notes')
        ];

        $prescriptionId = $model->addPrescription($this->userId, $data);

        // Also add up to 5 medications from the form
        $names = $_POST['med_name'] ?? [];
        $doses = $_POST['med_dose'] ?? [];
        $freqs = $_POST['med_freq'] ?? [];
        $scheds = $_POST['med_schedule'] ?? [];
        $starts = $_POST['med_start'] ?? [];
        $ends   = $_POST['med_end'] ?? [];

        $medCount = 0;
        foreach ($names as $i => $name) {
            if (empty(trim($name))) continue;
            $model->addPrescriptionMedication($this->userId, $prescriptionId, [
                'med_name'   => sanitize_input($name),
                'dose'       => sanitize_input($doses[$i] ?? ''),
                'frequency'  => sanitize_input($freqs[$i] ?? ''),
                'schedule'   => sanitize_input($scheds[$i] ?? ''),
                'start_date' => $starts[$i] ?? date('Y-m-d'),
                'end_date'   => $ends[$i] ?: null
            ]);
            $medCount++;
        }

        set_flash_message('health', "تم حفظ الروشتة و {$medCount} دواء بنجاح!", 'success');
        redirect('/health?tab=prescriptions');
    }

    public function prescriptionDetail($id) {
        $model = $this->model('Health/Models/HealthModel');
        $prescription = $model->getPrescriptionById($id, $this->userId);
        if (!$prescription) { redirect('/health?tab=prescriptions'); }
        $meds = $model->getPrescriptionMeds($id, $this->userId);

        $this->view('Health/Views/prescription_detail', [
            'title'        => "\u0631\u0648\u0634\u062a\u0629 {$prescription->doctor_type} | OTIS",
            'prescription' => $prescription,
            'meds'         => $meds
        ]);
    }

    public function deletePrescription($id) {
        $model = $this->model('Health/Models/HealthModel');
        $model->deletePrescription((int)$id, $this->userId);
        set_flash_message('health', 'تم حذف الروشتة وجميع أدويتها بنجاح.', 'success');
        redirect('/health?tab=prescriptions');
    }

    // --- Symptoms ---
    public function storeSymptom() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') redirect('/health?tab=symptoms');
        verify_csrf_token($_POST['csrf_token'] ?? '');

        $model = $this->model('Health/Models/HealthModel');
        $data = [
            'symptom_name' => get_secure_post('symptom_name'),
            'severity'     => get_secure_post('severity') ?: 1,
            'start_date'   => get_secure_post('start_date') ?: date('Y-m-d'),
            'notes'        => get_secure_post('notes')
        ];

        $model->addSymptom($this->userId, $data);
        set_flash_message('health', 'تم تسجيل واجهة العرض بنجاح.', 'success');
        redirect('/health?tab=symptoms');
    }

    public function recoverSymptom() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') redirect('/health?tab=symptoms');
        // Accept payload for AJAX or generic Form Post
        $data = json_decode(file_get_contents('php://input'), true);
        $symptomId = $data['id'] ?? ($_POST['id'] ?? null);

        if ($symptomId) {
            $model = $this->model('Health/Models/HealthModel');
            $model->markSymptomRecovered($this->userId, $symptomId);
            
            // If AJAX call:
            if(isset($data['id'])) {
                echo json_encode(['success' => true]);
                exit;
            }
        }
        
        set_flash_message('health', 'الحمد لله على السلامة! تم تسجيل التعافي.', 'success');
        redirect('/health?tab=symptoms');
    }

    // --- Smart Labs OCR System ---
    
    public function uploadLabDocument() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->jsonError('Method Not Allowed', 405);
        }

        if (!isset($_FILES['lab_file']) || $_FILES['lab_file']['error'] !== UPLOAD_ERR_OK) {
            $this->jsonError('فشل في رفع الملف، تأكد من صحته وحاول مجدداً.', 400);
        }

        $file = $_FILES['lab_file'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['pdf', 'png', 'jpg', 'jpeg'])) {
            http_response_code(400);
            echo json_encode(['error' => 'الامتداد غير مدعوم. يرجى رفع ملف بصيغة (PDF, PNG, JPG).']);
            exit;
        }

        // ── File size limit: 5 MB (Strict Production Rule) ─
        $maxBytes = 5 * 1024 * 1024; // 5 MB
        if ($file['size'] > $maxBytes) {
            http_response_code(413);
            echo json_encode(['error' => 'حجم الملف يتجاوز الحد المسموح (5 ميجابايت). يرجى رفع ملف أصغر.']);
            exit;
        }

        // ── MIME-type double-check (prevent extension spoofing) ─
        $allowedMimes = ['application/pdf', 'image/png', 'image/jpeg', 'image/jpg'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $detectedMime = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
        if (!in_array($detectedMime, $allowedMimes)) {
            http_response_code(400);
            echo json_encode(['error' => 'نوع الملف غير صالح. يُسمح فقط بـ PDF و PNG و JPG.']);
            exit;
        }

        // Save file locally for processing
        $uploadDir = __DIR__ . '/../../../../uploads/labs/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        
        $fileName = uniqid('lab_') . '.' . $ext;
        $destPath = $uploadDir . $fileName;

        if (!move_uploaded_file($file['tmp_name'], $destPath)) {
            $this->jsonError('حدث خطأ أثناء حفظ الملف على الخادم.', 500);
        }

        try {
            require_once __DIR__ . '/../../../../core/Services/OcrService.php';
            require_once __DIR__ . '/../../../../core/Services/LabParserService.php';
            require_once __DIR__ . '/../../../../core/Services/PdfSplitterService.php';

            // Count pages for status display
            $pageCount = 1;
            if ($ext === 'pdf') {
                $splitter  = new \Core\Services\PdfSplitterService();
                $pageCount = $splitter->countPages($destPath);
            }

            $ocr = new \Core\Services\OcrService();
            $rawText = $ocr->extractText($destPath);

            $parser = new \Core\Services\LabParserService();
            $parsedData = $parser->parse($rawText);

            $this->jsonResponse([
                'success'       => true,
                'data'          => $parsedData,
                'uploaded_file' => $fileName,
                'page_count'    => $pageCount,
            ]);
        } catch (\Exception $e) {
            // Clean up the uploaded file on failure
            if (file_exists($destPath)) @unlink($destPath);
            $this->handleException($e, $e->getMessage()); // OCR errors are user-facing (Arabic messages)
        }
    }

    public function storeParsedLabs() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('/health?tab=labs');
        }

        $data = json_decode(file_get_contents('php://input'), true);
        $tests = $data['tests'] ?? [];
        $filePath = $data['uploaded_file'] ?? null;

        if (empty($tests)) {
            echo json_encode(['success' => false, 'error' => 'لا توجد بيانات صالحة للحفظ.']);
            exit;
        }

        $model = $this->model('Health/Models/HealthModel');
        
        require_once __DIR__ . '/../../../../core/Services/LabAnalysisService.php';
        $analysisService = new \Core\Services\LabAnalysisService();
        
        $addedCount = 0;

        foreach ($tests as $t) {
            // Support both old keys (name/value/range) AND new keys (test_name/result_value/normal_range)
            $name = trim($t['test_name'] ?? $t['name'] ?? '');
            $val  = trim($t['result_value'] ?? $t['value'] ?? '');
            
            // Validation: Skip if test name is empty or value is heavily malformed/empty
            if (empty($name) || $val === '') continue;

            $isAbnormal  = !empty($t['is_abnormal']) ? 1 : (!empty($t['abnormal']) ? 1 : 0);
            $needsReview = !empty($t['needs_review']) ? true : false;
            $range = sanitize_input($t['normal_range'] ?? $t['range'] ?? '');

            
            // Advance Intelligence
            $analysis = $analysisService->analyzeSingleTest($name, $val, $range, $isAbnormal, $needsReview);
            
            $historyRecords = $model->getLabHistory($this->userId, $name, 3);
            $historyList = array_map(function($h) { return is_object($h) ? $h->result_value : $h['result_value']; }, $historyRecords);
            $trendStatus = $analysisService->calculateTrend($val, $historyList);

            $model->addSmartLab($this->userId, [
                'test_name' => sanitize_input($name),
                'result_value' => sanitize_input($val),
                'unit' => sanitize_input($t['unit'] ?? ''),
                'normal_range' => $range,
                'is_abnormal' => $isAbnormal,
                'file_path' => sanitize_input($filePath),
                'needs_review' => $needsReview ? 1 : 0,
                'analysis_status' => $analysis['status'],
                'interpretation' => $analysis['interpretation'],
                'recommendation' => $analysis['recommendation'],
                'severity_level' => $analysis['severity_level'],
                'action_level' => $analysis['action_level'],
                'confidence_level' => $analysis['confidence_level'],
                'trend_status' => $trendStatus
            ]);
            $addedCount++;
        }

        // Regenerate and Store Group Insight
        $allLabs = $model->getLabs($this->userId, 20);
        $abnormalLabs = array_filter($allLabs, function($l) { return $l->is_abnormal == 1; });
        $symptoms = $model->getSymptoms($this->userId);
        $activeSymptoms = array_filter($symptoms, function($s) { return is_null($s->end_date); });
        
        $historyMap = [];
        foreach($abnormalLabs as $abLab) {
            $lName = is_object($abLab) ? $abLab->test_name : $abLab['test_name'];
            if(!isset($historyMap[$lName])) {
                $historyMap[$lName] = $model->getLabHistory($this->userId, $lName, 3);
            }
        }
        
        $insightObj = $analysisService->generateGroupInsight($abnormalLabs, $activeSymptoms, $historyMap);
        if ($insightObj) {
            $model->saveGroupInsight($this->userId, $insightObj['text'], $insightObj['priority_issue']);
        }

        set_flash_message('health', "تم حفظ {$addedCount} نتائج تحاليل بنجاح!", 'success');
        echo json_encode(['success' => true, 'redirect' => BASE_URL . '/health?tab=labs']);
        exit;
    }

    public function updateLab($labId) {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { redirect('/health?tab=labs'); }
        verify_csrf_token($_POST['csrf_token']);

        $model  = $this->model('Health/Models/HealthModel');
        $name   = sanitize_input(get_secure_post('test_name'));
        $val    = sanitize_input(get_secure_post('result_value'));
        $unit   = sanitize_input(get_secure_post('unit'));
        $range  = sanitize_input(get_secure_post('normal_range'));
        $is_ab  = isset($_POST['is_abnormal']) ? 1 : 0;

        require_once __DIR__ . '/../../../../core/Services/LabAnalysisService.php';
        $svc      = new \Core\Services\LabAnalysisService();
        $analysis = $svc->analyzeSingleTest($name, $val, $range, $is_ab);

        $model->query(
            "UPDATE health_labs SET test_name=?, result_value=?, unit=?, normal_range=?, is_abnormal=?,
             analysis_status=?, interpretation=?, recommendation=?, severity_level=?
             WHERE id=? AND user_id=?",
            [
                $name, $val, $unit, $range, $is_ab,
                $analysis['status'], $analysis['interpretation'],
                $analysis['recommendation'], $analysis['severity_level'],
                (int)$labId, $this->userId
            ]
        );

        set_flash_message('health', 'تم تعديل نتيجة التحليل بنجاح.', 'success');
        redirect('/health?tab=labs');
    }

    /**
     * AJAX endpoint to fetch lab trends for a specific test
     */
    public function labTrends() {
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            $this->jsonError('Method Not Allowed', 405);
        }

        $testName = isset($_GET['test']) ? trim($_GET['test']) : '';
        if (empty($testName)) {
            $this->jsonError('اسم التحليل مطلوب', 400);
        }

        $model = $this->model('Health/Models/HealthModel');
        $trends = $model->getLabTrends($this->userId, $testName);

        $this->jsonResponse([
            'success' => true,
            'test_name' => htmlspecialchars($testName, ENT_QUOTES, 'UTF-8'),
            'data' => $trends
        ]);
    }
}

