<?php
namespace Booktics\Appointment\Schedule;

class Merged_Default_Team_Strategy implements Time_Slot_Strategy {
    /**
     * Generates time slots based on default and team schedule entries
     *
     * @param Schedule_Entry|null $service_entry Optional service schedule entry
     * @param Schedule_Entry|null $team_entry Team member's schedule entry
     * @param Schedule_Entry|null $default_entry Default schedule entry
     * @param Time_Slot_Manager $manager Time slot manager instance
     * @param \DateTime $date Date for which to generate slots
     *
     * @return array Array of Time_Slot objects representing available time slots
     */
    public function generate_slots(
        array $service_entries,
        array $team_entries,
        array $default_entries,
        Time_Slot_Manager $manager,
        \DateTime $date
    ): array {
        $slots = array();
        foreach ( $default_entries as $default_entry ) {
            if ( ! $default_entry || $default_entry->is_holiday() ) {
                continue;
            }
            foreach ( $team_entries as $team_entry ) {
                if ( $team_entry->get_day_of_week() !== $default_entry->get_day_of_week()) {
                    continue;
                }

                if ( ! $team_entry || $team_entry->is_holiday() ) {
                    continue;
                }
                $default_start = strtotime( $default_entry->get_start_time() );
                $default_end   = strtotime( $default_entry->get_end_time() );
                $team_start    = strtotime( $team_entry->get_start_time() );
                $team_end      = strtotime( $team_entry->get_end_time() );

                $start_time = max( $default_start, $team_start );
                $end_time   = min( $default_end, $team_end );

                if ( $start_time >= $end_time ) {
                    continue;
                }

                $slot_length   = $manager->get_slot_length() * 60;
                $before_buffer = $manager->get_before_buffer_time() * 60;
                $after_buffer  = $manager->get_after_buffer_time() * 60;
                $gap           = $before_buffer + $after_buffer;
                $current_start = $start_time;
                while ( $current_start + $slot_length <= $end_time ) {
                    $slot_start = gmdate( 'H:i', $current_start );
                    $slot_end   = gmdate( 'H:i', $current_start + $slot_length );
                    $slots[]    = new Time_Slot( $slot_start, $slot_end, true );
                    $current_start += $slot_length + $gap;
                }
            }
        }
        return $slots;
    }
}
