<?php
/**
 * Admin functionality for FoodOrd Delivery.
 *
 * @package FoodOrd
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Foodord_Delivery
 */
class Foodord_Delivery {
	/**
	 * Retrieve possible admin page slugs for Delivery settings.
	 *
	 * @return string[]
	 */
	private function get_page_slugs(): array {
		return function_exists( 'foodord_get_settings_page_slugs' )
			? foodord_get_settings_page_slugs( 'delivery' )
			: array( 'foodord-theme-settings-delivery', 'foodord-delivery' );
	}

	/**
	 * Build the admin URL for the Delivery settings page.
	 */
	/**
	 * Build the admin URL for the Delivery settings page.
	 *
	 * @param array $args Optional query args.
	 * @return string
	 */
	private function get_page_url( array $args = array() ): string {
		$base = function_exists( 'foodord_get_admin_page_url' )
			? foodord_get_admin_page_url( 'delivery' )
			: admin_url( 'admin.php?page=foodord-delivery' );

		return empty( $args ) ? $base : add_query_arg( $args, $base );
	}

	/**
	 * Check if license is active.
	 *
	 * @return bool
	 */
	private function is_license_active(): bool {
		return true;
	}

	/**
	 * Time To Deliver instance.
	 *
	 * @var Foodord_Time_To_Deliver
	 */
	private $time_to_deliver;

	/**
	 * Initialize the class.
	 */
	public function __construct() {
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );

