<?php
/**
 * The WooCommerce settings tab UI. Stored as a single option array `datery_settings`.
 *
 * @package Datery
 */

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'WC_Settings_Page' ) ) {
	return;
}

class Datery_Settings_Page extends WC_Settings_Page {

	public function __construct() {
		$this->id    = 'datery_delivery_date';
		$this->label = __( 'Delivery Date', 'datery-delivery-date-for-woocommerce' );
		parent::__construct();
	}

	/**
	 * Sections shown as sub-tabs. Pro registers its own via the filter.
	 */
	public function get_sections() {
		$sections = array( '' => __( 'General', 'datery-delivery-date-for-woocommerce' ) );
		return apply_filters( 'datery_settings_sections', $sections );
	}

	private function get_current_section() {
		global $current_section;
		if ( ! empty( $current_section ) ) {
			return sanitize_title( $current_section );
		}
		// Read-only tab routing, no state change. phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return isset( $_REQUEST['section'] ) ? sanitize_title( wp_unslash( $_REQUEST['section'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	}

	public function get_settings_for_default_section() {
		$current = get_option( 'datery_settings', array() );

		return array(
			array(
				'title' => __( 'Delivery Date', 'datery-delivery-date-for-woocommerce' ),
				'type'  => 'title',
				'desc'  => __( 'Show a delivery date picker on the checkout page.', 'datery-delivery-date-for-woocommerce' ),
				'id'    => 'datery_section',
			),
			array(
				'title'    => __( 'Field label', 'datery-delivery-date-for-woocommerce' ),
				'id'       => 'datery_settings[field_label]',
				'type'     => 'text',
				'default'  => __( 'Delivery date', 'datery-delivery-date-for-woocommerce' ),
				'value'    => isset( $current['field_label'] ) ? $current['field_label'] : __( 'Delivery date', 'datery-delivery-date-for-woocommerce' ),
			),
			array(
				'title'    => __( 'Required', 'datery-delivery-date-for-woocommerce' ),
				'desc'     => __( 'Customer must choose a delivery date to place the order.', 'datery-delivery-date-for-woocommerce' ),
				'id'       => 'datery_settings[required]',
				'type'     => 'checkbox',
				'default'  => 'yes',
				'value'    => isset( $current['required'] ) ? $current['required'] : 'yes',
			),
			array(
				'title'             => __( 'Minimum lead time (days)', 'datery-delivery-date-for-woocommerce' ),
				'desc'              => __( 'Earliest selectable date = today + this many days.', 'datery-delivery-date-for-woocommerce' ),
				'id'                => 'datery_settings[min_lead_days]',
				'type'              => 'number',
				'default'           => 1,
				'value'             => isset( $current['min_lead_days'] ) ? $current['min_lead_days'] : 1,
				'custom_attributes' => array( 'min' => '0', 'step' => '1' ),
			),
			array(
				'title'             => __( 'Booking window (days ahead)', 'datery-delivery-date-for-woocommerce' ),
				'desc'              => __( 'Latest selectable date = today + this many days.', 'datery-delivery-date-for-woocommerce' ),
				'id'                => 'datery_settings[max_days]',
				'type'              => 'number',
				'default'           => 30,
				'value'             => isset( $current['max_days'] ) ? $current['max_days'] : 30,
				'custom_attributes' => array( 'min' => '1', 'step' => '1' ),
			),
			array(
				'title'    => __( 'Same-day cutoff time', 'datery-delivery-date-for-woocommerce' ),
				'desc'     => __( 'Orders placed after this time push the earliest date one extra day forward. Leave empty to disable. Format HH:MM (store timezone).', 'datery-delivery-date-for-woocommerce' ),
				'id'       => 'datery_settings[cutoff_time]',
				'type'     => 'text',
				'default'  => '',
				'value'    => isset( $current['cutoff_time'] ) ? $current['cutoff_time'] : '',
				'css'      => 'width:80px;',
				'placeholder' => '14:00',
			),
			array(
				'type' => 'sectionend',
				'id'   => 'datery_section',
			),
		);
	}

	/**
	 * Persist settings for the section being saved.
	 */
	public function save() {
		$section = $this->get_current_section();
		if ( '' !== $section ) {
			// Pro (and any future section) handles its own persistence.
			do_action( 'datery_save_settings_' . sanitize_key( $section ) );
			return;
		}

		// WooCommerce verifies the 'woocommerce-settings' nonce in WC_Admin_Settings::save() before calling this method.
		// Each field is sanitized individually when building $clean below.
		$raw = isset( $_POST['datery_settings'] ) ? (array) wp_unslash( $_POST['datery_settings'] ) : array(); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

		$clean = array(
			'field_label'   => isset( $raw['field_label'] ) ? sanitize_text_field( $raw['field_label'] ) : __( 'Delivery date', 'datery-delivery-date-for-woocommerce' ),
			'required'      => ( isset( $raw['required'] ) && '1' === (string) $raw['required'] ) ? 'yes' : 'no',
			'min_lead_days' => isset( $raw['min_lead_days'] ) ? max( 0, absint( $raw['min_lead_days'] ) ) : 1,
			'max_days'      => isset( $raw['max_days'] ) ? max( 1, absint( $raw['max_days'] ) ) : 30,
			'cutoff_time'   => isset( $raw['cutoff_time'] ) ? $this->sanitize_time( $raw['cutoff_time'] ) : '',
		);

		update_option( 'datery_settings', $clean );
	}

	private function sanitize_time( $value ) {
		$value = trim( (string) $value );
		if ( '' === $value ) {
			return '';
		}
		return preg_match( '/^([01]\d|2[0-3]):([0-5]\d)$/', $value ) ? $value : '';
	}
}
