<?php
/**
 * معالجة طابور واتساب - يرسل الرسائل المعلقة بالخلفية
 * يدعم واتساب الطبيب (UltraMsg مالتة) وإعدادات المختبر
 *
 * Linux: * * * * * php /path/to/scripts/whatsapp_queue_cron.php
 * Windows: schtasks كل دقيقة
 */

$baseDir = dirname(__DIR__);
require_once $baseDir . '/src/Core/Database.php';
require_once $baseDir . '/src/Core/Tenant.php';
require_once $baseDir . '/src/Core/WhatsApp.php';

$config = require $baseDir . '/config/config.php';
date_default_timezone_set($config['timezone'] ?? 'Asia/Baghdad');

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

try {
    $db->query('SELECT id FROM whatsapp_send_queue LIMIT 1');
} catch (Throwable $e) {
    $f = $baseDir . '/migrations/034_doctor_whatsapp_queue.sql';
    if (file_exists($f)) {
        foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) {
            if (!empty($s) && strpos($s, '--') !== 0) {
                try { $db->exec($s); } catch (Throwable $x) {}
            }
        }
    }
}
try {
    $db->query('SELECT reminder_entity_type FROM whatsapp_send_queue LIMIT 1');
} catch (Throwable $e) {
    $f = $baseDir . '/migrations/035_whatsapp_queue_reminder_fields.sql';
    if (file_exists($f)) {
        foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) {
            if (!empty($s) && strpos($s, '--') !== 0) {
                try { $db->exec($s); } catch (Throwable $x) {}
            }
        }
    }
}

$stmt = $db->query("SELECT id, tenant_id, doctor_account_id, phone, message, use_doctor_config, reminder_entity_type, reminder_entity_id, reminder_doctor_account_id, reminder_patient_id, reminder_appointment_date, reminder_appointment_time FROM whatsapp_send_queue WHERE status = 'pending' ORDER BY created_at ASC LIMIT 50");
$rows = $stmt->fetchAll();
$sent = 0;
$failed = 0;

foreach ($rows as $row) {
    $waConfig = [];
    if (!empty($row['use_doctor_config']) && !empty($row['doctor_account_id'])) {
        try {
            $da = $db->prepare('SELECT whatsapp_instance_id, whatsapp_access_token FROM doctor_accounts WHERE id = ?');
            $da->execute([$row['doctor_account_id']]);
            $d = $da->fetch();
            if ($d && trim((string)($d['whatsapp_instance_id'] ?? '')) !== '' && trim((string)($d['whatsapp_access_token'] ?? '')) !== '') {
                \App\Core\Tenant::setId(0);
                $waConfig = [
                    'enabled' => true,
                    'provider' => 'ultramsg',
                    'instance_id' => trim($d['whatsapp_instance_id']),
                    'access_token' => trim($d['whatsapp_access_token']),
                    'api_url' => '', 'from_number' => ''
                ];
            }
        } catch (Throwable $e) {}
    }
    if (empty($waConfig)) {
        \App\Core\Tenant::setId((int)$row['tenant_id']);
        $waConfig = array_merge(['enabled' => false, 'provider' => 'ultramsg', 'api_url' => '', 'from_number' => '', 'access_token' => '', 'instance_id' => ''], $whatsappConfig ?? []);
        try {
            $st = $db->prepare('SELECT setting_key, setting_value FROM settings WHERE tenant_id = ? AND setting_key IN ("whatsapp_enabled","whatsapp_provider","whatsapp_api_url","whatsapp_from_number","whatsapp_access_token","whatsapp_instance_id")');
            $st->execute([(int)$row['tenant_id']]);
            foreach ($st->fetchAll() as $s) {
                $k = $s['setting_key'];
                $v = (string)$s['setting_value'];
                if ($k === 'whatsapp_enabled') $waConfig['enabled'] = $v === '1';
                elseif ($k === 'whatsapp_provider') $waConfig['provider'] = $v;
                elseif ($k === 'whatsapp_api_url') $waConfig['api_url'] = $v;
                elseif ($k === 'whatsapp_from_number') $waConfig['from_number'] = $v;
                elseif ($k === 'whatsapp_access_token') $waConfig['access_token'] = $v;
                elseif ($k === 'whatsapp_instance_id') $waConfig['instance_id'] = $v;
            }
        } catch (Throwable $e) {}
    }
    $enabled = !empty($waConfig['enabled']) || (!empty($waConfig['instance_id']) && !empty($waConfig['access_token']));
    if (!$enabled) {
        $db->prepare('UPDATE whatsapp_send_queue SET status = ?, error_message = ? WHERE id = ?')->execute(['failed', 'WhatsApp غير مفعّل', $row['id']]);
        $failed++;
        continue;
    }
    try {
        $wa = new \App\Core\WhatsApp($db, $waConfig);
        $ok = $wa->sendToNumber($row['phone'], $row['message']);
        $db->prepare('UPDATE whatsapp_send_queue SET status = ?, sent_at = NOW(), error_message = ? WHERE id = ?')
            ->execute([$ok ? 'sent' : 'failed', $ok ? null : 'فشل الإرسال', $row['id']]);
        if ($ok) {
            $sent++;
            if (!empty($row['reminder_entity_type']) && !empty($row['reminder_entity_id'])) {
                try {
                    $db->prepare('INSERT INTO patient_appointment_reminders (doctor_account_id, patient_id, appointment_date, appointment_time, entity_type, entity_id) VALUES (?, ?, ?, ?, ?, ?)')
                        ->execute([
                            $row['reminder_doctor_account_id'] ?? $row['doctor_account_id'],
                            $row['reminder_patient_id'],
                            $row['reminder_appointment_date'],
                            $row['reminder_appointment_time'],
                            $row['reminder_entity_type'],
                            $row['reminder_entity_id']
                        ]);
                } catch (Throwable $ex) {}
            }
        } else {
            $failed++;
        }
    } catch (Throwable $e) {
        $db->prepare('UPDATE whatsapp_send_queue SET status = ?, error_message = ? WHERE id = ?')
            ->execute(['failed', substr($e->getMessage(), 0, 500), $row['id']]);
        $failed++;
    }
}

if ($sent > 0 || $failed > 0) {
    echo date('Y-m-d H:i') . " - تم إرسال: $sent | فشل: $failed\n";
}
