<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\EventBus;
use App\Core\Logger;
use App\Core\App;

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

    public function shouldRun(): bool
    {
        return (int) date('j') === 1;
    }

    public function run(): array
    {
        App::getInstance()->setDb($this->db);

        $lastMonth = date('Y-m', strtotime('-1 month'));
        $from = $lastMonth . '-01';
        $to = date('Y-m-t', strtotime($from));

        $threshold = (int) ($this->db->selectOne(
            "SELECT value FROM system_config WHERE `key` = 'sa.absence_threshold'",
            []
        )['value'] ?? 3);

        $players = $this->db->select(
            "SELECT gp.player_id, gp.group_id, p.full_name_ar, p.phone, p.guardian_phone,
                    g.name_ar as group_name,
                    (SELECT COUNT(*) FROM sa_attendance a
                     WHERE a.player_id = gp.player_id AND a.group_id = gp.group_id
                     AND a.session_date BETWEEN ? AND ? AND a.status = 'absent') as absence_count
             FROM sa_group_players gp
             INNER JOIN sa_players p ON p.id = gp.player_id
             INNER JOIN sa_groups g ON g.id = gp.group_id
             WHERE gp.status = 'active'
             HAVING absence_count >= ?",
            [$from, $to, $threshold]
        );

        $notified = 0;
        foreach ($players as $player) {
            $phone = $player['guardian_phone'] ?: ($player['phone'] ?? '');
            if ($phone === '') {
                continue;
            }

            EventBus::dispatch('sa.player.absence_threshold', [
                'player_id'     => (int) $player['player_id'],
                'player_name'   => $player['full_name_ar'],
                'group_name'    => $player['group_name'],
                'absence_count' => (int) $player['absence_count'],
                'month'         => $lastMonth,
                'phone'         => $phone,
            ]);
            $notified++;
        }

        Logger::info("SaAttendanceReportJob for {$lastMonth}: {$notified} players exceeded threshold ({$threshold})");
        return ['month' => $lastMonth, 'threshold' => $threshold, 'notified' => $notified];
    }
}
