<?php
/**
 * 定时任务：每天检查即将到期的服务并发送邮件提醒
 * 建议设置 crontab: 0 9 * * * php /www/wwwroot/auth.lhwks.cn/encrypt/cron_check_expire.php >> /www/wwwroot/auth.lhwks.cn/logs/cron.log 2>&1
 */

require_once 'config.php';

// 设置执行时间限制，避免超时
set_time_limit(0);

// 日志记录函数
function log_message($msg) {
    $timestamp = date('Y-m-d H:i:s');
    echo "[$timestamp] $msg\n";
}

log_message("========== 开始检查到期服务 ==========");

// 检查邮件配置是否完善
$mail_config = getMailConfig();
if (empty($mail_config['user']) || empty($mail_config['pass'])) {
    log_message("错误：邮件配置未设置，请先在后台配置SMTP");
    exit(1);
}

// 获取即将到期的服务（7天内到期）
// 并且用户开启了邮件通知、有邮箱地址、今天还未发送过提醒
$services = $db->fetchAll("
    SELECT s.*, u.id as user_id, u.username, u.email, u.email_notify, u.last_notify_at
    FROM encrypt_services s
    INNER JOIN users u ON s.user_id = u.id
    WHERE s.status = 1 
    AND s.expire_date IS NOT NULL
    AND s.expire_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 7 DAY)
    AND u.email_notify = 1
    AND u.email IS NOT NULL
    AND u.email != ''
    AND (u.last_notify_at IS NULL OR DATE(u.last_notify_at) < CURDATE())
    ORDER BY s.expire_date ASC
");

log_message("找到 " . count($services) . " 个即将到期的服务");

$sent_count = 0;
$fail_count = 0;
$today = date('Y-m-d');

foreach ($services as $service) {
    $expire_date = $service['expire_date'];
    $remaining_days = getServiceRemainingDays($service);
    
    // 只在剩余 7天、3天、1天 时发送提醒
    if (!in_array($remaining_days, [7, 3, 1])) {
        continue;
    }
    
    $user = [
        'id' => $service['user_id'],
        'username' => $service['username'],
        'email' => $service['email']
    ];
    
    log_message("正在向 {$user['username']} ({$user['email']}) 发送提醒，剩余 {$remaining_days} 天");
    
    if (sendExpireNotification($user, $remaining_days)) {
        // 更新最后通知时间
        $db->query("UPDATE users SET last_notify_at = NOW() WHERE id = {$user['id']}");
        $sent_count++;
        log_message("  ✅ 发送成功");
    } else {
        $fail_count++;
        log_message("  ❌ 发送失败");
    }
    
    // 避免发送过快，稍作延迟
    usleep(500000); // 0.5秒
}

log_message("========== 执行完成 ==========");
log_message("成功发送: {$sent_count} 封，失败: {$fail_count} 封");