<?php
/**
 * Plugin-wide settings (default zoom, animation duration).
 * Stored in a single option for cheap retrieval.
 */

defined( 'ABSPATH' ) || exit;

class BW_Map_Magnet_Settings {

	const OPTION_KEY = 'bw_map_magnet_settings';

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public static function defaults() {
		return [
			'default_zoom'      => 16,
			'anim_duration'     => 1.5,
			'central_enabled'   => false,
			// Bowden Works (Powell River, BC) — the plugin author's location, used as a placeholder
			// on fresh installs so the preview map shows something meaningful before the user has
			// configured their own location.
			'central_lat'       => 49.688234,
			'central_lng'       => -124.992516,
			'central_title'     => 'Bowden Works',
			'central_icon_mode'        => 'logo',  // 'logo' | 'pin' | 'custom'
			'central_custom_image_id'  => 0,       // attachment ID, used when icon_mode = 'custom'
			'central_color'            => '#f59e0b', // accent — background of the marker (image modes) or pin badge fill.
			'show_distance'     => true,
			'distance_unit'     => 'km',
			'directions_label'  => 'Get directions',
		];
	}

	/**
	 * Get the merged settings (stored + defaults).
	 */
	public static function all() {
		$stored = get_option( self::OPTION_KEY, [] );
		if ( ! is_array( $stored ) ) {
			$stored = [];
		}
		return wp_parse_args( $stored, self::defaults() );
	}

	public static function get( $key ) {
		$all = self::all();
		return isset( $all[ $key ] ) ? $all[ $key ] : null;
	}

	public function boot() {
		add_action( 'admin_menu', [ $this, 'register_page' ] );
		add_action( 'admin_init', [ $this, 'register_settings' ] );
	}

	public function register_page() {
		add_submenu_page(
			'edit.php?post_type=' . BW_MAP_MAGNET_CPT,
			__( 'Map Magnet Settings', 'bw-map-magnet' ),
			__( 'Settings', 'bw-map-magnet' ),
			'manage_options',
			'bw-map-magnet-settings',
			[ $this, 'render_page' ]
		);
	}

