<?php

namespace Stub;

use Model\Training;
use Repository\ITrainingRepository;

class TrainingRepository implements ITrainingRepository {
    private array $trainings = [];

    public function __construct() {
       
    }

    public function getItemById(int $id): ?Training {
        foreach ($this->trainings as $training) {
            if ($training->getId() === $id) {
                return $training;
            }
        }
        return null;
    }

    public function getNbItems(): int {
        return count($this->trainings);
    }

    public function getItems(int $index, int $count, ?string $orderingPropertyName = null, bool $descending = false): array {
        // Implement the logic for ordering and slicing the array
        return array_slice($this->trainings, $index, $count);
    }

    public function getItemsByDate(\DateTime $date, int $index, int $count, ?string $orderingPropertyName = null, bool $descending = false): array {
        $filteredTrainings = array_filter($this->trainings, function ($training) use ($date) {
            return $training->getDate() == $date;
        });
        // Implement sorting if necessary
        return array_slice($filteredTrainings, $index, $count);
    }

    public function updateItem( $oldTraining,  $newTraining): void {
        $index = array_search($oldTraining, $this->trainings);
        if ($index !== false) {
            $this->trainings[$index] = $newTraining;
        }
    }

    public function addItem( $training): void {
        $this->trainings[] = $training;
    }

    public function deleteItem( $training): bool {
        $index = array_search($training, $this->trainings);
        if ($index !== false) {
            unset($this->trainings[$index]);
            return true;
        }
        return false;
    }
    public function getItemsByName(string $substring, int $index, int $count, ?string $orderingPropertyName = null, bool $descending = false): array {
        $filteredTrainings = array_filter($this->trainings, function ($training) use ($substring) {
            // Assuming the 'description' field is the one to be searched
            return str_contains(strtolower($training->getDescription()), strtolower($substring));
        });
        // Implement sorting if necessary
        return array_slice($filteredTrainings, $index, $count);
    }

    public function getItemByName(string $substring, int $index, int $count, ?string $orderingPropertyName = null, bool $descending = false): ?Training {
        $filteredTrainings = $this->getItemsByName($substring, $index, $count, $orderingPropertyName, $descending);
        return $filteredTrainings[0] ?? null;
    }
}
