<?php
// scripts/send_reminders.php
// Should be run as a cron job daily: php scripts/send_reminders.php

require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../m_services/MailService.php';

echo "[" . date('Y-m-d H:i:s') . "] Starting reminder process..." . PHP_EOL;

$tables = ['inbound_mail', 'outbound_mail']; // internal mail usually doesn't have due dates or reminders the same way

foreach ($tables as $table) {
    echo "Processing $table..." . PHP_EOL;
    
    // 1. Tasks due in 24 hours
    $stmt = db()->prepare("
        SELECT m.*, u.email, u.full_name 
        FROM $table m 
        JOIN users u ON m.assigned_to = u.id 
        JOIN mailbox_statuses s ON m.status_id = s.id
        WHERE m.due_date = DATE_ADD(CURDATE(), INTERVAL 1 DAY) 
        AND s.name != 'closed'
    ");
    $stmt->execute();
    $due_tomorrow = $stmt->fetchAll();

    foreach ($due_tomorrow as $task) {
        if (!empty($task['email'])) {
            $subject = "تذكير: موعد نهائي لمهمة غداً - " . $task['ref_no'];
            $html = "
                <div dir='rtl' style='font-family: Arial, sans-serif;'>
                    <h3>تذكير بموعد نهائي</h3>
                    <p>عزيزي <b>" . htmlspecialchars($task['full_name']) . "</b>،</p>
                    <p>هذا تذكير بأن المهمة التالية مستحقة غداً:</p>
                    <ul>
                        <li><b>رقم المرجع:</b> " . htmlspecialchars($task['ref_no']) . "</li>
                        <li><b>الموضوع:</b> " . htmlspecialchars($task['subject']) . "</li>
                        <li><b>تاريخ الاستحقاق:</b> " . $task['due_date'] . "</li>
                    </ul>
                    <p>يرجى متابعة المهمة وإغلاقها في الوقت المحدد.</p>
                </div>
            ";
            $res = MailService::sendMail($task['email'], $subject, $html);
            if ($res['success']) {
                echo "Sent 24h reminder to " . $task['email'] . " for task " . $task['ref_no'] . PHP_EOL;
            }
        }
    }

    // 2. Overdue tasks
    $stmt = db()->prepare("
        SELECT m.*, u.email, u.full_name 
        FROM $table m 
        JOIN users u ON m.assigned_to = u.id 
        JOIN mailbox_statuses s ON m.status_id = s.id
        WHERE m.due_date < CURDATE() 
        AND s.name != 'closed'
    ");
    $stmt->execute();
    $overdue = $stmt->fetchAll();

    foreach ($overdue as $task) {
        if (!empty($task['email'])) {
            $subject = "تنبيه: مهمة متأخرة! - " . $task['ref_no'];
            $html = "
                <div dir='rtl' style='font-family: Arial, sans-serif;'>
                    <h3 style='color: red;'>تنبيه: مهمة متأخرة</h3>
                    <p>عزيزي <b>" . htmlspecialchars($task['full_name']) . "</b>،</p>
                    <p>هذه المهمة قد تجاوزت الموعد النهائي المحدد:</p>
                    <ul>
                        <li><b>رقم المرجع:</b> " . htmlspecialchars($task['ref_no']) . "</li>
                        <li><b>الموضوع:</b> " . htmlspecialchars($task['subject']) . "</li>
                        <li><b>تاريخ الاستحقاق:</b> <span style='color: red;'>" . $task['due_date'] . "</span></li>
                    </ul>
                    <p>يرجى معالجة هذه المهمة في أقرب وقت ممكن.</p>
                </div>
            ";
            $res = MailService::sendMail($task['email'], $subject, $html);
            if ($res['success']) {
                echo "Sent overdue reminder to " . $task['email'] . " for task " . $task['ref_no'] . PHP_EOL;
            }
        }
    }
}

echo "[" . date('Y-m-d H:i:s') . "] Reminder process finished." . PHP_EOL;