<?php
/** Windows任务计划程序统一入口；唯一参数为站点根目录，每天固定时间或每小时执行。 */
use think\facade\Db;

function scheduledKpiConfirm() {
    // 保留旧规则：按考评日期，而非提交时间；严格早于今天往前两天。
    return Db::name('kpi_record')->where('kpi_date','<',strtotime('today')-2*86400)
        ->where('status',1)->update(['status'=>4,'update'=>time()]);
}

if(PHP_SAPI!=='cli' || realpath($_SERVER['SCRIPT_FILENAME']??'')!==__FILE__)return;
$root=isset($argv[1])?realpath($argv[1]):false;
if(!$root || !is_file($root.'/vendor/autoload.php')){
    fwrite(STDERR,"Please pass the site root directory.\n");exit(1);
}
require $root.'/vendor/autoload.php';
$app=new \think\App($root.'/');$app->initialize();
date_default_timezone_set('Asia/Shanghai');
$lock=fopen($root.'/runtime/scheduled-tasks.lock','c');
if(!$lock){fwrite(STDERR,"Cannot open scheduler lock.\n");exit(1);}
if(!flock($lock,LOCK_EX|LOCK_NB)){fclose($lock);echo "Another scheduler is running.\n";exit(0);}
$failed=false;
try{
    $tasks=[
        'suggestion-transfer'=>function(){return \app\mobile\service\SuggestionTransfer::acceptExpired();},
        'performance-confirm'=>'scheduledKpiConfirm',
    ];
    foreach($tasks as $name=>$task){
        try{$count=$task();$message=$name.' OK processed='.$count;}
        catch(\Throwable $error){$failed=true;$message=$name.' FAILED '.$error->getMessage();}
        $line='['.date('Y-m-d H:i:s').'] '.$message.PHP_EOL;
        echo $line;
        if(file_put_contents($root.'/runtime/scheduled-tasks.log',$line,FILE_APPEND|LOCK_EX)===false)$failed=true;
    }
}finally{flock($lock,LOCK_UN);fclose($lock);}
exit($failed?1:0);
