<?php
namespace App\Commands;

use App\Libraries\AttendanceAutoPublish as AutoPublishLib;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class AttendanceAutoPublishCommand extends BaseCommand
{
    protected $group       = 'Attendance';
    protected $name        = 'attendance:auto-publish';
    protected $description = 'Auto-publish attendance days per "second Sunday backward" rule.';

    public function run(array $params)
    {
        $db     = db_connect();
        $zone   = AutoPublishLib::tz();
        $now    = new \DateTimeImmutable('now', $zone);
        $nowStr = $now->format('Y-m-d H:i:s');

        $cutoffDate = AutoPublishLib::secondSundayBackwardDate($now);

        $builder = $db->table('attendance_day');
        $builder->where('status', 'submitted')
                ->groupStart()
                    ->where('auto_publish_at <=', $nowStr)
                    ->orGroupStart()
                        ->where('auto_publish_at IS NULL', null, false)
                        ->where('date <=', $cutoffDate)
                    ->groupEnd()
                ->groupEnd();

        $count = $builder->countAllResults(false); // keep the WHEREs

        if ($count > 0) {
            $builder->update([
                'status'       => 'published',
                'published_by' => 0, // system
                'published_at' => $nowStr,
                'updated_at'   => $nowStr,
            ]);
        }

        CLI::write("Auto-publish checked at {$nowStr} (TZ: {$zone->getName()}). Published rows: {$count}.");
    }
}
