<?php
namespace SabaiApps\Directories\Component\Form\Field;

use SabaiApps\Directories\Component\Form\Form;

/**
 * MonthPickerField provides a date picker for selecting a month.
 * Handles initialization and calendar widget configuration.
 */
class MonthPickerField extends AbstractDatePickerField {

	/**
	 * Initializes the MonthPicker field with a placeholder.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		$data['#placeholder'] = __( 'Select month', 'directories-pro' );
		parent::formFieldInit( $name, $data, $form );
	}

	/**
	 * Returns the configuration options for the calendar widget for month selection.
	 *
	 * @param array $data
	 * @return array
	 */
	protected function _getCalendarOptions( array $data ) {
		$options         = parent::_getCalendarOptions( $data );
		$options['type'] = 'month';
		if ( ! empty( $data['#default_value'] ) ) {
			if ( is_int( $data['#default_value'] ) ) {
				if ( $data['#default_value'] !== $data['#empty_value'] ) {
					$options['settings']['selected']['dates'] = array( date( 'Y-m-d', $data['#default_value'] ) );
				}
			} elseif ( is_string( $data['#default_value'] ) ) {
				// only date
				$options['settings']['selected']['dates'] = array( $data['#default_value'] );
			}
			if ( ! empty( $options['settings']['selected']['dates'] ) ) {
				$first_date_parts                         = explode( '-', $options['settings']['selected']['dates'][0] );
				$options['settings']['selected']['year']  = $first_date_parts[0];
				$options['settings']['selected']['month'] = $first_date_parts[1] - 1;
			}
		}

		return $options;
	}
}