	public function register_settings() {
		register_setting(
			'bw_map_magnet_settings_group',
			self::OPTION_KEY,
			[
				'type'              => 'array',
				'sanitize_callback' => [ $this, 'sanitize' ],
				'default'           => self::defaults(),
			]
		);

		add_settings_section(
			'bw_map_magnet_main',
			__( 'Map behaviour', 'bw-map-magnet' ),
			function () {
				echo '<p>' . esc_html__( 'Defaults used by every map on the site. Individual shortcodes/blocks and individual map items can override these.', 'bw-map-magnet' ) . '</p>';
			},
			'bw-map-magnet-settings'
		);

		add_settings_field(
			'default_zoom',
			__( 'Default hover zoom level', 'bw-map-magnet' ),
			[ $this, 'field_default_zoom' ],
			'bw-map-magnet-settings',
			'bw_map_magnet_main'
		);

		add_settings_field(
			'anim_duration',
			__( 'Animation duration (seconds)', 'bw-map-magnet' ),
			[ $this, 'field_anim_duration' ],
			'bw-map-magnet-settings',
			'bw_map_magnet_main'
		);

		add_settings_section(
			'bw_map_magnet_central',
			__( 'Central focus location', 'bw-map-magnet' ),
			function () {
				echo '<p>' . esc_html__( 'A pinned "home" location that stays visible on every map. Hovering an item zooms the map to show both the central location and the hovered item, so visitors can see distance at a glance. Popups can show the distance from this location and a "Get directions" link.', 'bw-map-magnet' ) . '</p>';
			},
			'bw-map-magnet-settings'
		);

		add_settings_field( 'central_enabled',  __( 'Enable central location',   'bw-map-magnet' ), [ $this, 'field_central_enabled'  ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'central_title',    __( 'Label',                     'bw-map-magnet' ), [ $this, 'field_central_title'    ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'central_coords',   __( 'Latitude / Longitude',      'bw-map-magnet' ), [ $this, 'field_central_coords'   ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'central_gmaps',    __( 'Fetch by Google Maps URL',  'bw-map-magnet' ), [ $this, 'field_central_gmaps'    ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'central_icon_mode',        __( 'Marker style',         'bw-map-magnet' ), [ $this, 'field_central_icon_mode'         ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'central_custom_image_id', __( 'Custom image',         'bw-map-magnet' ), [ $this, 'field_central_custom_image'      ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'central_color',           __( 'Marker accent color',  'bw-map-magnet' ), [ $this, 'field_central_color'             ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'show_distance',   __( 'Show distance in popups',     'bw-map-magnet' ), [ $this, 'field_show_distance'   ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'distance_unit',   __( 'Distance unit',               'bw-map-magnet' ), [ $this, 'field_distance_unit'   ], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
		add_settings_field( 'directions_label',__( '"Get directions" label',      'bw-map-magnet' ), [ $this, 'field_directions_label'], 'bw-map-magnet-settings', 'bw_map_magnet_central' );
	}

	public function sanitize( $input ) {
		$defaults = self::defaults();
		$out      = [];

		$zoom = isset( $input['default_zoom'] ) ? (int) $input['default_zoom'] : $defaults['default_zoom'];
		$out['default_zoom'] = max( 6, min( 19, $zoom ) );

		$dur = isset( $input['anim_duration'] ) ? (float) $input['anim_duration'] : $defaults['anim_duration'];
		$out['anim_duration'] = max( 0.1, min( 5.0, $dur ) );

		$out['central_enabled'] = ! empty( $input['central_enabled'] );

		$out['central_lat'] = isset( $input['central_lat'] ) && '' !== $input['central_lat'] ? (float) $input['central_lat'] : 0.0;
		$out['central_lng'] = isset( $input['central_lng'] ) && '' !== $input['central_lng'] ? (float) $input['central_lng'] : 0.0;
		$out['central_lat'] = max( -90.0,  min( 90.0,  $out['central_lat'] ) );
		$out['central_lng'] = max( -180.0, min( 180.0, $out['central_lng'] ) );

		$out['central_title'] = isset( $input['central_title'] ) ? sanitize_text_field( $input['central_title'] ) : '';

		$mode = isset( $input['central_icon_mode'] ) ? sanitize_key( $input['central_icon_mode'] ) : $defaults['central_icon_mode'];
		$out['central_icon_mode'] = in_array( $mode, [ 'logo', 'pin', 'custom' ], true ) ? $mode : $defaults['central_icon_mode'];

		$out['central_custom_image_id'] = isset( $input['central_custom_image_id'] ) ? (int) $input['central_custom_image_id'] : 0;
		if ( $out['central_custom_image_id'] < 0 ) {
			$out['central_custom_image_id'] = 0;
		}

		$color = isset( $input['central_color'] ) ? sanitize_hex_color( $input['central_color'] ) : $defaults['central_color'];
		$out['central_color'] = $color ? $color : $defaults['central_color'];

		$out['show_distance']    = ! empty( $input['show_distance'] );
		$unit = isset( $input['distance_unit'] ) ? strtolower( (string) $input['distance_unit'] ) : 'km';
		$out['distance_unit']    = in_array( $unit, [ 'km', 'mi' ], true ) ? $unit : 'km';
		$out['directions_label'] = isset( $input['directions_label'] ) ? sanitize_text_field( $input['directions_label'] ) : $defaults['directions_label'];

		return $out;
	}

	public function field_default_zoom() {
		$value = (int) self::get( 'default_zoom' );
		?>
		<input type="number" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[default_zoom]" value="<?php echo esc_attr( $value ); ?>" min="6" max="19" step="1" />
		<p class="description">
			<?php esc_html_e( 'Range 6 (world) to 19 (max). 14 ≈ district, 15 ≈ neighbourhood, 16 ≈ street, 17 ≈ buildings, 18 ≈ detailed buildings.', 'bw-map-magnet' ); ?>
		</p>
		<?php
	}

	public function field_anim_duration() {
		$value = (float) self::get( 'anim_duration' );
		?>
		<input type="number" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[anim_duration]" value="<?php echo esc_attr( $value ); ?>" min="0.1" max="5" step="0.1" />
		<p class="description">
			<?php esc_html_e( 'How long the fly-to / zoom-out transitions take. 0.6 s feels snappy; 1.5–2 s feels calm and easier on the eyes; above 3 s drags. Applies to both hover-in and idle-out animations.', 'bw-map-magnet' ); ?>
		</p>
		<?php
	}

	public function render_page() {
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Map Magnet — Settings', 'bw-map-magnet' ); ?></h1>
			<form method="post" action="options.php">
				<?php
				settings_fields( 'bw_map_magnet_settings_group' );
				do_settings_sections( 'bw-map-magnet-settings' );
				submit_button();
				?>
			</form>
			<div id="bw-mm-central-map" style="display:none;width:100%;max-width:720px;height:280px;margin-top:14px;border:1px solid #ccd0d4;border-radius:4px;"></div>
		</div>
		<?php
	}

	public function field_central_enabled() {
		$v = (bool) self::get( 'central_enabled' );
		?>
		<label>
			<input type="checkbox" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_enabled]" value="1" <?php checked( $v ); ?> />
			<?php esc_html_e( 'Show the central location on every map. When off, nothing below this checkbox has any effect.', 'bw-map-magnet' ); ?>
		</label>
		<?php
	}

	public function field_central_title() {
		$v = (string) self::get( 'central_title' );
		?>
		<input type="text" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_title]" id="bw-mm-central-title" value="<?php echo esc_attr( $v ); ?>" style="width:360px;" placeholder="The Regent Grand" />
		<p class="description"><?php esc_html_e( 'Shown on the marker tooltip and used as the origin label on "Get directions" links.', 'bw-map-magnet' ); ?></p>
		<?php
	}

	public function field_central_coords() {
		$lat = self::get( 'central_lat' );
		$lng = self::get( 'central_lng' );
		?>
		<input type="number" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_lat]" id="bw-mm-central-lat" value="<?php echo esc_attr( $lat ); ?>" step="any" min="-90"  max="90"  placeholder="21.795" style="width:160px;" />
		<input type="number" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_lng]" id="bw-mm-central-lng" value="<?php echo esc_attr( $lng ); ?>" step="any" min="-180" max="180" placeholder="-72.183" style="width:160px;" />
		<?php
	}

	public function field_central_gmaps() {
		?>
		<input type="url" id="bw-mm-central-gmaps-url" placeholder="https://maps.app.goo.gl/... or https://www.google.com/maps/place/..." style="width:480px;" />
		<button type="button" class="button button-secondary" id="bw-mm-central-gmaps-btn"><?php esc_html_e( 'Fetch location', 'bw-map-magnet' ); ?></button>
		<span id="bw-mm-central-gmaps-status" class="bw-mm-gmaps-status" aria-live="polite"></span>
		<p class="description"><?php esc_html_e( 'Paste a Google Maps share URL to set the coordinates above.', 'bw-map-magnet' ); ?></p>
		<?php
	}

	public function field_central_icon_mode() {
		$current  = (string) self::get( 'central_icon_mode' );
		$logo_url = self::resolve_logo_url();
		?>
		<fieldset id="bw-mm-central-icon-mode">
			<label style="display:block;margin-bottom:6px;">
				<input type="radio" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_icon_mode]" value="logo" <?php checked( $current, 'logo' ); ?> />
				<?php esc_html_e( 'Site logo', 'bw-map-magnet' ); ?>
				<?php if ( ! $logo_url ) : ?>
					<span style="color:#c2410c; margin-left:6px;"><?php esc_html_e( '(no site logo set — falls back to Pin until you upload one in Customizer → Site Identity)', 'bw-map-magnet' ); ?></span>
				<?php endif; ?>
			</label>
			<label style="display:block;margin-bottom:6px;">
				<input type="radio" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_icon_mode]" value="pin" <?php checked( $current, 'pin' ); ?> />
				<?php esc_html_e( 'Pin (default map-pin icon)', 'bw-map-magnet' ); ?>
			</label>
			<label style="display:block;">
				<input type="radio" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_icon_mode]" value="custom" <?php checked( $current, 'custom' ); ?> />
				<?php esc_html_e( 'Custom image — upload a specific image to use as the marker', 'bw-map-magnet' ); ?>
			</label>
		</fieldset>
		<?php
	}

	public function field_central_custom_image() {
		$image_id  = (int) self::get( 'central_custom_image_id' );
		$image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'medium' ) : '';
		?>
		<div id="bw-mm-central-custom-image-wrap">
			<input type="hidden" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_custom_image_id]" id="bw-mm-central-custom-image-id" value="<?php echo esc_attr( $image_id ); ?>" />
			<div id="bw-mm-central-custom-image-preview" style="margin-bottom:8px;<?php echo $image_url ? '' : 'display:none;'; ?>">
				<?php if ( $image_url ) : ?>
					<img src="<?php echo esc_url( $image_url ); ?>" alt="" style="max-width:120px;max-height:120px;border-radius:6px;border:1px solid #ccd0d4;padding:4px;background:#fff;" />
				<?php endif; ?>
			</div>
			<button type="button" class="button" id="bw-mm-central-custom-image-choose">
				<?php echo $image_id ? esc_html__( 'Replace image', 'bw-map-magnet' ) : esc_html__( 'Choose image', 'bw-map-magnet' ); ?>
			</button>
			<button type="button" class="button-link" id="bw-mm-central-custom-image-clear" style="margin-left:8px;<?php echo $image_id ? '' : 'display:none;'; ?>">
				<?php esc_html_e( 'Remove', 'bw-map-magnet' ); ?>
			</button>
			<p class="description"><?php esc_html_e( 'Only used when Marker style is set to "Custom image". Pick an image from the media library or upload a new one.', 'bw-map-magnet' ); ?></p>
		</div>
		<?php
	}

