<?php

namespace SugarCalendarBookings\Availability;

use DateTimeZone;
use SugarCalendarBookings\Employees\EmployeeModel;

/**
 * Working schedule regular rule.
 *
 * @since 1.0.0
 */
class WorkingScheduleWeekdayRule extends AbstractWorkingScheduleRule {

	/**
	 * Weekday.
	 *
	 * @since 1.0.0
	 *
	 * @var int Weekday.
	 */
	private $weekday;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param int                      $weekday   Weekday.
	 * @param array<WorkingPeriodRule> $periods   Periods.
	 * @param DateTimeZone             $time_zone Time zone.
	 * @param EmployeeModel            $employee  Employee model.
	 * @param int                      $priority  Priority.
	 */
	public function __construct( $weekday, $periods, $time_zone, $employee, $priority ) {

		parent::__construct( $periods, $time_zone, $employee, $priority );

		$this->weekday = $weekday;
	}

	/**
	 * Get weekday.
	 *
	 * @since 1.0.0
	 *
	 * @return int Weekday.
	 */
	public function get_weekday() {

		return $this->weekday;
	}

	/**
	 * Create a working schedule regular rule from an array.
	 *
	 * @since 1.0.0
	 *
	 * @param array         $data      Data.
	 * @param DateTimeZone  $time_zone Time zone.
	 * @param EmployeeModel $employee  Employee model.
	 * @param int           $priority  Priority.
	 *
	 * @return WorkingScheduleWeekdayRule|null Working schedule regular rule.
	 */
	public static function from_array( $data, $time_zone, $employee, $priority ) {

		if (
			! isset( $data['weekday'], $data['periods'] ) ||
			! is_numeric( $data['weekday'] ) ||
			! is_array( $data['periods'] )
		) {
			return null;
		}

		$weekday = $data['weekday'];
		$periods = $data['periods'];

		$periods = array_map(
			fn( $period ) => WorkingPeriodRule::from_array( $period, $time_zone, $employee ),
			$periods
		);

		return new self( $weekday, array_filter( $periods ), $time_zone, $employee, $priority );
	}
}
