<?php
/**
 * Demo data seeder for BW Map Magnet — Vancouver Island sample items.
 */

defined( 'ABSPATH' ) || exit;

class BW_Map_Magnet_Seeder {

	private static $instance = null;

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

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

	public function maybe_seed() {
		if ( ! isset( $_POST['bw_map_magnet_action'] ) || 'seed' !== $_POST['bw_map_magnet_action'] ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! isset( $_POST['bw_map_magnet_seed_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['bw_map_magnet_seed_nonce'] ) ), 'bw_map_magnet_seed' ) ) {
			return;
		}

		$created = $this->seed();

		update_option( 'bw_map_magnet_demo_seeded', time() );

		add_action( 'admin_notices', function () use ( $created ) {
			printf(
				'<div class="notice notice-success is-dismissible"><p>%s</p></div>',
				sprintf(
					/* translators: %d: count of seeded items */
					esc_html( _n( '%d demo map item created.', '%d demo map items created.', $created, 'bw-map-magnet' ) ),
					(int) $created
				)
			);
		} );
	}

	private function seed() {
		$created = 0;

		$categories = [
			'free-outdoor-activities' => [
				'name'  => __( 'Free Outdoor Activities', 'bw-map-magnet' ),
				'icon'  => 'palm',
				'color' => '#15803d', // green
			],
			'best-restaurants' => [
				'name'  => __( 'Best Restaurants', 'bw-map-magnet' ),
				'icon'  => 'restaurant',
				'color' => '#c2410c', // burnt orange
			],
		];

		$term_ids = [];
		foreach ( $categories as $slug => $cat ) {
			$existing = get_term_by( 'slug', $slug, BW_MAP_MAGNET_TAX );
			if ( $existing ) {
				$term_ids[ $slug ] = (int) $existing->term_id;
			} else {
				$new = wp_insert_term( $cat['name'], BW_MAP_MAGNET_TAX, [ 'slug' => $slug ] );
				if ( is_wp_error( $new ) ) {
					continue;
				}
				$term_ids[ $slug ] = (int) $new['term_id'];
			}
			// Always (re)set the icon and color so re-seeding upgrades older categories.
			update_term_meta( $term_ids[ $slug ], '_bw_map_icon', $cat['icon'] );
			update_term_meta( $term_ids[ $slug ], '_bw_map_color', $cat['color'] );
		}

		foreach ( $this->items() as $item ) {
			$existing_q = new WP_Query( [
				'post_type'              => BW_MAP_MAGNET_CPT,
				'title'                  => $item['title'],
				'post_status'            => 'any',
				'posts_per_page'         => 1,
				'fields'                 => 'ids',
				'no_found_rows'          => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
			] );

			$image_url = isset( $item['image'] ) ? $item['image'] : '';

			if ( $existing_q->have_posts() ) {
				// Re-seed: upgrade older items with image URLs if missing.
				$existing_id = (int) $existing_q->posts[0];
				if ( $image_url && ! get_post_meta( $existing_id, '_bw_map_image_url', true ) ) {
					update_post_meta( $existing_id, '_bw_map_image_url', $image_url );
				}
				continue;
			}

			$post_id = wp_insert_post( [
				'post_type'    => BW_MAP_MAGNET_CPT,
				'post_status'  => 'publish',
				'post_title'   => $item['title'],
				'post_content' => $item['content'],
				'post_excerpt' => $item['excerpt'],
			] );

			if ( ! $post_id || is_wp_error( $post_id ) ) {
				continue;
			}

			update_post_meta( $post_id, '_bw_map_lat', (float) $item['lat'] );
			update_post_meta( $post_id, '_bw_map_lng', (float) $item['lng'] );

			if ( $image_url ) {
				update_post_meta( $post_id, '_bw_map_image_url', $image_url );
			}

			if ( isset( $term_ids[ $item['category'] ] ) ) {
				wp_set_object_terms( $post_id, [ $term_ids[ $item['category'] ] ], BW_MAP_MAGNET_TAX );
			}

			$created++;
		}

		return $created;
	}

	private function items() {
		return [
			// Free Outdoor Activities.
			[
				'category' => 'free-outdoor-activities',
				'title'    => 'Cathedral Grove (MacMillan Provincial Park)',
				'lat'      => 49.2828,
				'lng'      => -124.6691,
				'image'    => 'https://picsum.photos/seed/cathedral-grove/800/520',
				'excerpt'  => 'Walk among 800-year-old Douglas firs on an easy loop trail on the road between Parksville and Port Alberni.',
				'content'  => "MacMillan Provincial Park protects one of the most accessible stands of old-growth coastal Douglas fir on Vancouver Island. Two short loop trails wind through the grove — including a tree more than nine metres in circumference. Bring a rain jacket; the canopy is dramatic in any weather.",
			],
			[
				'category' => 'free-outdoor-activities',
				'title'    => 'Botanical Beach (Juan de Fuca Park)',
				'lat'      => 48.5290,
				'lng'      => -124.4470,
				'image'    => 'https://picsum.photos/seed/botanical-beach/800/520',
				'excerpt'  => 'Tide-pool wonderland near Port Renfrew — visit at low tide to see purple urchins, anemones and giant chitons in sandstone shelves.',
				'content'  => "Botanical Beach is famous for its sandstone shelf carved with tide pools that fill with intertidal life. Time your visit for a tide of 1.2 m or lower. The Botanical Loop Trail (2.7 km) connects the main beach to Botany Bay through coastal rainforest.",
			],
			[
				'category' => 'free-outdoor-activities',
				'title'    => 'Goldstream Provincial Park',
				'lat'      => 48.4828,
				'lng'      => -123.5500,
				'image'    => 'https://picsum.photos/seed/goldstream-park/800/520',
				'excerpt'  => 'Old-growth cedars, a 47-metre waterfall, and the annual chum salmon run just 16 km from Victoria.',
				'content'  => "Goldstream is a year-round park, but the chum salmon run from late October through December is the headline event. Niagara Falls (the BC one) is a short hike from the day-use area, and the trestle bridge ruins from the original E&N Railway are a popular detour.",
			],
			[
				'category' => 'free-outdoor-activities',
				'title'    => 'Mystic Beach',
				'lat'      => 48.5380,
				'lng'      => -123.9540,
				'image'    => 'https://picsum.photos/seed/mystic-beach/800/520',
				'excerpt'  => 'A 2 km rainforest hike on the Juan de Fuca Trail ends at a sandy cove with a waterfall tumbling onto the beach.',
				'content'  => "Mystic Beach is the southernmost access point on the Juan de Fuca Marine Trail. The trail crosses a suspension bridge and descends through second-growth forest to a wide sandy beach where a small waterfall drops from the cliffs at high tide. Camping is permitted with a backcountry permit.",
			],
			[
				'category' => 'free-outdoor-activities',
				'title'    => 'Mount Douglas Park Summit',
				'lat'      => 48.4945,
				'lng'      => -123.3470,
				'image'    => 'https://picsum.photos/seed/mount-douglas/800/520',
				'excerpt'  => 'A short walk or drive to a 360° viewpoint over Greater Victoria, the Saanich Peninsula and the Olympic Mountains.',
				'content'  => "PKOLS (Mount Douglas) is a 225 m summit ringed by Garry oak meadows. The viewpoint takes in Mount Baker, the Olympic Peninsula, and on clear days the San Juan Islands. The road to the summit closes to vehicles before noon for runners and walkers.",
			],
			[
				'category' => 'free-outdoor-activities',
				'title'    => 'Tow Hill / Long Beach (Pacific Rim)',
				'lat'      => 49.0900,
				'lng'      => -125.7470,
				'image'    => 'https://picsum.photos/seed/long-beach/800/520',
				'excerpt'  => 'Sixteen kilometres of wide sandy beach in Pacific Rim National Park — surf, walk or storm-watch.',
				'content'  => "Long Beach is the heart of Pacific Rim National Park Reserve between Tofino and Ucluelet. Parking requires a Parks Canada day pass, but beach access itself is free. The interpretive boardwalk at Schooner Cove is a quick introduction to coastal rainforest ecology.",
			],

			// Best Restaurants.
			[
				'category' => 'best-restaurants',
				'title'    => 'The Pointe Restaurant (Wickaninnish Inn)',
				'lat'      => 49.0508,
				'lng'      => -125.7350,
				'image'    => 'https://picsum.photos/seed/the-pointe/800/520',
				'excerpt'  => 'Tofino fine dining with floor-to-ceiling Pacific views, focused on West Coast seafood and BC wines.',
				'content'  => "Perched on Chesterman Beach, The Pointe is the flagship restaurant of the Wickaninnish Inn. The menu rotates around what Clayoquot Sound is providing — spot prawns, Dungeness crab, halibut, sablefish — and the wine list leans heavily on the Okanagan and Vancouver Island. Reservations essential.",
			],
			[
				'category' => 'best-restaurants',
				'title'    => 'Red Fish Blue Fish',
				'lat'      => 48.4243,
				'lng'      => -123.3697,
				'image'    => 'https://picsum.photos/seed/red-fish-blue-fish/800/520',
				'excerpt'  => 'Iconic dockside fish-and-chips from a converted shipping container on Victoria\'s Inner Harbour.',
				'content'  => "Red Fish Blue Fish is the Victoria fish-and-chip benchmark. Salmon, halibut, cod and a rotating special — battered or grilled — served in compostable cones with hand-cut chips. Open seasonally; expect a line, but it moves fast.",
			],
			[
				'category' => 'best-restaurants',
				'title'    => 'Pluvio Restaurant + Rooms',
				'lat'      => 49.2280,
				'lng'      => -125.8780,
				'image'    => 'https://picsum.photos/seed/pluvio/800/520',
				'excerpt'  => 'Acclaimed multi-course tasting menu in Ucluelet by chef Warren Barr.',
				'content'  => "Pluvio offers a six-course tasting menu that changes weekly with what local fishers and foragers bring through the door. The dining room is small and the bar is a great place to eat solo. Stay over in one of the four rooms upstairs.",
			],
			[
				'category' => 'best-restaurants',
				'title'    => 'Stage Wine Bar',
				'lat'      => 48.4350,
				'lng'      => -123.3300,
				'image'    => 'https://picsum.photos/seed/stage-wine-bar/800/520',
				'excerpt'  => 'Small-plates and an obsessive wine list in Victoria\'s Fernwood neighbourhood.',
				'content'  => "Stage is a neighbourhood wine bar that takes wine seriously without taking itself too seriously. The menu changes nightly — usually a dozen or so small plates plus a couple of larger shared dishes. Walk-ins welcome at the bar.",
			],
			[
				'category' => 'best-restaurants',
				'title'    => 'Hilary\'s Cheese & Deli',
				'lat'      => 48.7400,
				'lng'      => -123.6190,
				'image'    => 'https://picsum.photos/seed/hilarys-cheese/800/520',
				'excerpt'  => 'Cowichan Bay artisan cheesemaker and lunch spot — start a picnic here.',
				'content'  => "Hilary's makes farmstead cheeses on the spot and runs a deli counter loaded with charcuterie, baguettes and local preserves. Build a picnic and walk it down to the marina, or eat in at the small cafe.",
			],
			[
				'category' => 'best-restaurants',
				'title'    => 'The Aerie (Malahat)',
				'lat'      => 48.5760,
				'lng'      => -123.5530,
				'image'    => 'https://picsum.photos/seed/the-aerie/800/520',
				'excerpt'  => 'A mountainside dining room overlooking the Finlayson Arm and the Gulf Islands.',
				'content'  => "The Aerie reopened in 2024 with a renewed focus on West Coast tasting menus and a serious cocktail program. The view from the terrace at sunset is the headline; the seasonal menu by chef Castro Boateng is the reason to stay.",
			],
		];
	}
}
