<?php
declare(strict_types=1);

namespace Booktics\Appointment\Schedule;

use DateTime;

/**
 * Class schedule collection
 */
class Schedule_Collection {
    /**
     * @var mixed
     */
    protected $id;

    /**
     * Store collection of schedules
     *
     * @var Schedule_Entry[]
     */
    private array $entries = array();

    /**
     * Constructor for schedule collections
     *
     * @param array $raw_data
     * @param mixed $id
     */
    public function __construct( array $raw_data, $id = null ) {
        $this->id = $id;
        foreach ( $raw_data as $item ) {
            $this->entries[] = new Schedule_Entry( $item );
        }
    }

    /**
     * Get collection of date entry for matching date
     *
     * @param DateTime $date
     * @return Schedule_Entry[]
     */
    public function get_dates( DateTime $date ): array {
        return array_filter(
            $this->entries, function ( $entry ) use ( $date ) {
				return $entry->matches_date( $date );
			}
        );
    }

    /**
     * Get all schedule entries for the date range
     *
     * @param DateTime $date
     * @return array Array of Schedule_Entry objects
     */
    public function get_first_date( DateTime $date ): array {
        if ( ! is_array( $this->entries ) ) {
            return array();
        }
        $custom_date_entries = array();
        $week_day_entries = array();
        $dow = intval( $date->format( 'N' ) );

        foreach ( $this->entries as $entry ) {
            if ( $entry->get_custom_date() === $date->format( 'Y-m-d' ) ) {
                $custom_date_entries[] = $entry;
            } elseif ( empty( $entry->get_custom_date() ) && (int) $entry->get_day_of_week() === $dow ) {
                $week_day_entries[] = $entry;
            }
        }

        // Prioritize custom date entries over regular weekday entries
        return ! empty( $custom_date_entries ) ? $custom_date_entries : $week_day_entries;
    }
    /**
     * Get id
     *
     * @return mixed
     */
    public function get_id() {
        return $this->id;
    }

    /**
     * Get all entries
     *
     * @return Schedule_Entry[]
     */
    public function get_entries(): array {
        return $this->entries;
    }
}
