<?php
/**
 * نظام التذكيرات التلقائية - Smart Doctor
 * يمكن تشغيله كـ Cron job يومياً
 * 
 * استخدام: php modules/doctor/auto_reminders.php
 * أو: 0 8 * * * php /path/to/modules/doctor/auto_reminders.php
 */

$config = require __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../src/Core/Database.php';

$db = \App\Core\Database::getInstance($config['db'])->connection();

// التحقق من وجود الجداول
$tablesExist = true;
try {
    $db->query('SELECT id FROM doctor_alerts LIMIT 1');
} catch (Throwable $e) {
    $tablesExist = false;
    echo "⚠️ جدول doctor_alerts غير موجود. يرجى تشغيل migration أولاً.\n";
    exit(1);
}

try {
    $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1');
} catch (Throwable $e) {
    $tablesExist = false;
    echo "⚠️ جدول doctor_follow_up_reminders غير موجود. يرجى تشغيل migration أولاً.\n";
    exit(1);
}

try {
    // التحقق من وجود جدول doctor_accounts
    $db->query('SELECT id FROM doctor_accounts LIMIT 1');
    
    // 1. إنشاء تنبيهات للنتائج الحرجة الجديدة
    $criticalResults = [];
    try {
        // التحقق من وجود الجداول المطلوبة
        $db->query('SELECT id FROM results LIMIT 1');
        $db->query('SELECT id FROM order_items LIMIT 1');
        
        $stmt = $db->prepare("SELECT DISTINCT o.doctor_id, o.tenant_id, o.id AS order_id, o.patient_id, p.full_name AS patient_name,
            da.id AS doctor_account_id
            FROM lab_orders o
            JOIN patients p ON p.id = o.patient_id
            JOIN order_items oi ON oi.order_id = o.id
            JOIN results r ON r.order_item_id = oi.id
            JOIN doctor_accounts da ON da.doctor_id = o.doctor_id AND da.tenant_id = o.tenant_id AND da.is_active = 1
            WHERE o.doctor_id IS NOT NULL 
            AND o.tenant_id IS NOT NULL
            AND r.flag = 'C' 
            AND r.created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
            AND NOT EXISTS (
                SELECT 1 FROM doctor_alerts 
                WHERE doctor_account_id = da.id 
                AND entity_type = 'order' 
                AND entity_id = o.id 
                AND alert_type = 'critical'
                AND created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
            )");
        $stmt->execute();
        $criticalResults = $stmt->fetchAll();
    } catch (Throwable $e) {
        error_log("Error fetching critical results: " . $e->getMessage());
    }
    
    foreach ($criticalResults as $cr) {
        try {
            $alertStmt = $db->prepare('INSERT INTO doctor_alerts 
                (doctor_account_id, alert_type, title, message, priority, entity_type, entity_id, action_url) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
            $alertStmt->execute([
                $cr['doctor_account_id'],
                'critical',
                'نتيجة حرجة جديدة',
                'مريض: ' . $cr['patient_name'] . ' - يوجد نتيجة حرجة تحتاج مراجعة فورية',
                'urgent',
                'order',
                $cr['order_id'],
                'doctor.php?page=results&order_id=' . $cr['order_id']
            ]);
        } catch (Throwable $e) {
            error_log("Error creating critical alert: " . $e->getMessage());
        }
    }
    
    // 2. إنشاء تذكيرات تلقائية للمتابعة بناءً على النتائج غير الطبيعية
    $abnormalPatients = [];
    try {
        $stmt = $db->prepare("SELECT DISTINCT o.patient_id, o.doctor_id, o.tenant_id, 
            da.id AS doctor_account_id,
            p.full_name AS patient_name,
            COUNT(DISTINCT r.id) AS abnormal_count
            FROM lab_orders o
            JOIN patients p ON p.id = o.patient_id
            JOIN order_items oi ON oi.order_id = o.id
            JOIN results r ON r.order_item_id = oi.id
            JOIN doctor_accounts da ON da.doctor_id = o.doctor_id AND da.tenant_id = o.tenant_id AND da.is_active = 1
            WHERE o.doctor_id IS NOT NULL 
            AND o.tenant_id IS NOT NULL
            AND r.flag IN ('L', 'H', 'C')
            AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
            AND NOT EXISTS (
                SELECT 1 FROM doctor_follow_up_reminders 
                WHERE doctor_account_id = da.id 
                AND patient_id = o.patient_id
                AND reminder_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 14 DAY)
                AND is_done = 0
            )
            GROUP BY o.patient_id, o.doctor_id, o.tenant_id, da.id, p.full_name
            HAVING abnormal_count >= 2");
        $stmt->execute();
        $abnormalPatients = $stmt->fetchAll();
    } catch (Throwable $e) {
        error_log("Error fetching abnormal patients: " . $e->getMessage());
    }
    
    foreach ($abnormalPatients as $ap) {
        try {
            $reminderDate = date('Y-m-d', strtotime('+2 weeks'));
            $reminderStmt = $db->prepare('INSERT INTO doctor_follow_up_reminders 
                (doctor_account_id, patient_id, reminder_date, note) 
                VALUES (?, ?, ?, ?)');
            $reminderStmt->execute([
                $ap['doctor_account_id'],
                $ap['patient_id'],
                $reminderDate,
                'متابعة تلقائية: تم اكتشاف ' . $ap['abnormal_count'] . ' نتيجة غير طبيعية خلال آخر 7 أيام'
            ]);
            
            // إنشاء تنبيه أيضاً
            $alertStmt = $db->prepare('INSERT INTO doctor_alerts 
                (doctor_account_id, alert_type, title, message, priority, entity_type, entity_id, action_url) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
            $alertStmt->execute([
                $ap['doctor_account_id'],
                'reminder',
                'تذكير متابعة تلقائي',
                'مريض: ' . $ap['patient_name'] . ' - يُنصح بمتابعة بعد أسبوعين',
                'medium',
                'patient',
                $ap['patient_id'],
                'doctor.php?page=results&patient_id=' . $ap['patient_id']
            ]);
        } catch (Throwable $e) {
            error_log("Error creating auto reminder: " . $e->getMessage());
        }
    }
    
    // 3. تنبيهات للمواعيد القادمة
    $upcomingAppointments = [];
    try {
        $db->query('SELECT id FROM doctor_appointments LIMIT 1');
        $stmt = $db->prepare('SELECT a.*, p.full_name AS patient_name, da.id AS doctor_account_id
            FROM doctor_appointments a
            JOIN patients p ON p.id = a.patient_id
            JOIN doctor_accounts da ON da.id = a.doctor_account_id AND da.is_active = 1
            WHERE a.appointment_date = DATE_ADD(CURDATE(), INTERVAL 1 DAY)
            AND a.status IN ("scheduled", "confirmed")
            AND NOT EXISTS (
                SELECT 1 FROM doctor_alerts 
                WHERE doctor_account_id = da.id 
                AND entity_type = "appointment" 
                AND entity_id = a.id 
                AND alert_type = "appointment"
                AND created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)
            )');
        $stmt->execute();
        $upcomingAppointments = $stmt->fetchAll();
        
        foreach ($upcomingAppointments as $apt) {
            try {
                $alertStmt = $db->prepare('INSERT INTO doctor_alerts 
                    (doctor_account_id, alert_type, title, message, priority, entity_type, entity_id, action_url) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
                $alertStmt->execute([
                    $apt['doctor_account_id'],
                    'appointment',
                    'موعد غداً',
                    'مريض: ' . $apt['patient_name'] . ' - موعد غداً في ' . date('H:i', strtotime($apt['appointment_time'])),
                    'high',
                    'appointment',
                    $apt['id'],
                    'doctor.php?page=appointments&date=' . $apt['appointment_date']
                ]);
            } catch (Throwable $e) {
                error_log("Error creating appointment alert: " . $e->getMessage());
            }
        }
    } catch (Throwable $e) {
        // جدول المواعيد قد لا يكون موجوداً
    }
    
    echo "✅ تم معالجة التذكيرات التلقائية بنجاح\n";
    echo "   - تنبيهات حرجة: " . count($criticalResults) . "\n";
    echo "   - تذكيرات متابعة: " . count($abnormalPatients) . "\n";
    echo "   - تنبيهات مواعيد: " . count($upcomingAppointments) . "\n";
    
} catch (Throwable $e) {
    error_log("Auto reminders error: " . $e->getMessage());
    echo "❌ خطأ: " . $e->getMessage() . "\n";
    echo "   Trace: " . $e->getTraceAsString() . "\n";
    exit(1);
}
