<?php

namespace Booktics\Services;

use Booktics\Abstracts\Booktics_Database;

/**
 * Class Schedule_Record
 * Handles schedule record operations and data formatting.
 */
class Schedule_Record {
    /**
     * Formats time string to 12-hour format with AM/PM.
     *
     * @param string $time
     *
     * @return string
     */
    private function format_time( $time ) {
        return date_i18n( 'h:i A', strtotime( get_date_from_gmt( $time ) ) );
    }

    /**
     * Retrieves and formats schedules for a team member or service.
     *
     * @param int $id
     * @param string $type
     *
     * @return array
     */
    public function get_schedules( $id, $type = 'team_member' ) {
        $database = new Booktics_Database();
        if ( 'default' === $type ) {
            $where = array(
				'team_member_id' => 0,
				'service_id' => 0,
			);
        } elseif ( 'team_member' === $type ) {
            $where = array( 'team_member_id' => $id );
        } else {
            $where = array( 'service_id' => $id );
        }

        $schedules = $database->select( booktics_get_table_name( 'booktics_schedules' ), $where );

        $formatted = array(
            'schedule' => array(),
            'custom'   => array(),
            'holiday'  => array(),
        );

        if ( ! is_array( $schedules ) ) {
            return $formatted;
        }

        foreach ( $schedules as $schedule ) {
            if ( '0' == $schedule->custom_date ) {
                $day = strtolower( array_search( $schedule->week_day, Schedule_Manager::$day_map ) );
                if ( '0' == $schedule->start_time && '0' == $schedule->end_time ) {
                    continue;
                }
                $formatted['schedule'][ $day ][] = array(
                    'start_time' => $this->format_time( $schedule->start_time ),
                    'end_time'   => $this->format_time( $schedule->end_time ),
                );
            } elseif ( '0' == $schedule->start_time && '0' == $schedule->end_time ) {
                    $formatted['holiday'][] = $schedule->custom_date;
			} else {
				$formatted['custom'][] = array(
					$schedule->custom_date,
					$schedule->custom_date,
					array(
						'start_time' => $schedule->start_time,
						'end_time'   => $schedule->end_time,
					),
				);
            }
        }

        $formatted['holiday'] = $this->to_ranges( $formatted['holiday'] );

        return $formatted;
    }

    /**
     * Convert single dates into date ranges
     *
     * @param array $dates Array of individual dates
     *
     * @return array Array of date ranges [['start_date', 'end_date']]
     */
    public function to_ranges( $dates ) {
        if ( empty( $dates ) ) {
            return array();
        }

        // Remove duplicates and sort dates
        $dates = array_unique( $dates );
        sort( $dates );

        $ranges = array();
        $start  = $dates[0];
        $prev   = $dates[0];
        $dates_count = count( $dates );

        for ( $i = 1; $i <= $dates_count; $i++ ) {
            $current = $dates[ $i ] ?? null;

            // If we've reached the end or found a gap in dates
            if ( null === $current || strtotime( $current ) > strtotime( '+1 day', strtotime( $prev ) ) ) {
                // Add the range only if start and end are different or it's the last single date
                $ranges[] = array( $start, $prev );
                if ( null !== $current ) {
                    $start = $current;
                }
            }

            if ( null !== $current ) {
                $prev = $current;
            }
        }

        return $ranges;
    }
}
