<?php
require_once __DIR__ . '/MPHX/common.php';

$today = date('Y-m-d');
$days7 = date('Y-m-d', strtotime('+7 days'));
$days3 = date('Y-m-d', strtotime('+3 days'));
$days1 = date('Y-m-d', strtotime('+1 days'));

$users = $DB->query("SELECT * FROM `zj` WHERE `dqsj` IN ('{$days7}', '{$days3}', '{$days1}') AND `zt`='正常'");

while ($user = $DB->fetch($users)) {
    $daysUntilExpire = 0;
    if ($user['dqsj'] == $days7) {
        $daysUntilExpire = 7;
    } elseif ($user['dqsj'] == $days3) {
        $daysUntilExpire = 3;
    } elseif ($user['dqsj'] == $days1) {
        $daysUntilExpire = 1;
    }
    
    $settings = $DB->get_row("SELECT * FROM `notification_settings` WHERE `user_id`='{$user['id']}'");
    
    if (!$settings) {
        continue;
    }
    
    $existingNotification = intval($user['id']);
    $daysUntilExpire_escaped = $DB->escape($daysUntilExpire);
    $today_escaped = $DB->escape($today);
    $existingNotification = $DB->get_row("SELECT * FROM `notifications` WHERE `user_id`='{$user_id_escaped}' AND `type`='expire' AND `title` LIKE '%{$daysUntilExpire_escaped}天%' AND DATE(`create_time`)='{$today_escaped}'");
    
    if ($existingNotification) {
        continue;
    }
    
    $title = "主机即将到期提醒";
    $content = "您的主机将在 {$daysUntilExpire} 天后到期，到期时间：{$user['dqsj']}。请及时续费，以免影响您的使用。";
    
    if ($settings['site_expire'] == 1) {
        $DB->query("INSERT INTO `notifications` (`user_id`,`type`,`title`,`content`,`is_read`,`create_time`) VALUES ('{$user['id']}','expire','{$title}','{$content}',0,NOW())");
    }
    
    if ($settings['email_expire'] == 1 && !empty($user['email'])) {
        require_once ROOT . 'mail.php';
        $subject = $title;
        $message = "尊敬的用户 {$user['user']}：\n\n{$content}\n\n感谢您使用我们的服务！";
        sendEmail($user['email'], $subject, $message);
    }
    
    logjl($user['user'], '发送到期提醒', "主机将在{$daysUntilExpire}天后到期", true);
}

echo "通知检查完成\n";
