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

$current_time = date('Y-m-d H:i:s');

$tasks = $DB->escape($current_time);
$tasks = $DB->query("SELECT * FROM `cron_tasks` WHERE `status`='enabled' AND `next_run_time` <= '{$current_time_escaped}'");

while ($task = $DB->fetch($tasks)) {
    $command = $task['command'];
    $output = '';
    $status = 'success';
    $return_code = 0;
    
    exec($command . ' 2>&1', $output, $return_code);
    
    $output_text = implode("\n", $output);
    
    if ($return_code !== 0) {
        $status = 'failed';
    }
    
    $run_count = $task['run_count'] + 1;
    $success_count = $task['success_count'];
    $fail_count = $task['fail_count'];
    
    if ($status === 'success') {
        $success_count++;
    } else {
        $fail_count++;
    }
    
    $next_run_time = calculateNextRunTime($task['cron_expression']);
    
    $DB->query("UPDATE `cron_tasks` SET 
        `last_run_time`='{$current_time}',
        `next_run_time`='{$next_run_time}',
        `run_count`='{$run_count}',
        `success_count`='{$success_count}',
        `fail_count`='{$fail_count}',
        `last_run_status`='{$status}',
        `last_run_output`='" . addslashes($output_text) . "'
        WHERE `id`='{$task['id']}'");
    
    $user = $DB->get_row("SELECT * FROM `zj` WHERE `id`='{$task['user_id']}'");
    
    if ($user) {
        logjl($user['user'], '执行定时任务', '执行定时任务：' . $task['name'] . '，状态：' . $status, true);
    }
}

echo "定时任务执行完成\n";

function calculateNextRunTime($cron_expression) {
    $parts = explode(' ', $cron_expression);
    
    if (count($parts) < 5) {
        return date('Y-m-d H:i:s', strtotime('+1 hour'));
    }
    
    $minute = $parts[0];
    $hour = $parts[1];
    $day = $parts[2];
    $month = $parts[3];
    $weekday = $parts[4];
    
    $next_time = strtotime(date('Y-m-d H:00:00'));
    
    if ($minute !== '*') {
        $next_time = strtotime(date('Y-m-d H:' . $minute . ':00'));
    }
    
    if ($hour !== '*') {
        $next_time = strtotime(date('Y-m-d ' . $hour . ':' . $minute . ':00'));
    }
    
    if ($next_time < time()) {
        $next_time = strtotime('+1 day', $next_time);
    }
    
    return date('Y-m-d H:i:s', $next_time);
}
?>
