<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;

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

    public function shouldRun(): bool
    {
        return (int) date('N') === 7; // Sundays
    }

    public function run(): array
    {
        $nextMonday = date('Y-m-d', strtotime('next monday'));
        $created = 0;
        $skipped = 0;

        $groups = $this->db->select("
            SELECT id, academy_id, coach_id, facility_id, day_of_week, start_time, end_time
            FROM training_groups
            WHERE status = 'active'
        ");

        $dayMap = [
            'saturday' => 6, 'sunday' => 0, 'monday' => 1, 'tuesday' => 2,
            'wednesday' => 3, 'thursday' => 4, 'friday' => 5,
        ];

        foreach ($groups as $group) {
            $dayNum = $dayMap[$group['day_of_week']] ?? null;
            if ($dayNum === null) {
                $skipped++;
                continue;
            }

            $daysFromMonday = ($dayNum - 1 + 7) % 7;
            $sessionDate = date('Y-m-d', strtotime($nextMonday . ' +' . $daysFromMonday . ' days'));

            $exists = $this->db->selectOne(
                "SELECT id FROM training_sessions WHERE group_id = ? AND session_date = ?",
                [(int) $group['id'], $sessionDate]
            );

            if ($exists) {
                $skipped++;
                continue;
            }

            $enrolledCount = $this->db->selectOne(
                "SELECT COUNT(*) AS cnt FROM group_memberships WHERE group_id = ? AND status = 'active'",
                [(int) $group['id']]
            )['cnt'] ?? 0;

            $this->db->insert('training_sessions', [
                'group_id'         => (int) $group['id'],
                'academy_id'       => $group['academy_id'] ? (int) $group['academy_id'] : null,
                'coach_id'         => $group['coach_id'] ? (int) $group['coach_id'] : null,
                'facility_id'      => $group['facility_id'] ? (int) $group['facility_id'] : null,
                'session_date'     => $sessionDate,
                'start_time'       => $group['start_time'],
                'end_time'         => $group['end_time'],
                'session_type'     => 'regular',
                'status'           => 'scheduled',
                'players_expected' => (int) $enrolledCount,
            ]);
            $created++;
        }

        return [
            'status'  => 'success',
            'message' => "Generated {$created} sessions for week of {$nextMonday}, skipped {$skipped}.",
        ];
    }
}
