<?php
/**
 * Class representing a day time period.
 *
 * @package flo-sync
 */

namespace NMFS\Sync\Items\Article_Availabilities\Models\Schedules\Periods;

use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Interfaces\JsonUnserializable;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Traits\Json_Decode_Trait;

/**
 * Class Day_Time_Period_Model
 */
class Day_Time_Period_Model implements JsonUnserializable {
	use Json_Decode_Trait;

	/**
	 * Start hour of the time period.
	 *
	 * @var int
	 */
	public int $start_time_hour;

	/**
	 * Start minute of the time period.
	 *
	 * @var string
	 */
	public string $start_time_minute;

	/**
	 * End hour of the time period.
	 *
	 * @var int
	 */
	public int $end_time_hour;

	/**
	 * End minute of the time period.
	 *
	 * @var string
	 */
	public string $end_time_minute;

	/**
	 * Check if the current time is within the time range.
	 *
	 * @return bool.
	 */
	public function is_now_within_time_range(): bool {
		$hour_now   = (int) current_time( 'H' );
		$minute_now = (int) current_time( 'i' );

		if ( $hour_now < $this->start_time_hour || $hour_now > $this->end_time_hour ) {
			return false;
		}

		if ( $hour_now === $this->start_time_hour && $minute_now < $this->start_time_minute ) {
			return false;
		}

		if ( $hour_now === $this->end_time_hour && $minute_now > $this->end_time_minute ) {
			return false;
		}

		return true;
	}

	/**
	 * Specify data which should be serialized to JSON
	 */
	public function jsonSerialize(): array {
		return array(
			'start_time_hour'   => $this->start_time_hour,
			'start_time_minute' => $this->start_time_minute,
			'end_time_hour'     => $this->end_time_hour,
			'end_time_minute'   => $this->end_time_minute,
		);
	}

	/**
	 * Takes a JSON string matching what is returned by jsonSerialize() and returns an instance of the class.
	 *
	 * @param string|array $data JSON data. This is either a JSON string or an already decoded array.
	 *
	 * @return static|null The instance of the class, or null if the data is invalid.
	 */
	public static function jsonUnserialize( string|array $data ): ?static {
		$data = self::decode_json_data( $data );
		if ( ! $data ) {
			return null;
		}

		$instance                    = new self();
		$instance->start_time_hour   = (int) $data['start_time_hour'];
		$instance->start_time_minute = (string) $data['start_time_minute'];
		$instance->end_time_hour     = (int) $data['end_time_hour'];
		$instance->end_time_minute   = (string) $data['end_time_minute'];

		return $instance;
	}
}