	/**
	 * Returns the URL of the WP custom logo (Customizer → Site Identity), or '' if none.
	 */
	public static function resolve_logo_url() {
		$logo_id = (int) get_theme_mod( 'custom_logo' );
		if ( ! $logo_id ) {
			return '';
		}
		$url = wp_get_attachment_image_url( $logo_id, 'medium' );
		return $url ? $url : '';
	}

	public function field_central_color() {
		$v = (string) self::get( 'central_color' );
		?>
		<input type="text" class="bw-mm-color-picker" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[central_color]" value="<?php echo esc_attr( $v ); ?>" data-default-color="#f59e0b" />
		<?php
	}

	public function field_show_distance() {
		$v = (bool) self::get( 'show_distance' );
		?>
		<label>
			<input type="checkbox" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[show_distance]" value="1" <?php checked( $v ); ?> />
			<?php esc_html_e( 'Display "X km from <Label>" in each item popup.', 'bw-map-magnet' ); ?>
		</label>
		<?php
	}

	public function field_distance_unit() {
		$v = (string) self::get( 'distance_unit' );
		?>
		<label style="margin-right:14px;">
			<input type="radio" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[distance_unit]" value="km" <?php checked( $v, 'km' ); ?> /> km
		</label>
		<label>
			<input type="radio" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[distance_unit]" value="mi" <?php checked( $v, 'mi' ); ?> /> miles
		</label>
		<?php
	}

	public function field_directions_label() {
		$v = (string) self::get( 'directions_label' );
		?>
		<input type="text" name="<?php echo esc_attr( self::OPTION_KEY ); ?>[directions_label]" value="<?php echo esc_attr( $v ); ?>" style="width:240px;" placeholder="Get directions" />
		<p class="description"><?php esc_html_e( 'Button label in each popup. Opens Google Maps directions from the central location.', 'bw-map-magnet' ); ?></p>
		<?php
	}
}
