<?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 = [];

        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;
                }

                $schedules = [];

                for ($i = 1; 0 < count($weeks); $i++) {
                    if (isset($weeks[$i])) {
                        foreach ($weeks[$i] as $schedule) {
                            $schedules[] = $schedule;
                        }

                        unset($weeks[$i]);
                    } else {
                        $schedules[] = [
                            'type' => 'Week ' . $i,
                            'date' => 'BYE',
                            'opponent' => 'BYE',
                            'result' => 'BYE',
                        ];
                    }
                }

                $data[$key] = $schedules;
            }
        }

        return $data;
    }
}
