<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;

class SessionAutoCompleteJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        return true; // Daily
    }

    public function run(): array
    {
        $yesterday = date('Y-m-d', strtotime('-1 day'));

        $result = $this->db->query(
            "UPDATE training_sessions
             SET status = 'completed',
                 players_attended = (
                     SELECT COUNT(*) FROM session_attendance
                     WHERE session_id = training_sessions.id
                       AND status IN ('present', 'late', 'makeup')
                 )
             WHERE status IN ('scheduled', 'in_progress')
               AND session_date < ?",
            [$yesterday]
        );

        $count = $result->rowCount();

        return [
            'status'  => 'success',
            'message' => "Auto-completed {$count} past sessions.",
        ];
    }
}