		// Initialize Time To Deliver module.
		require_once plugin_dir_path( __FILE__ ) . 'class-foodord-time-to-deliver.php';
		$this->time_to_deliver = new Foodord_Time_To_Deliver();
	}

	/**
	 * Register settings for opening hours.
	 */
	public function register_settings() {
		if ( ! $this->is_license_active() ) {
			return;
		}
		register_setting(
			'foodord_delivery_hours',
			'foodord_opening_hours',
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_opening_hours_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_custom_hours',
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_custom_hours_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_preorder_enabled_delivery',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_yes_no_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_preorder_time_delivery',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_time_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_delivery_fee_type',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_delivery_fee_type_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_delivery_locations',
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_delivery_locations_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_delivery_mode',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_delivery_mode_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_maps_api_key',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_api_key_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_delivery_radius_distance',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_decimal_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_delivery_radius_minimum',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_decimal_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_delivery_radius_fee',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_decimal_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_delivery_radius_zones',
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_radius_zones_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_time_to_deliver_enabled',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_yes_no_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_time_to_deliver_breakdown',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_time_to_deliver_breakdown_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_average_delivery_time',
			array(
				'type'              => 'integer',
				'sanitize_callback' => array( $this, 'sanitize_average_delivery_time_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_scheduled_date_enabled_delivery',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_yes_no_option' ),
			)
		);
		register_setting(
			'foodord_delivery_hours',
			'foodord_scheduled_date_max_days_delivery',
			array(
				'type'              => 'integer',
				'sanitize_callback' => array( $this, 'sanitize_scheduled_date_max_days_option' ),
			)
		);
	}

	/**
	 * Sanitize opening hours option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_opening_hours_option( $value ): array {
		$days      = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );
		$sanitized = array();

		if ( ! is_array( $value ) ) {
			return $sanitized;
		}

		foreach ( $days as $day ) {
			$day_data          = isset( $value[ $day ] ) && is_array( $value[ $day ] ) ? $value[ $day ] : array();
			$closed            = ! empty( $day_data['closed'] );
			$sanitized[ $day ] = array(
				'closed'        => $closed,
				'morning_start' => $closed ? '' : $this->sanitize_time_string( $day_data['morning_start'] ?? '' ),
				'morning_end'   => $closed ? '' : $this->sanitize_time_string( $day_data['morning_end'] ?? '' ),
				'evening_start' => $closed ? '' : $this->sanitize_time_string( $day_data['evening_start'] ?? '' ),
				'evening_end'   => $closed ? '' : $this->sanitize_time_string( $day_data['evening_end'] ?? '' ),
			);
		}

		return $sanitized;
	}

	/**
	 * Sanitize custom hours option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_custom_hours_option( $value ): array {
		if ( ! is_array( $value ) ) {
			return array();
		}

		$sanitized = array();
		foreach ( $value as $entry ) {
			if ( ! is_array( $entry ) ) {
				continue;
			}
			$date_range = $this->normalize_custom_hours_date_range( $entry );
			if ( null === $date_range ) {
				continue;
			}
			$sanitized[] = array(
				'date'          => $date_range['start_date'],
				'start_date'    => $date_range['start_date'],
				'end_date'      => $date_range['end_date'],
				'description'   => isset( $entry['description'] ) ? sanitize_text_field( (string) $entry['description'] ) : '',
				'closed'        => ! empty( $entry['closed'] ),
				'morning_start' => $this->sanitize_time_string( $entry['morning_start'] ?? ( $entry['morningStart'] ?? '' ) ),
				'morning_end'   => $this->sanitize_time_string( $entry['morning_end'] ?? ( $entry['morningEnd'] ?? '' ) ),
				'evening_start' => $this->sanitize_time_string( $entry['evening_start'] ?? ( $entry['eveningStart'] ?? '' ) ),
				'evening_end'   => $this->sanitize_time_string( $entry['evening_end'] ?? ( $entry['eveningEnd'] ?? '' ) ),
			);
		}

		return $sanitized;
	}

	/**
	 * Sanitize HH:MM option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_time_option( $value ): string {
		return $this->sanitize_time_string( $value );
	}

	/**
	 * Sanitize yes/no option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_yes_no_option( $value ): string {
		return 'yes' === $value ? 'yes' : 'no';
	}

	/**
	 * Sanitize delivery fee type.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_delivery_fee_type_option( $value ): string {
		$allowed = array( 'distance', 'location', 'locations', 'zone', 'zones', 'flat' );
		$type    = sanitize_key( (string) $value );
		return in_array( $type, $allowed, true ) ? $type : 'distance';
	}

	/**
	 * Sanitize stored delivery locations.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_delivery_locations_option( $value ): array {
		if ( ! is_array( $value ) ) {
			return array();
		}

		$locations = array();
		foreach ( $value as $location ) {
			if ( ! is_array( $location ) ) {
				continue;
			}
			$city = isset( $location['city'] ) ? sanitize_text_field( (string) $location['city'] ) : '';
			if ( '' === $city ) {
				continue;
			}
			$entry = array(
				'city'    => $city,
				'fee'     => isset( $location['fee'] ) ? sanitize_text_field( (string) $location['fee'] ) : '',
				'minimum' => isset( $location['minimum'] ) ? sanitize_text_field( (string) $location['minimum'] ) : '',
			);
			if ( isset( $location['postal_code'] ) ) {
				$entry['postal_code'] = sanitize_text_field( (string) $location['postal_code'] );
			} elseif ( isset( $location['postalCode'] ) ) {
				$entry['postal_code'] = sanitize_text_field( (string) $location['postalCode'] );
			}
			$locations[] = $entry;
		}

		return $locations;
	}

	/**
	 * Sanitize delivery mode option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_delivery_mode_option( $value ): string {
		$mode = sanitize_key( (string) $value );
		return in_array( $mode, array( 'postal', 'radius' ), true ) ? $mode : 'postal';
	}

	/**
	 * Sanitize API key option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_api_key_option( $value ): string {
		return sanitize_text_field( (string) $value );
	}

	/**
	 * Sanitize decimal-like option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_decimal_option( $value ): string {
		return $this->normalize_decimal_value( $value );
	}

	/**
	 * Sanitize radius zones option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_radius_zones_option( $value ): array {
		if ( ! is_array( $value ) ) {
			return array();
		}

		$zones = array();
		foreach ( $value as $zone ) {
			if ( ! is_array( $zone ) ) {
				continue;
			}
			$radius = $this->normalize_decimal_value( $zone['radius'] ?? '' );
			if ( '' === $radius ) {
				continue;
			}
			$zones[] = array(
				'radius'  => (float) $radius,
				'minimum' => (float) $this->normalize_decimal_value( $zone['minimum'] ?? '' ),
				'fee'     => (float) $this->normalize_decimal_value( $zone['fee'] ?? '' ),
				'label'   => isset( $zone['label'] ) ? sanitize_text_field( (string) $zone['label'] ) : '',
			);
		}

		return $zones;
	}

	/**
	 * Sanitize average delivery time.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_average_delivery_time_option( $value ): int {
		$time = absint( $value );
		if ( $time <= 0 || $time > 480 ) {
			$time = 30;
		}
		return $time;
	}

	/**
	 * Sanitize scheduled date max days option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_scheduled_date_max_days_option( $value ): int {
		$days = absint( $value );
		if ( $days < 1 || $days > 365 ) {
			$days = 7;
		}
		return $days;
	}

	/**
	 * Sanitize time-to-deliver breakdown option.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	public function sanitize_time_to_deliver_breakdown_option( $value ): string {
		$allowed  = array( '5', '10', '15', '20', '30', '45', '60', '90' );
		$selected = sanitize_text_field( (string) $value );
		return in_array( $selected, $allowed, true ) ? $selected : '30';
	}

	/**
	 * Normalize decimal-like strings.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	private function normalize_decimal_value( $value ): string {
		if ( is_scalar( $value ) ) {
			$value = (string) $value;
		} else {
			return '';
		}

		$value = sanitize_text_field( $value );
		$value = str_replace( ',', '.', $value );
		$value = preg_replace( '/[^0-9\.\-]/', '', $value );
		if ( '' === $value ) {
			return '';
		}

		$number = (float) $value;
		if ( $number < 0 ) {
			$number = 0.0;
		}

		return (string) $number;
	}

	/**
	 * Sanitize time strings.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	private function sanitize_time_string( $value ): string {
		if ( ! is_scalar( $value ) ) {
			return '';
		}
		$time = sanitize_text_field( (string) $value );
		return preg_match( '/^\d{2}:\d{2}$/', $time ) ? $time : '';
	}

	/**
	 * Normalize a custom hours date range.
	 *
	 * @param array $entry Custom hours entry.
	 * @return array|null Date range or null when invalid.
	 */
	private function normalize_custom_hours_date_range( array $entry ): ?array {
		$start_date = $this->sanitize_date_string( $entry['start_date'] ?? ( $entry['startDate'] ?? ( $entry['date'] ?? '' ) ) );
		if ( '' === $start_date ) {
			return null;
		}

		$end_date = $this->sanitize_date_string( $entry['end_date'] ?? ( $entry['endDate'] ?? ( $entry['date'] ?? $start_date ) ) );
		if ( '' === $end_date ) {
			$end_date = $start_date;
		}

		if ( $end_date < $start_date ) {
			$initial_start_date = $start_date;
			$start_date         = $end_date;
			$end_date           = $initial_start_date;
		}

		return array(
			'start_date' => $start_date,
			'end_date'   => $end_date,
		);
	}

	/**
	 * Sanitize date strings.
	 *
	 * @param mixed $value Value to sanitize.
	 */
	private function sanitize_date_string( $value ): string {
		if ( ! is_scalar( $value ) ) {
			return '';
		}

		$date = sanitize_text_field( (string) $value );
		if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) ) {
			return '';
		}

		$parsed = date_create_from_format( '!Y-m-d', $date );
		return $parsed && $parsed->format( 'Y-m-d' ) === $date ? $date : '';
	}

	/**
	 * Enqueue admin styles.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_admin_styles( $hook ) {
		if ( ! $this->is_license_active() ) {
			return;
		}

		$matches_page = false;
		foreach ( $this->get_page_slugs() as $slug ) {
			if ( '' !== $slug && false !== strpos( (string) $hook, $slug ) ) {
				$matches_page = true;
				break;
			}
		}

		if ( ! $matches_page ) {
			return;
		}

		wp_enqueue_style(
			'wrc-admin-styles',
			plugin_dir_url( __FILE__ ) . 'css/wrc-admin.css',
			array(),
			FOODORD_VERSION
		);
	}


	/**
	 * Handle form submission.
	 */
	public function handle_form_submission() {
		$nonce = isset( $_POST['wrc_save_hours_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['wrc_save_hours_nonce'] ) ) : '';
		if ( '' === $nonce || ! wp_verify_nonce( $nonce, 'wrc_save_hours' ) ) {
			wp_safe_redirect(
				$this->get_page_url(
					array(
						'saved' => '0',
						'error' => 'nonce',
					)
				)
			);
			exit;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'foodord' ) );
		}

		if ( ! $this->is_license_active() ) {
			wp_die( esc_html__( 'Delivery settings require an active FoodOrd license.', 'foodord' ) );
		}

		$prev_mode            = get_option( 'foodord_delivery_mode', 'postal' );
		$prev_maps_api_key    = get_option( 'foodord_maps_api_key', '' );
		$prev_radius_settings = array(
			'distance' => (string) get_option( 'foodord_delivery_radius_distance', '' ),
			'minimum'  => (string) get_option( 'foodord_delivery_radius_minimum', '' ),
			'fee'      => (string) get_option( 'foodord_delivery_radius_fee', '' ),
			'lat'      => (string) get_option( 'foodord_delivery_radius_center_lat', '' ),
			'lng'      => (string) get_option( 'foodord_delivery_radius_center_lng', '' ),
			'zones'    => Foodord_Location_Service::get_radius_zones(),
		);

		$normalize_decimal = static function ( $value ) {
			if ( '' === $value ) {
				return '';
			}
			if ( function_exists( 'wc_format_decimal' ) ) {
				$formatted = wc_format_decimal( $value );
				$number    = (float) $formatted;
			} else {
				$cleaned = str_replace( ',', '.', (string) $value );
				$cleaned = preg_replace( '/[^0-9\.\-]/', '', $cleaned );
				$number  = (float) $cleaned;
			}
			if ( $number < 0 ) {
				$number = 0.0;
			}
			return (string) $number;
		};

		// Snapshot previous Location Based settings to detect changes.
		$prev_fee_type  = get_option( 'foodord_delivery_fee_type', 'distance' );
		$prev_locations = get_option( 'foodord_delivery_locations', array() );

		$delivery_mode = isset( $_POST['wrc_delivery_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['wrc_delivery_mode'] ) ) : 'postal';
		if ( ! in_array( $delivery_mode, array( 'postal', 'radius' ), true ) ) {
			$delivery_mode = 'postal';
		}
		update_option( 'foodord_delivery_mode', $delivery_mode );

		$maps_api_key = isset( $_POST['wrc_maps_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['wrc_maps_api_key'] ) ) : '';
		update_option( 'foodord_maps_api_key', $maps_api_key );

		$radius_distance = isset( $_POST['wrc_radius_distance'] ) ? $normalize_decimal( sanitize_text_field( wp_unslash( $_POST['wrc_radius_distance'] ) ) ) : '';
		$radius_minimum  = isset( $_POST['wrc_radius_minimum'] ) ? $normalize_decimal( sanitize_text_field( wp_unslash( $_POST['wrc_radius_minimum'] ) ) ) : '';
		$radius_fee      = isset( $_POST['wrc_radius_fee'] ) ? $normalize_decimal( sanitize_text_field( wp_unslash( $_POST['wrc_radius_fee'] ) ) ) : '';

		$radius_zones_raw     = isset( $_POST['wrc_radius_zones'] ) ? sanitize_textarea_field( wp_unslash( $_POST['wrc_radius_zones'] ) ) : '';
		$radius_zones_decoded = json_decode( is_string( $radius_zones_raw ) ? $radius_zones_raw : '', true );
		$radius_zones         = array();

		if ( is_array( $radius_zones_decoded ) ) {
			foreach ( $radius_zones_decoded as $zone ) {
				if ( ! is_array( $zone ) ) {
					continue;
				}

				$raw_radius_source = '';
				if ( isset( $zone['radius'] ) ) {
					$raw_radius_source = (string) $zone['radius'];
				} elseif ( isset( $zone['radius_km'] ) ) {
					$raw_radius_source = (string) $zone['radius_km'];
				} elseif ( isset( $zone['distance'] ) ) {
					$raw_radius_source = (string) $zone['distance'];
				}

				$raw_radius = $normalize_decimal( sanitize_text_field( $raw_radius_source ) );
				if ( '' === $raw_radius ) {
					continue;
				}

				$radius_value = (float) $raw_radius;
				if ( $radius_value <= 0 ) {
					continue;
				}

				$raw_minimum = isset( $zone['minimum'] ) ? $normalize_decimal( sanitize_text_field( (string) $zone['minimum'] ) ) : '';
				$raw_fee     = isset( $zone['fee'] ) ? $normalize_decimal( sanitize_text_field( (string) $zone['fee'] ) ) : '';

				$radius_zones[] = array(
					'radius'  => $radius_value,
					'minimum' => '' === $raw_minimum ? 0.0 : (float) $raw_minimum,
					'fee'     => '' === $raw_fee ? 0.0 : (float) $raw_fee,
					'label'   => isset( $zone['label'] ) ? sanitize_text_field( (string) $zone['label'] ) : '',
				);
			}
		}

		if ( empty( $radius_zones ) && '' !== $radius_distance ) {
			$radius_zones[] = array(
				'radius'  => (float) $radius_distance,
				'minimum' => '' === $radius_minimum ? 0.0 : (float) $radius_minimum,
				'fee'     => '' === $radius_fee ? 0.0 : (float) $radius_fee,
				'label'   => '',
			);
		}

		if ( ! empty( $radius_zones ) ) {
			usort(
				$radius_zones,
				static function ( $a, $b ) {
					$radius_compare = $a['radius'] <=> $b['radius'];
					if ( 0 !== $radius_compare ) {
						return $radius_compare;
					}
					return $a['minimum'] <=> $b['minimum'];
				}
			);
			$radius_zones = array_values( $radius_zones );
		}

		update_option( 'foodord_delivery_radius_zones', $radius_zones );

		$primary_radius  = '';
		$primary_minimum = '';
		$primary_fee     = '';

		if ( ! empty( $radius_zones ) ) {
			$primary_radius  = $normalize_decimal( (string) $radius_zones[0]['radius'] );
			$primary_minimum = $normalize_decimal( (string) $radius_zones[0]['minimum'] );
			$primary_fee     = $normalize_decimal( (string) $radius_zones[0]['fee'] );
		} else {
			$primary_radius  = $radius_distance;
			$primary_minimum = $radius_minimum;
			$primary_fee     = $radius_fee;
		}

		update_option( 'foodord_delivery_radius_distance', $primary_radius );
		update_option( 'foodord_delivery_radius_minimum', $primary_minimum );
		update_option( 'foodord_delivery_radius_fee', $primary_fee );

		if ( 'radius' === $delivery_mode ) {
			Foodord_Location_Service::ensure_radius_center_coordinates( $maps_api_key );
		}

		$radius_settings = array(
			'distance' => $primary_radius,
			'minimum'  => $primary_minimum,
			'fee'      => $primary_fee,
			'lat'      => (string) get_option( 'foodord_delivery_radius_center_lat', '' ),
			'lng'      => (string) get_option( 'foodord_delivery_radius_center_lng', '' ),
			'zones'    => $radius_zones,
		);

		$hours = array();
		$days  = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );

		foreach ( $days as $day ) {
			$closed = isset( $_POST[ $day . '_closed' ] );
			if ( $closed ) {
				$hours[ $day ] = array( 'closed' => true );
			} else {
				$morning_start = isset( $_POST[ $day . '_morning_start' ] ) ? sanitize_text_field( wp_unslash( $_POST[ $day . '_morning_start' ] ) ) : '';
				$morning_end   = isset( $_POST[ $day . '_morning_end' ] ) ? sanitize_text_field( wp_unslash( $_POST[ $day . '_morning_end' ] ) ) : '';
				$evening_start = isset( $_POST[ $day . '_evening_start' ] ) ? sanitize_text_field( wp_unslash( $_POST[ $day . '_evening_start' ] ) ) : '';
				$evening_end   = isset( $_POST[ $day . '_evening_end' ] ) ? sanitize_text_field( wp_unslash( $_POST[ $day . '_evening_end' ] ) ) : '';

				$hours[ $day ] = array(
					'closed'        => false,
					'morning_start' => $morning_start,
					'morning_end'   => $morning_end,
					'evening_start' => $evening_start,
					'evening_end'   => $evening_end,
				);
			}
		}

		update_option( 'foodord_opening_hours', $hours );

		// Handle custom hours.
		$custom_hours = array();
		if ( isset( $_POST['wrc_custom_hours'] ) && is_string( $_POST['wrc_custom_hours'] ) ) {
			$custom_hours_data = json_decode( sanitize_textarea_field( wp_unslash( $_POST['wrc_custom_hours'] ) ), true );
			if ( is_array( $custom_hours_data ) ) {
				foreach ( $custom_hours_data as $custom_hour ) {
					if ( is_array( $custom_hour ) ) {
						$date_range = $this->normalize_custom_hours_date_range( $custom_hour );
						if ( null === $date_range ) {
							continue;
						}
						$custom_hours[] = array(
							'date'          => $date_range['start_date'],
							'start_date'    => $date_range['start_date'],
							'end_date'      => $date_range['end_date'],
							'description'   => sanitize_text_field( $custom_hour['description'] ?? '' ),
							'closed'        => (bool) ( $custom_hour['closed'] ?? false ),
							'morning_start' => sanitize_text_field( $custom_hour['morningStart'] ?? '' ),
							'morning_end'   => sanitize_text_field( $custom_hour['morningEnd'] ?? '' ),
							'evening_start' => sanitize_text_field( $custom_hour['eveningStart'] ?? '' ),
							'evening_end'   => sanitize_text_field( $custom_hour['eveningEnd'] ?? '' ),
						);
					}
				}
			}
		}
		update_option( 'foodord_custom_hours', $custom_hours );

		// Handle preorder settings.
		$preorder_enabled = isset( $_POST['wrc_preorder_enabled_delivery'] );
		$preorder_time    = '';
		if ( $preorder_enabled && isset( $_POST['wrc_preorder_time_delivery'] ) ) {
			$raw_preorder_time = sanitize_text_field( wp_unslash( $_POST['wrc_preorder_time_delivery'] ) );
			if ( preg_match( '/^\d{2}:\d{2}$/', $raw_preorder_time ) ) {
				$preorder_time = $raw_preorder_time;
			}
		}
		update_option( 'foodord_preorder_enabled_delivery', $preorder_enabled ? 'yes' : 'no' );
		update_option( 'foodord_preorder_time_delivery', $preorder_time );

		// Handle delivery fee settings - only location-based delivery is supported.
		$delivery_fee_type = 'distance';
		update_option( 'foodord_delivery_fee_type', $delivery_fee_type );

		// Handle location based settings.
		$delivery_locations = array();
		if ( isset( $_POST['wrc_delivery_locations'] ) ) {
			$raw_locations     = sanitize_textarea_field( wp_unslash( $_POST['wrc_delivery_locations'] ) );
			$decoded_locations = json_decode( $raw_locations, true );
			if ( is_array( $decoded_locations ) ) {
				foreach ( $decoded_locations as $location ) {
					if ( ! is_array( $location ) ) {
						continue;
					}

					$city        = isset( $location['city'] ) ? sanitize_text_field( $location['city'] ) : '';
					$postal_code = '';
					if ( isset( $location['postalCode'] ) ) {
						$postal_code = sanitize_text_field( $location['postalCode'] );
					} elseif ( isset( $location['postal_code'] ) ) {
						$postal_code = sanitize_text_field( $location['postal_code'] );
					}
					$fee_raw     = isset( $location['fee'] ) ? $location['fee'] : '';
					$minimum_raw = isset( $location['minimum'] ) ? $location['minimum'] : '';

					if ( '' === $city ) {
						continue;
					}

					$entry = array(
						'city'    => $city,
						'fee'     => sanitize_text_field( $fee_raw ),
						'minimum' => sanitize_text_field( $minimum_raw ),
					);
					if ( '' !== $postal_code ) {
						$entry['postal_code'] = $postal_code;
					}
					$delivery_locations[] = $entry;
				}
			}
		}
		update_option( 'foodord_delivery_locations', $delivery_locations );

		// Handle time to deliver settings.
		$time_to_deliver_enabled = isset( $_POST['wrc_time_to_deliver_enabled'] );
		update_option( 'foodord_time_to_deliver_enabled', $time_to_deliver_enabled ? 'yes' : 'no' );

		// Handle scheduled date settings.
		$scheduled_date_enabled = isset( $_POST['wrc_scheduled_date_enabled_delivery'] );
		update_option( 'foodord_scheduled_date_enabled_delivery', $scheduled_date_enabled ? 'yes' : 'no' );
		$max_days_ahead = 7;
		if ( isset( $_POST['wrc_scheduled_date_max_days_delivery'] ) ) {
			$max_days_ahead = absint( $_POST['wrc_scheduled_date_max_days_delivery'] );
		}
		if ( $max_days_ahead < 1 || $max_days_ahead > 365 ) {
			$max_days_ahead = 7;
		}
		update_option( 'foodord_scheduled_date_max_days_delivery', $max_days_ahead );

		// Handle time to deliver breakdown setting.
		$breakdown_value = isset( $_POST['wrc_time_to_deliver_breakdown'] ) ? sanitize_text_field( wp_unslash( $_POST['wrc_time_to_deliver_breakdown'] ) ) : '30';
		$allowed_values  = array( '5', '10', '15', '20', '30', '45', '60', '90' );
		if ( in_array( $breakdown_value, $allowed_values, true ) ) {
			update_option( 'foodord_time_to_deliver_breakdown', $breakdown_value );
		}

		// Handle average delivery time setting.
		$average_delivery_time = isset( $_POST['wrc_average_delivery_time'] ) ? absint( $_POST['wrc_average_delivery_time'] ) : 30;
		if ( $average_delivery_time > 480 ) {
			$average_delivery_time = 30; // Default fallback.
		}
		update_option( 'foodord_average_delivery_time', $average_delivery_time );

		// Bump a delivery rules version so frontend sessions invalidate immediately when rules change.
		try {
			$changed = false;
			if ( (string) $prev_mode !== $delivery_mode ) {
				$changed = true;
			}
			if ( (string) $prev_maps_api_key !== $maps_api_key ) {
				$changed = true;
			}
			$prev_radius_json = wp_json_encode( $prev_radius_settings );
			$new_radius_json  = wp_json_encode( $radius_settings );
			if ( $prev_radius_json !== $new_radius_json ) {
				$changed = true;
			}
			if ( $prev_fee_type !== $delivery_fee_type ) {
				$changed = true;
			}
			$prev_loc_json = wp_json_encode( is_array( $prev_locations ) ? $prev_locations : array() );
			$new_loc_json  = wp_json_encode( is_array( $delivery_locations ) ? $delivery_locations : array() );
			if ( $prev_loc_json !== $new_loc_json ) {
				$changed = true;
			}
			if ( $changed ) {
				update_option( 'foodord_delivery_rules_version', time() );
			}
		} catch ( \Throwable $e ) {
			// Do not block saving on failure. Expose via hook for logging.
			do_action( 'foodord_delivery_rules_version_error', $e );
		}

		// Redirect to avoid resubmission and show notice like other pages.
		wp_safe_redirect( $this->get_page_url( array( 'saved' => '1' ) ) );
		exit;
	}

	/**
	 * Get saved opening hours.
	 *
	 * @return array Saved hours or default values.
	 */
	private function get_opening_hours() {
		$default_hours = array(
			'monday'    => array(
				'closed'        => false,
				'morning_start' => '10:00',
				'morning_end'   => '14:00',
				'evening_start' => '16:00',
				'evening_end'   => '22:00',
			),
			'tuesday'   => array(
				'closed'        => false,
				'morning_start' => '10:00',
				'morning_end'   => '14:00',
				'evening_start' => '16:00',
				'evening_end'   => '22:00',
			),
			'wednesday' => array(
				'closed'        => false,
				'morning_start' => '10:00',
				'morning_end'   => '14:00',
				'evening_start' => '16:00',
				'evening_end'   => '22:00',
			),
			'thursday'  => array(
				'closed'        => false,
				'morning_start' => '10:00',
				'morning_end'   => '14:00',
				'evening_start' => '16:00',
				'evening_end'   => '22:00',
			),
			'friday'    => array(
				'closed'        => false,
				'morning_start' => '10:00',
				'morning_end'   => '14:00',
				'evening_start' => '16:00',
				'evening_end'   => '22:00',
			),
			'saturday'  => array(
				'closed'        => false,
				'morning_start' => '10:00',
				'morning_end'   => '14:00',
				'evening_start' => '16:00',
				'evening_end'   => '22:00',
			),
			'sunday'    => array(
				'closed'        => true,
				'morning_start' => '',
				'morning_end'   => '',
				'evening_start' => '',
				'evening_end'   => '',
			),
		);

		return get_option( 'foodord_opening_hours', $default_hours );
	}

	/**
	 * Get saved custom hours.
	 *
	 * @return array Saved custom hours or empty array.
	 */
	private function get_custom_hours() {
		return get_option( 'foodord_custom_hours', array() );
	}

	/**
	 * Get day names in Turkish.
	 *
	 * @return array Day names.
	 */
	private function get_day_names() {
		return array(
			'monday'    => esc_html__( 'Monday', 'foodord' ),
			'tuesday'   => esc_html__( 'Tuesday', 'foodord' ),
			'wednesday' => esc_html__( 'Wednesday', 'foodord' ),
			'thursday'  => esc_html__( 'Thursday', 'foodord' ),
			'friday'    => esc_html__( 'Friday', 'foodord' ),
			'saturday'  => esc_html__( 'Saturday', 'foodord' ),
			'sunday'    => esc_html__( 'Sunday', 'foodord' ),
		);
	}


	/**
	 * Render the Delivery settings page.
	 */
	public function render_delivery_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'foodord' ) );
		}

		if ( ! $this->is_license_active() ) {
			$license_url = function_exists( 'foodord_get_admin_page_url' )
				? foodord_get_admin_page_url( 'license' )
				: admin_url( 'admin.php?page=foodord-license' );
			wp_safe_redirect( $license_url );
			exit;
		}

		// Handle form submission.
		$request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
		if ( 'POST' === $request_method ) {
			$nonce = isset( $_POST['wrc_save_hours_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['wrc_save_hours_nonce'] ) ) : '';
			if ( '' !== $nonce ) {
				if ( wp_verify_nonce( $nonce, 'wrc_save_hours' ) ) {
					$this->handle_form_submission();
				} else {
					wp_safe_redirect(
						$this->get_page_url(
							array(
								'saved' => '0',
								'error' => 'nonce',
							)
						)
					);
					exit;
				}
			}
		}

		$hours = $this->get_opening_hours();

		$custom_hours = $this->get_custom_hours();

		$delivery_mode = get_option( 'foodord_delivery_mode', 'postal' );
		if ( ! in_array( $delivery_mode, array( 'postal', 'radius' ), true ) ) {
			$delivery_mode = 'postal';
		}
		$maps_api_key        = get_option( 'foodord_maps_api_key', '' );
		$radius_settings_all = Foodord_Location_Service::get_radius_settings();
		$radius_zones        = isset( $radius_settings_all['zones'] ) && is_array( $radius_settings_all['zones'] ) ? $radius_settings_all['zones'] : Foodord_Location_Service::get_radius_zones();
		$radius_zones_json   = wp_json_encode( $radius_zones );
		if ( ! is_string( $radius_zones_json ) ) {
			$radius_zones_json = '[]';
		}
		$store_base_address    = isset( $radius_settings_all['store_address'] ) ? (string) $radius_settings_all['store_address'] : Foodord_Location_Service::get_store_address_string();
		$radius_center_lat     = isset( $radius_settings_all['center_lat'] ) && is_numeric( $radius_settings_all['center_lat'] ) ? (float) $radius_settings_all['center_lat'] : '';
		$radius_center_lng     = isset( $radius_settings_all['center_lng'] ) && is_numeric( $radius_settings_all['center_lng'] ) ? (float) $radius_settings_all['center_lng'] : '';
		$radius_map_zones      = isset( $radius_settings_all['zones'] ) && is_array( $radius_settings_all['zones'] ) ? $radius_settings_all['zones'] : array();
		$radius_map_zones_json = wp_json_encode( $radius_map_zones );
		if ( ! is_string( $radius_map_zones_json ) ) {
			$radius_map_zones_json = '[]';
		}

		$day_names             = $this->get_day_names();
		$delivery_fee_type     = get_option( 'foodord_delivery_fee_type', 'distance' );
		$delivery_locations    = get_option( 'foodord_delivery_locations', array() );
		$preorder_enabled      = 'yes' === get_option( 'foodord_preorder_enabled_delivery', 'no' );
		$preorder_time         = get_option( 'foodord_preorder_time_delivery', '' );
		$preorder_class        = $preorder_enabled ? '' : 'wrc-field--preorder-hidden';
		$average_delivery_time = get_option( 'foodord_average_delivery_time', '30' );

		?>
		<div class="wrap">
			<h1 class="wrc-admin-title"><?php esc_html_e( 'Delivery Settings', 'foodord' ); ?></h1>
			<?php
			if ( function_exists( 'foodord_admin_render_horizontal_menu' ) ) {
				foodord_admin_render_horizontal_menu();
			}
			?>
			<?php
			$saved_raw = filter_input( INPUT_GET, 'saved', FILTER_SANITIZE_NUMBER_INT );
			$error_raw = filter_input( INPUT_GET, 'error', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

			$foodord_saved = is_string( $saved_raw ) ? sanitize_text_field( $saved_raw ) : '';
			$foodord_error = is_string( $error_raw ) ? sanitize_text_field( $error_raw ) : '';

			$notice_class   = '';
			$notice_message = '';
			if ( '1' === $foodord_saved ) {
				$notice_class   = 'notice-success';
				$notice_message = esc_html__( 'Settings saved.', 'foodord' );
			} elseif ( '0' === $foodord_saved ) {
				$notice_class = 'notice-error';
				if ( 'nonce' === $foodord_error ) {
					$notice_message = esc_html__( 'Security check failed. Please try again.', 'foodord' );
				} else {
					$notice_message = esc_html__( 'Settings could not be saved. Please try again.', 'foodord' );
				}
			}
			?>
			<?php if ( $notice_message ) : ?>
				<div class="notice <?php echo esc_attr( $notice_class ); ?> is-dismissible"><p class="notice-text"><?php echo esc_html( $notice_message ); ?></p></div>
			<?php endif; ?>
			<div class="wrc-admin-content">
				<form class="wrc-settings-form" method="post" action="">
					<?php wp_nonce_field( 'wrc_save_hours', 'wrc_save_hours_nonce' ); ?>
					<input type="hidden" class="wrc-input" id="wrc_custom_hours" name="wrc_custom_hours" value="<?php echo esc_attr( wp_json_encode( $custom_hours ) ); ?>">
					<input type="hidden" class="wrc-input" id="wrc_delivery_locations" name="wrc_delivery_locations" value="<?php echo esc_attr( wp_json_encode( $delivery_locations ) ); ?>">
					<input type="hidden" class="wrc-input" id="wrc_radius_zones" name="wrc_radius_zones" value="<?php echo esc_attr( $radius_zones_json ); ?>">


				<div class="wrc-opening-hours-container">
						<div class="wrc-opening-hours-header">
							<h2 class="wrc-section-title"><?php esc_html_e( 'Opening Hours', 'foodord' ); ?></h2>
							<p class="wrc-admin-description"><?php esc_html_e( 'Manage your restaurant opening hours and delivery settings from here.', 'foodord' ); ?></p>
						</div>
						
						<div class="wrc-opening-hours-content">
							<?php foreach ( $day_names as $day => $day_name ) : ?>
								<div class="wrc-day-row">
									<div class="wrc-day-label"><?php echo esc_html( $day_name ); ?></div>
									
									<div class="wrc-time-inputs">
										<?php if ( ! $hours[ $day ]['closed'] ) : ?>
											<div class="wrc-time-group">
												<input type="time" class="wrc-time-input"
													name="<?php echo esc_attr( $day . '_morning_start' ); ?>" 
													value="<?php echo esc_attr( $hours[ $day ]['morning_start'] ); ?>">
												<span class="wrc-time-separator">-</span>
												<input type="time" class="wrc-time-input"
													name="<?php echo esc_attr( $day . '_morning_end' ); ?>" 
													value="<?php echo esc_attr( $hours[ $day ]['morning_end'] ); ?>">
											</div>
											
											<span class="wrc-period-separator">/</span>
											
											<div class="wrc-time-group">
												<input type="time" class="wrc-time-input"
													name="<?php echo esc_attr( $day . '_evening_start' ); ?>" 
													value="<?php echo esc_attr( $hours[ $day ]['evening_start'] ); ?>">
												<span class="wrc-time-separator">-</span>
												<input type="time" class="wrc-time-input"
													name="<?php echo esc_attr( $day . '_evening_end' ); ?>" 
													value="<?php echo esc_attr( $hours[ $day ]['evening_end'] ); ?>">
											</div>
										<?php else : ?>
											<div class="wrc-time-group">
												<input type="time" class="wrc-time-input"
													name="<?php echo esc_attr( $day . '_morning_start' ); ?>" 
													value="" 
													disabled>
												<span class="wrc-time-separator">-</span>
												<input type="time" class="wrc-time-input"
													name="<?php echo esc_attr( $day . '_morning_end' ); ?>" 
													value="" 
													disabled>
											</div>
											
											<span class="wrc-period-separator">/</span>
											
											<div class="wrc-time-group">
												<input type="time" class="wrc-time-input"
													name="<?php echo esc_attr( $day . '_evening_start' ); ?>" 
													value="" 
													disabled>
												<span class="wrc-time-separator">-</span>
												<input type="time" class="wrc-time-input"
													name="<?php echo esc_attr( $day . '_evening_end' ); ?>" 
													value="" 
													disabled>
											</div>
										<?php endif; ?>
									</div>
									
									<div class="wrc-closed-checkbox">
										<label class="wrc-closed-label">
											<input type="checkbox" class="wrc-closed-input"
												name="<?php echo esc_attr( $day . '_closed' ); ?>" 
												value="1" 
												<?php checked( $hours[ $day ]['closed'], true ); ?>
												onchange="this.closest('.wrc-day-row').querySelectorAll('.wrc-time-input').forEach(input => input.disabled = this.checked)">
											<?php esc_html_e( 'Closed', 'foodord' ); ?>
										</label>
									</div>
								</div>
							<?php endforeach; ?>
						</div>
					</div>
					
					<div class="wrc-preorder-container">
						<div class="wrc-preorder-header">
							<h2 class="wrc-section-title"><?php esc_html_e( 'Pre-order', 'foodord' ); ?></h2>
							<p class="description"><?php esc_html_e( 'Allow customers to schedule their order for a future time.', 'foodord' ); ?></p>
						</div>
						
						<div class="wrc-preorder-content">
							<div class="wrc-preorder-grid">
								<div class="wrc-preorder-group">
									<div class="wrc-preorder-cell">
										<label class="wrc-field-label" for="wrc_preorder_enabled_delivery"><?php esc_html_e( 'Enable pre-orders', 'foodord' ); ?></label>
										<div class="wrc-control">
											<div class="foodord-toggle-row">
												<label class="foodord-toggle-switch" for="wrc_preorder_enabled_delivery">
													<input type="checkbox" class="wrc-input" id="wrc_preorder_enabled_delivery" name="wrc_preorder_enabled_delivery" value="1" <?php checked( $preorder_enabled, true ); ?> />
													<span class="foodord-toggle-slider"></span>
												</label>
												<span class="foodord-toggle-label"><?php esc_html_e( 'Customers can select a later fulfilment time.', 'foodord' ); ?></span>
											</div>
										</div>
									</div>

									<div class="wrc-preorder-cell <?php echo esc_attr( $preorder_class ); ?>" id="wrc_preorder_time_wrapper_delivery">
										<label class="wrc-field-label" for="wrc_preorder_time_delivery"><?php esc_html_e( 'Earliest pre-order time', 'foodord' ); ?></label>
										<div class="wrc-control">
											<input type="time" id="wrc_preorder_time_delivery" name="wrc_preorder_time_delivery" class="wrc-input" value="<?php echo esc_attr( $preorder_time ); ?>" />
											<p class="wrc-help"><?php esc_html_e( 'Displayed when pre-orders are active.', 'foodord' ); ?></p>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
					
					<div class="wrc-average-delivery-time-container">
						<div class="wrc-average-delivery-time-header">
							<h2 class="wrc-section-title"><?php esc_html_e( 'Average Delivery Time', 'foodord' ); ?></h2>
							<p class="description"><?php esc_html_e( 'Configure estimated delivery time information for customers.', 'foodord' ); ?></p>
						</div>
						
						<div class="wrc-average-delivery-time-content">
							<div class="wrc-average-delivery-time-grid">
								<div class="wrc-average-delivery-time-group">
									<div class="wrc-average-delivery-time-cell">
										<label class="wrc-field-label" for="wrc_average_delivery_time"><?php esc_html_e( 'Average Delivery Time', 'foodord' ); ?></label>
										<div class="wrc-control">
											<input type="number" id="wrc_average_delivery_time" name="wrc_average_delivery_time" class="wrc-input" value="<?php echo esc_attr( $average_delivery_time ); ?>" min="0" max="480" step="1" />
											<p class="wrc-help"><?php esc_html_e( 'Enter the estimated delivery time in minutes.', 'foodord' ); ?></p>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>

					<div class="wrc-custom-hours-container">
						<div class="wrc-custom-hours-header">
							<h2 class="wrc-section-title"><?php esc_html_e( 'Custom Delivery Hours', 'foodord' ); ?></h2>
							<p class="wrc-custom-description"><?php esc_html_e( 'Configure special delivery hours for holidays or custom dates.', 'foodord' ); ?></p>
						</div>
						
						<div class="wrc-custom-hours-content">
					<button type="button" class="button button-secondary wrc-add-custom-hour" id="wrc-add-custom-hour-btn">
							<?php esc_html_e( 'Add Custom Delivery Hours', 'foodord' ); ?>
						</button>
							<div id="wrc-custom-hours-list" class="wrc-custom-hours-list">
								<!-- Custom hour entries will be dynamically added here -->
							</div>
						</div>
					</div>
					
					<?php
					// Render Time To Deliver container.
					$this->time_to_deliver->render_time_to_deliver_container();
					?>

					<div class="wrc-card wrc-delivery-options-container">
						<div class="wrc-card-header">
							<h2 class="wrc-section-title"><?php esc_html_e( 'Delivery Availability', 'foodord' ); ?></h2>
							<p class="description"><?php esc_html_e( 'Configure how customers confirm delivery eligibility and related fees.', 'foodord' ); ?></p>
						</div>
						<div class="wrc-card-body">
							<div class="wrc-delivery-mode-options" id="wrc-delivery-mode-options">
								<label class="wrc-mode-option <?php echo esc_attr( 'postal' === $delivery_mode ? 'is-selected' : '' ); ?>" data-wrc-mode-option="postal">
									<span class="wrc-mode-option__radio">
										<input type="radio" class="wrc-mode-radio" name="wrc_delivery_mode" value="postal" <?php checked( $delivery_mode, 'postal' ); ?> />
									</span>
									<span class="wrc-mode-option__title"><?php esc_html_e( 'City & postal code', 'foodord' ); ?></span>
									<span class="wrc-mode-option__desc"><?php esc_html_e( 'Customers enter city and postal code to check delivery availability.', 'foodord' ); ?></span>
								</label>
								<label class="wrc-mode-option <?php echo esc_attr( 'radius' === $delivery_mode ? 'is-selected' : '' ); ?>" data-wrc-mode-option="radius">
									<span class="wrc-mode-option__radio">
										<input type="radio" class="wrc-mode-radio" name="wrc_delivery_mode" value="radius" <?php checked( $delivery_mode, 'radius' ); ?> />
									</span>
									<span class="wrc-mode-option__title"><?php esc_html_e( 'Google Maps radius', 'foodord' ); ?></span>
									<span class="wrc-mode-option__desc"><?php esc_html_e( 'Customers enter an address validated against your configured radius.', 'foodord' ); ?></span>
								</label>
							</div>

							<div class="wrc-mode-section <?php echo esc_attr( 'postal' === $delivery_mode ? 'is-mode-active' : '' ); ?>" data-wrc-mode-section="postal">
								<div class="wrc-delivery-options-content">
									<div class="wrc-field">
								<div id="wrc-location-based" class="wrc-location-based is-active" aria-live="polite" data-city-label="<?php echo esc_attr__( 'City', 'foodord' ); ?>" data-city-placeholder="<?php echo esc_attr__( 'e.g. Ankara', 'foodord' ); ?>" data-fee-label="<?php echo esc_attr__( 'Delivery Fee', 'foodord' ); ?>" data-fee-placeholder="<?php echo esc_attr__( 'e.g. 5.00', 'foodord' ); ?>" data-minimum-label="<?php echo esc_attr__( 'Minimum Order amount', 'foodord' ); ?>" data-minimum-placeholder="<?php echo esc_attr__( 'e.g. 10.00', 'foodord' ); ?>" data-remove-label="<?php echo esc_attr__( 'Remove location', 'foodord' ); ?>" data-remove-text="<?php echo esc_attr__( 'Remove', 'foodord' ); ?>">
											<p class="wrc-location-description"><?php esc_html_e( 'Define delivery areas by city and postal code.', 'foodord' ); ?></p>
											<div id="wrc-location-list" class="wrc-location-list" data-empty-message="<?php echo esc_attr__( 'No locations added yet. Use the button below to add one.', 'foodord' ); ?>"></div>
											<button type="button" class="button button-secondary wrc-add-location" id="wrc-add-location-btn">
												<?php esc_html_e( 'Add New Location', 'foodord' ); ?>
											</button>
										</div>
									</div>
								</div>
							</div>

							<div class="wrc-mode-section <?php echo esc_attr( 'radius' === $delivery_mode ? 'is-mode-active' : '' ); ?>" data-wrc-mode-section="radius">
								<div class="wrc-radius-info">
									<p class="wrc-radius-store-address">
										<span class="wrc-radius-store-address__label"><?php esc_html_e( 'Store base address', 'foodord' ); ?>:</span>
										<span class="wrc-radius-store-address__value"><?php echo esc_html( $store_base_address ); ?></span>
									</p>
								</div>
								<div class="wrc-form wrc-radius-form">
									<div class="wrc-field">
										<label class="wrc-label" for="wrc_maps_api_key"><?php esc_html_e( 'Google Maps API key', 'foodord' ); ?></label>
										<div class="wrc-control">
											<input type="text" id="wrc_maps_api_key" name="wrc_maps_api_key" class="wrc-input regular-text" value="<?php echo esc_attr( $maps_api_key ); ?>" autocomplete="off" />
											<p class="wrc-help wrc-help--nowrap"><?php esc_html_e( 'Create an API key: https://console.cloud.google.com/apis/credentials', 'foodord' ); ?></p>
										</div>
									</div>
								<div class="wrc-field">
									<div id="wrc-radius-zones" class="wrc-radius-zones" data-radius-label="<?php echo esc_attr__( 'Radius (km)', 'foodord' ); ?>" data-radius-placeholder="<?php echo esc_attr__( 'e.g. 5', 'foodord' ); ?>" data-minimum-label="<?php echo esc_attr__( 'Minimum order', 'foodord' ); ?>" data-minimum-placeholder="<?php echo esc_attr__( 'e.g. 10.00', 'foodord' ); ?>" data-fee-label="<?php echo esc_attr__( 'Delivery fee', 'foodord' ); ?>" data-fee-placeholder="<?php echo esc_attr__( 'e.g. 1.50', 'foodord' ); ?>" data-label-label="<?php echo esc_attr__( 'Label (optional)', 'foodord' ); ?>" data-label-placeholder="<?php echo esc_attr__( 'e.g. Inner city', 'foodord' ); ?>" data-remove-label="<?php echo esc_attr__( 'Remove radius zone', 'foodord' ); ?>" data-remove-text="<?php echo esc_attr__( 'Remove', 'foodord' ); ?>" data-title-placeholder="<?php echo esc_attr__( 'Radius zone', 'foodord' ); ?>">
										<p class="wrc-radius-description"><?php esc_html_e( 'Define one or more delivery zones based on distance from your store. Zones are matched from the smallest radius upwards.', 'foodord' ); ?> <span class="wrc-radius-description__note"><?php esc_html_e( 'When multiple zones use the same radius, the cart total selects the matching minimum and delivery fee tier.', 'foodord' ); ?></span></p>
										<div id="wrc-radius-zone-list" class="wrc-radius-zone-list" data-empty-message="<?php echo esc_attr__( 'No radius zones added yet. Use the button below to add one.', 'foodord' ); ?>"></div>
										<button type="button" class="button button-secondary wrc-add-radius-zone" id="wrc-add-radius-zone-btn">
											<?php esc_html_e( 'Add radius zone', 'foodord' ); ?>
										</button>
									</div>
								</div>
								<div class="wrc-field">
									<div id="wrc-radius-map" class="wrc-radius-map" data-center-lat="<?php echo esc_attr( $radius_center_lat ); ?>" data-center-lng="<?php echo esc_attr( $radius_center_lng ); ?>" data-zones="<?php echo esc_attr( $radius_map_zones_json ); ?>" data-api-key="<?php echo esc_attr( $maps_api_key ); ?>" data-store-address="<?php echo esc_attr( $store_base_address ); ?>">
										<div class="wrc-radius-map__placeholder"><?php esc_html_e( 'Map preview will appear here once Google Maps is configured.', 'foodord' ); ?></div>
									</div>
								</div>
						</div>
					</div>
				</div>
			</div>
		
		<?php submit_button( esc_html__( 'Save Changes', 'foodord' ), 'primary', 'wrc_save_hours' ); ?>
				</form>
			</div>
		</div>
		
		<!-- Custom Hours Modal -->
		<div id="wrc-custom-hours-modal" class="foodord-modal">
			<div class="foodord-modal__content">
				<div class="foodord-modal__header">
					<h3 class="foodord-modal__title" data-add-title="<?php echo esc_attr__( 'Add Custom Delivery Hours', 'foodord' ); ?>" data-edit-title="<?php echo esc_attr__( 'Edit Custom Delivery Hours', 'foodord' ); ?>">
						<?php esc_html_e( 'Add Custom Delivery Hours', 'foodord' ); ?>
					</h3>
					<button type="button" class="foodord-modal__close" id="wrc-modal-close-btn">
						<span class="dashicons dashicons-no-alt"></span>
					</button>
				</div>
				
				<div class="foodord-modal__body">
					<form id="wrc-custom-hours-form" class="wrc-modal-form">
						<div class="wrc-field">
							<label class="wrc-field-label" for="custom-start-date"><?php esc_html_e( 'Start Date', 'foodord' ); ?></label>
							<input type="date" id="custom-start-date" name="custom-start-date" class="regular-text" required>
						</div>

						<div class="wrc-field">
							<label class="wrc-field-label" for="custom-end-date"><?php esc_html_e( 'End Date', 'foodord' ); ?></label>
							<input type="date" id="custom-end-date" name="custom-end-date" class="regular-text">
						</div>

						<div class="wrc-field">
							<label class="wrc-field-label" for="custom-description"><?php esc_html_e( 'Description', 'foodord' ); ?></label>
							<input type="text" id="custom-description" name="custom-description" class="regular-text" placeholder="<?php esc_attr_e( 'e.g., New Year, Holiday', 'foodord' ); ?>">
						</div>
						
						<div class="wrc-field wrc-field--toggle">
							<div class="wrc-toggle-container">
								<label class="wrc-toggle-switch">
									<span class="wrc-toggle-label"><?php esc_html_e( 'Closed', 'foodord' ); ?></span>
									<div class="wrc-toggle-switch-control">
								<input class="wrc-toggle-input" type="checkbox" id="custom-closed" name="custom-closed">
										<span class="wrc-toggle-slider"></span>
									</div>
								</label>
							</div>
						</div>
						
						<div id="custom-time-inputs" class="wrc-custom-time-inputs">
							<div class="wrc-time-row">
								<label class="wrc-time-label"><?php esc_html_e( 'Morning Hours', 'foodord' ); ?></label>
								<div class="wrc-time-group">
									<input type="time" id="custom-morning-start" name="custom-morning-start" class="wrc-time-input">
									<span class="wrc-time-separator">-</span>
									<input type="time" id="custom-morning-end" name="custom-morning-end" class="wrc-time-input">
								</div>
							</div>
							
							<div class="wrc-time-row">
								<label class="wrc-time-label"><?php esc_html_e( 'Evening Hours', 'foodord' ); ?></label>
								<div class="wrc-time-group">
									<input type="time" id="custom-evening-start" name="custom-evening-start" class="wrc-time-input">
									<span class="wrc-time-separator">-</span>
									<input type="time" id="custom-evening-end" name="custom-evening-end" class="wrc-time-input">
								</div>
							</div>
						</div>
				</form>
				</div>

				<div class="foodord-modal__actions">
					<button type="button" class="foodord-modal__button foodord-modal__button--cancel" id="wrc-modal-cancel-btn">
						<?php esc_html_e( 'Cancel', 'foodord' ); ?>
					</button>
					<button type="button" class="foodord-modal__button foodord-modal__button--confirm" id="wrc-modal-save-btn" data-add-label="<?php echo esc_attr__( 'Add Delivery Hours', 'foodord' ); ?>" data-update-label="<?php echo esc_attr__( 'Save changes', 'foodord' ); ?>">
						<?php esc_html_e( 'Add Delivery Hours', 'foodord' ); ?>
					</button>
				</div>
			</div>
		</div>
		<?php
	}
}
