<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;

final class ScheduleGeneratorService
{
    public static function generateForGroup(int $groupId, string $fromDate, string $toDate): array
    {
        $db = App::getInstance()->db();

        $group = $db->selectOne("SELECT * FROM sa_groups WHERE id = ?", [$groupId]);
        if (!$group || $group['status'] !== 'active') {
            return ['success' => false, 'error' => 'المجموعة غير نشطة', 'generated' => 0, 'skipped' => 0];
        }

        $schedules = $db->select(
            "SELECT gs.*, fu.name_ar as unit_name
             FROM sa_group_schedule gs
             JOIN sa_facility_units fu ON fu.id = gs.facility_unit_id
             WHERE gs.group_id = ? AND gs.is_active = 1",
            [$groupId]
        );

        if (empty($schedules)) {
            return ['success' => false, 'error' => 'لا يوجد جدول للمجموعة', 'generated' => 0, 'skipped' => 0];
        }

        $generated = 0;
        $skipped = 0;
        $errors = [];

        $current = new \DateTime($fromDate);
        $end = new \DateTime($toDate);

        while ($current <= $end) {
            $dayOfWeek = (int) $current->format('w');
            $dateStr = $current->format('Y-m-d');

            foreach ($schedules as $sched) {
                if ((int) $sched['day_of_week'] !== $dayOfWeek) {
                    continue;
                }

                $existing = $db->selectOne(
                    "SELECT id FROM sa_bookings
                     WHERE group_id = ? AND facility_unit_id = ? AND booking_date = ?
                     AND start_time = ? AND status != 'cancelled'",
                    [$groupId, (int) $sched['facility_unit_id'], $dateStr, $sched['start_time']]
                );

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

                $result = BookingService::createTrainingBooking(
                    $groupId,
                    (int) $sched['facility_unit_id'],
                    $dateStr,
                    $sched['start_time'],
                    $sched['end_time'],
                    (int) $group['coach_id']
                );

                if ($result['success']) {
                    $generated++;
                } else {
                    $skipped++;
                    $errors[] = "{$dateStr}: {$result['error']}";
                }
            }

            $current->modify('+1 day');
        }

        return [
            'success'   => true,
            'generated' => $generated,
            'skipped'   => $skipped,
            'errors'    => $errors,
        ];
    }
}
