<?php
// Usage: php scripts/fix-check-date-20261030.php <site-root>
// Repairs 2026-10-30 daytime records by the fixed 07:00-19:00 rule.
$root = $argv[1] ?? '';
if (!$root || !is_file($root.'/vendor/autoload.php')) { fwrite(STDERR,"Invalid site root\n"); exit(1); }
require $root.'/vendor/autoload.php';
$app = new think\App(rtrim($root,'/\\').DIRECTORY_SEPARATOR);
$app->initialize();
use think\facade\Db;
$day = strtotime('2026-10-30');
$rows = Db::name('me_check_record')->alias('r')->join('team_list t','t.id=r.tid')
    ->where('r.shift',1)->where('r.check_date',$day-86400)
    ->where('r.update','>=',$day+7*3600)->where('r.update','<',$day+19*3600)
    ->field('r.*')->order('r.id')->select()->toArray();
if (!$rows) { echo "No matching records; nothing changed.\n"; exit; }
// Keep original rows before any mutation, including their primary keys.
$backup = rtrim($root,'/\\').'/runtime/check-date-20261030-'.date('YmdHis').'-'.bin2hex(random_bytes(4)).'.json';
if (file_put_contents($backup,json_encode($rows,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT),LOCK_EX)===false) throw new RuntimeException('Backup failed');
$fixed=0;$skipped=0;
Db::transaction(function()use($rows,$day,&$fixed,&$skipped){
    foreach($rows as $r){
        // Conflicting same-period records need manual review; do not merge or delete them.
        $conflict=Db::name('me_check_record')->where(['m_id'=>$r['m_id'],'check_id'=>$r['check_id'],'shift'=>1,'check_date'=>$day,'status'=>1])->count();
        if($conflict){$skipped++;continue;}
        $fixed+=Db::name('me_check_record')->where(['id'=>$r['id'],'check_date'=>$r['check_date'],'update'=>$r['update']])->update(['check_date'=>$day]);
    }
});
echo "Fixed: $fixed; conflicts skipped: $skipped; backup: $backup\n";
