<?php

namespace Rdgcorp\Blocks\TeamSchedules\Utils\Mappers;

class FootballSchedulesMapper extends AbstractScheduleMapper
{
    public function getMappedData($homeTeamId, $rawSchedules): array
    {
        $days = [];

        foreach ($rawSchedules as $schedule) {
            $date = new \DateTime($schedule['start_date']);

            $days[(int)$date->format('Ymd')][] = [
                'type' => $schedule['type'],
                'date' => $date->format('D d/m/Y'),
                'opponent' => $this->getScheduleOpponent($homeTeamId, $schedule),
                'result' => $this->getScheduleResult($homeTeamId, $schedule),
            ];
        }

        ksort($days);

        $types = [];

        foreach ($days as $day) {
            foreach ($day as $schedule) {
                if (str_starts_with(strtolower($schedule['type']), 'pre-season')) {
                    $type = 'Pre-Season';

                    $schedule['type'] = str_replace('Pre-Season ', '', $schedule['type']);
                } elseif (str_starts_with(strtolower($schedule['type']), 'week')) {
                    $type = 'Regular-Season';
                } else {
                    $type = 'Post-Season';
                }

                $types[$type][] = $schedule;
            }
        }

        $data = [];
        $schedules = [];

        foreach ($types as $key => $type) {
            if ('Post-Season' === $key) {
                $data[$key] = $type;
            } else {
                $weeks = [];
                foreach ($type as $schedule) {
                    $week = (int)str_replace('Week ', '', $schedule['type']);
                    $weeks[$week][] = $schedule;
                }
                ksort($weeks);
                for ($i = 1; $i <= max(array_keys($weeks)); $i++) {
                    if (isset($weeks[$i])) {
                        $schedules = array_merge($schedules, $weeks[$i]);
                    } else {
                        $schedules[] = [
                            'type' => 'Week ' . $i,
                            'date' => 'BYE',
                            'opponent' => 'BYE',
                            'result' => 'BYE',
                        ];
                    }
                }
                $data[$key] = $schedules;
                $schedules = [];
            }
        }

        return $data;
    }
}
