<?php

namespace App\Core;

/**
 * Notification Center - مركز الإشعارات
 * يوحد جميع أنواع الإشعارات (Email, SMS, WhatsApp, In-app)
 */
class NotificationCenter
{
    private \PDO $db;
    private array $config;
    private Logger $logger;
    private ?EmailService $emailService = null;
    private ?SMS $smsService = null;
    private ?WhatsApp $whatsappService = null;

    public function __construct(\PDO $db, array $config, Logger $logger)
    {
        $this->db = $db;
        $this->config = $config;
        $this->logger = $logger;
        
        // تهيئة الخدمات
        if (!empty($config['email']['enabled'])) {
            require_once __DIR__ . '/EmailService.php';
            $this->emailService = new EmailService($config['email'] ?? []);
        }
        
        if (!empty($config['sms']['enabled'])) {
            $this->smsService = new SMS($db, $config['sms'] ?? [], \App\Core\Tenant::id());
        }
        
        if (!empty($config['whatsapp']['enabled'])) {
            $this->whatsappService = new WhatsApp($db, $config['whatsapp'] ?? []);
        }
    }

    /**
     * إرسال إشعار متعدد القنوات
     */
    public function send(array $channels, string $to, string $subject, string $message, array $options = []): array
    {
        $results = [];
        
        foreach ($channels as $channel) {
            try {
                switch ($channel) {
                    case 'email':
                        if ($this->emailService) {
                            $results['email'] = $this->emailService->sendSimple($to, $subject, $message);
                        }
                        break;
                    case 'sms':
                        if ($this->smsService) {
                            $results['sms'] = $this->smsService->send($to, $message);
                        }
                        break;
                    case 'whatsapp':
                        if ($this->whatsappService) {
                            $results['whatsapp'] = $this->whatsappService->sendMessage($to, $message);
                        }
                        break;
                    case 'in_app':
                        $results['in_app'] = $this->sendInApp($to, $subject, $message, $options);
                        break;
                }
            } catch (\Throwable $e) {
                $results[$channel] = ['error' => $e->getMessage()];
                $this->logger->error("Notification send failed", [
                    'channel' => $channel,
                    'error' => $e->getMessage()
                ]);
            }
        }
        
        return $results;
    }

    /**
     * إرسال إشعار داخل التطبيق
     */
    private function sendInApp(string $userId, string $title, string $message, array $options = []): bool
    {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO notifications (user_id, type, title, message, created_at)
                VALUES (?, ?, ?, ?, NOW())
            ");
            
            return $stmt->execute([
                $userId,
                $options['type'] ?? 'info',
                $title,
                $message
            ]);
        } catch (\Throwable $e) {
            // إنشاء جدول notifications إذا لم يكن موجوداً
            try {
                $this->db->exec("
                    CREATE TABLE IF NOT EXISTS notifications (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        user_id INT NOT NULL,
                        type VARCHAR(50) DEFAULT 'info',
                        title VARCHAR(255),
                        message TEXT,
                        read_at TIMESTAMP NULL,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        INDEX idx_user_id (user_id),
                        INDEX idx_read_at (read_at)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                ");
                
                $stmt = $this->db->prepare("
                    INSERT INTO notifications (user_id, type, title, message, created_at)
                    VALUES (?, ?, ?, ?, NOW())
                ");
                return $stmt->execute([$userId, $options['type'] ?? 'info', $title, $message]);
            } catch (\Throwable $e2) {
                $this->logger->error("In-app notification failed", ['error' => $e2->getMessage()]);
                return false;
            }
        }
    }

    /**
     * إرسال إشعار نتائج جاهزة
     */
    public function sendResultsReady(int $patientId, string $orderNumber, array $channels = ['email', 'sms', 'whatsapp']): array
    {
        // جلب بيانات المريض
        $stmt = $this->db->prepare("SELECT full_name, phone, email FROM patients WHERE id = ?");
        $stmt->execute([$patientId]);
        $patient = $stmt->fetch();
        
        if (!$patient) {
            return ['error' => 'Patient not found'];
        }

        $subject = 'نتائج التحاليل جاهزة';
        $message = "عزيزي/عزيزتي {$patient['full_name']}، نتائج تحاليلك جاهزة. رقم الطلب: {$orderNumber}";
        
        $results = [];
        
        // Email
        if (in_array('email', $channels) && !empty($patient['email']) && $this->emailService) {
            require_once __DIR__ . '/EmailTemplate.php';
            $template = new EmailTemplate();
            $results['email'] = $template->send(
                $patient['email'],
                $subject,
                'results_ready',
                [
                    'patient_name' => $patient['full_name'],
                    'order_number' => $orderNumber,
                    'order_date' => date('Y-m-d'),
                    'portal_url' => 'https://your-domain.com/patient_portal'
                ]
            );
        }
        
        // SMS
        if (in_array('sms', $channels) && !empty($patient['phone']) && $this->smsService) {
            $results['sms'] = $this->smsService->send($patient['phone'], $message);
        }
        
        // WhatsApp
        if (in_array('whatsapp', $channels) && !empty($patient['phone']) && $this->whatsappService) {
            $results['whatsapp'] = $this->whatsappService->sendMessage($patient['phone'], $message);
        }
        
        return $results;
    }
}
