<?php
/**
 * Idempotent Foliora catalog + pages + menus. Run via: wp eval-file inc/cli-seed.php
 *
 * @package Foliora
 */

if ( ! defined( 'WP_CLI' ) && php_sapi_name() !== 'cli' ) {
	fwrite( STDERR, "Run with WP-CLI: wp eval-file inc/cli-seed.php\n" );
	return;
}

if ( ! class_exists( 'WooCommerce' ) ) {
	WP_CLI::error( 'WooCommerce must be active first.' );
}

/**
 * Insert or update a page by slug.
 *
 * @param string $slug    Slug.
 * @param string $title   Title.
 * @param string $content Content.
 * @return int
 */
function foliora_seed_page( $slug, $title, $content ) {
	$existing = get_page_by_path( $slug );
	if ( $existing ) {
		wp_update_post(
			array(
				'ID'           => $existing->ID,
				'post_title'   => $title,
				'post_content' => $content,
				'post_status'  => 'publish',
			)
		);
		return (int) $existing->ID;
	}
	return (int) wp_insert_post(
		array(
			'post_title'   => $title,
			'post_name'    => $slug,
			'post_content' => $content,
			'post_status'  => 'publish',
			'post_type'    => 'page',
		)
	);
}

/**
 * Import a theme image once.
 *
 * @param string $filename File in assets/images.
 * @return int
 */
function foliora_seed_media( $filename ) {
	$q = new WP_Query(
		array(
			'post_type'      => 'attachment',
			'post_status'    => 'inherit',
			'posts_per_page' => 1,
			'meta_key'       => '_foliora_source',
			'meta_value'     => $filename,
			'fields'         => 'ids',
		)
	);
	if ( $q->posts ) {
		return (int) $q->posts[0];
	}

	$path = get_theme_file_path( 'assets/images/' . $filename );
	if ( ! file_exists( $path ) ) {
		return 0;
	}

	require_once ABSPATH . 'wp-admin/includes/file.php';
	require_once ABSPATH . 'wp-admin/includes/media.php';
	require_once ABSPATH . 'wp-admin/includes/image.php';

	$tmp = wp_tempnam( $filename );
	copy( $path, $tmp );
	$file = array(
		'name'     => $filename,
		'tmp_name' => $tmp,
	);
	$id = media_handle_sideload( $file, 0, sanitize_title( pathinfo( $filename, PATHINFO_FILENAME ) ) );
	if ( is_wp_error( $id ) ) {
		@unlink( $tmp );
		return 0;
	}
	update_post_meta( $id, '_foliora_source', $filename );
	return (int) $id;
}

/**
 * Ensure a product category.
 *
 * @param string $slug Slug.
 * @param string $name Name.
 * @return int
 */
function foliora_seed_cat( $slug, $name ) {
	$term = get_term_by( 'slug', $slug, 'product_cat' );
	if ( $term && ! is_wp_error( $term ) ) {
		return (int) $term->term_id;
	}
	$created = wp_insert_term( $name, 'product_cat', array( 'slug' => $slug ) );
	if ( is_wp_error( $created ) ) {
		return 0;
	}
	return (int) $created['term_id'];
}

/**
 * Ensure a global attribute and terms.
 *
 * @param string   $slug  pa_ slug without prefix.
 * @param string   $label Label.
 * @param string[] $terms Terms.
 * @return int Attribute id.
 */
function foliora_seed_attribute( $slug, $label, $terms ) {
	$taxonomy = 'pa_' . $slug;
	$id       = wc_attribute_taxonomy_id_by_name( $slug );
	if ( ! $id ) {
		$id = wc_create_attribute(
			array(
				'name'         => $label,
				'slug'         => $slug,
				'type'         => 'select',
				'order_by'     => 'menu_order',
				'has_archives' => false,
			)
		);
	}
	register_taxonomy( $taxonomy, array( 'product' ) );
	foreach ( $terms as $term ) {
		if ( ! term_exists( $term, $taxonomy ) ) {
			wp_insert_term( $term, $taxonomy );
		}
	}
	return (int) $id;
}

/**
 * Create or update a simple product.
 *
 * @param array $data Product data.
 * @return int
 */
function foliora_seed_simple( $data ) {
	$id = wc_get_product_id_by_sku( $data['sku'] );
	$product = $id ? wc_get_product( $id ) : new WC_Product_Simple();
	if ( ! $product ) {
		$product = new WC_Product_Simple();
	}
	$product->set_name( $data['name'] );
	$product->set_sku( $data['sku'] );
	$product->set_regular_price( (string) $data['regular'] );
	if ( ! empty( $data['sale'] ) ) {
		$product->set_sale_price( (string) $data['sale'] );
	} else {
		$product->set_sale_price( '' );
	}
	$product->set_short_description( $data['short'] );
	$product->set_catalog_visibility( 'visible' );
	$product->set_status( 'publish' );
	$product->set_stock_status( 'instock' );
	if ( ! empty( $data['image'] ) ) {
		$product->set_image_id( $data['image'] );
	}
	if ( ! empty( $data['gallery'] ) ) {
		$product->set_gallery_image_ids( $data['gallery'] );
	}
	$product->set_category_ids( $data['cats'] );
	$saved = $product->save();
	update_post_meta( $saved, '_foliora_badge', $data['badge'] );
	update_post_meta( $saved, '_foliora_eyebrow', $data['eyebrow'] );
	update_post_meta( $saved, '_foliora_rating_display', '4.8 (126)' );
	if ( ! empty( $data['hover'] ) ) {
		update_post_meta( $saved, '_foliora_hover_image', $data['hover'] );
	}
	return $saved;
}

$home_id = foliora_seed_page(
	'home',
	'Home',
	''
);
$story_id = foliora_seed_page(
	'our-story',
	'Our Story',
	"<p>Foliora began with a simple wish: that the hour you steal for a book could feel a little more considered. A warmer light. A sleeve that keeps the cover looking like itself. A mark that says this copy is yours.</p><p>We make reading accessories for slower evenings — not more stuff, just the few objects we would actually want beside our own books.</p><p>Make every reading moment feel special.</p>"
);
foliora_seed_page(
	'shipping',
	'Shipping',
	'<p>Most orders leave within 2–4 business days. Free shipping on orders $50+ within the United States.</p><p>You will receive a note when your parcel is on its way. International shipping is quoted at checkout when available.</p>'
);
foliora_seed_page(
	'returns',
	'Returns',
	'<p>30 days, unused and in original condition. Personalized pieces made to order cannot be returned unless they arrive damaged.</p><p>Write to us and we will help you send it back — simply, without a performance.</p>'
);
foliora_seed_page(
	'faq',
	'FAQ',
	'<h2>Will my book fit?</h2><p>Sleeves come in Paperback, Hardcover and Kindle. When in doubt, size up.</p><h2>How long does shipping take?</h2><p>Most orders leave within 2–4 business days. Free shipping on $50+.</p><h2>Can I return it?</h2><p>30 days, unused and in original condition.</p>'
);
foliora_seed_page(
	'contact',
	'Contact',
	'<p>Questions about an order, a fit, or a gift? Write to hello@foliora.local — we read every note.</p><p>12 Chapter Lane, Portland, OR 97201</p>'
);
$journal_id = foliora_seed_page(
	'journal',
	'Journal',
	''
);

update_option( 'show_on_front', 'page' );
update_option( 'page_on_front', $home_id );
update_option( 'page_for_posts', $journal_id );
update_option( 'blogname', 'Foliora' );
update_option( 'blogdescription', 'Make every reading moment feel special.' );

$cats = array(
	'book-protection' => 'Book Protection',
	'bookmarks'       => 'Bookmarks',
	'book-lights'     => 'Book Lights',
	'reading-comfort' => 'Reading Comfort',
	'annotations'     => 'Annotations & Journaling',
	'gifts'           => 'Gifts for Readers',
	'bundles'         => 'Bundles',
);
$cat_ids = array();
foreach ( $cats as $slug => $name ) {
	$cat_ids[ $slug ] = foliora_seed_cat( $slug, $name );
}

$color_id = foliora_seed_attribute( 'color', 'Color', array( 'Burgundy', 'Blue', 'Sage', 'Brown' ) );
$size_id  = foliora_seed_attribute( 'size', 'Size', array( 'Paperback', 'Hardcover', 'Kindle' ) );

$media = array();
foreach ( array(
	'hero-nook.jpg',
	'cat-protection.jpg',
	'cat-bookmarks.jpg',
	'cat-lights.jpg',
	'cat-comfort.jpg',
	'cat-annotate.jpg',
	'cat-gifts.jpg',
	'embosser-hero.jpg',
	'embosser-press.jpg',
	'ritual-nook.jpg',
	'sleeve-feature.jpg',
	'sleeve-burgundy.jpg',
	'sleeve-blue.jpg',
	'sleeve-sage.jpg',
	'sleeve-brown.jpg',
	'gift-chapter.jpg',
	'still-life-desk.jpg',
	'reel-01.jpg',
	'reel-02.jpg',
	'reel-03.jpg',
	'reel-04.jpg',
	'product-light-scene.jpg',
) as $file ) {
	$media[ $file ] = foliora_seed_media( $file );
}

$copy = function_exists( 'foliora_product_copy_map' ) ? foliora_product_copy_map() : array();

$simples = array(
	array(
		'sku'      => 'FOL-EMB-001',
		'name'     => 'Personalized Book Embosser',
		'regular'  => 42,
		'sale'     => 0,
		'short'    => $copy['FOL-EMB-001']['short'],
		'cats'     => array( $cat_ids['gifts'] ),
		'badge'    => 'Reader Favorite',
		'eyebrow'  => 'FOLIORA READER FAVORITE',
		'image'    => $media['embosser-hero.jpg'],
		'hover'    => $media['embosser-press.jpg'],
		'gallery'  => array_filter( array( $media['embosser-press.jpg'], $media['reel-01.jpg'] ) ),
		'featured' => true,
	),
	array(
		'sku'      => 'FOL-LGT-001',
		'name'     => 'Clip-on Reading Light',
		'regular'  => 22,
		'sale'     => 0,
		'short'    => $copy['FOL-LGT-001']['short'],
		'cats'     => array( $cat_ids['book-lights'] ),
		'badge'    => 'Gift Pick',
		'eyebrow'  => 'FOLIORA',
		'image'    => $media['product-light-scene.jpg'],
		'hover'    => $media['cat-lights.jpg'],
		'gallery'  => array_filter( array( $media['cat-lights.jpg'], $media['reel-04.jpg'] ) ),
		'featured' => true,
	),
	array(
		'sku'     => 'FOL-ANN-KIT',
		'name'    => 'Annotation Kit',
		'regular' => 16,
		'sale'    => 0,
		'short'   => $copy['FOL-ANN-KIT']['short'],
		'cats'    => array( $cat_ids['annotations'] ),
		'badge'   => '',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['cat-annotate.jpg'],
		'hover'   => $media['still-life-desk.jpg'],
		'gallery' => array_filter( array( $media['still-life-desk.jpg'], $media['reel-03.jpg'] ) ),
	),
	array(
		'sku'     => 'FOL-BMK-MAG',
		'name'    => 'Magnetic Bookmark',
		'regular' => 8,
		'sale'    => 0,
		'short'   => $copy['FOL-BMK-MAG']['short'],
		'cats'    => array( $cat_ids['bookmarks'] ),
		'badge'   => '',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['cat-bookmarks.jpg'],
		'hover'   => $media['cat-bookmarks.jpg'],
		'gallery' => array(),
	),
	array(
		'sku'     => 'FOL-JRN-001',
		'name'    => 'Reading Journal',
		'regular' => 24,
		'sale'    => 0,
		'short'   => $copy['FOL-JRN-001']['short'],
		'cats'    => array( $cat_ids['annotations'] ),
		'badge'   => '',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['still-life-desk.jpg'],
		'hover'   => $media['cat-annotate.jpg'],
		'gallery' => array(),
	),
	array(
		'sku'     => 'FOL-STD-001',
		'name'    => 'Book Stand',
		'regular' => 28,
		'sale'    => 0,
		'short'   => $copy['FOL-STD-001']['short'],
		'cats'    => array( $cat_ids['reading-comfort'] ),
		'badge'   => '',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['cat-comfort.jpg'],
		'hover'   => $media['cat-comfort.jpg'],
		'gallery' => array(),
	),
	array(
		'sku'     => 'FOL-GFT-SET',
		'name'    => 'Gift Bundle',
		'regular' => 68,
		'sale'    => 0,
		'short'   => $copy['FOL-GFT-SET']['short'],
		'cats'    => array( $cat_ids['gifts'] ),
		'badge'   => 'Gift Pick',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['gift-chapter.jpg'],
		'hover'   => $media['cat-gifts.jpg'],
		'gallery' => array( $media['cat-gifts.jpg'] ),
	),
	array(
		'sku'     => 'FOL-BND-COZY',
		'name'    => 'Cozy Reader Set',
		'regular' => 108,
		'sale'    => 89,
		'short'   => $copy['FOL-BND-COZY']['short'],
		'cats'    => array( $cat_ids['bundles'], $cat_ids['gifts'] ),
		'badge'   => '',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['hero-nook.jpg'],
		'hover'   => $media['cat-lights.jpg'],
		'gallery' => array(),
	),
	array(
		'sku'     => 'FOL-BND-ANNO',
		'name'    => 'Annotation Lover Set',
		'regular' => 56,
		'sale'    => 48,
		'short'   => $copy['FOL-BND-ANNO']['short'],
		'cats'    => array( $cat_ids['bundles'], $cat_ids['gifts'] ),
		'badge'   => '',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['still-life-desk.jpg'],
		'hover'   => $media['cat-annotate.jpg'],
		'gallery' => array(),
	),
	array(
		'sku'     => 'FOL-BND-LIB',
		'name'    => 'Personal Library Set',
		'regular' => 96,
		'sale'    => 82,
		'short'   => $copy['FOL-BND-LIB']['short'],
		'cats'    => array( $cat_ids['bundles'], $cat_ids['gifts'] ),
		'badge'   => '',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['embosser-hero.jpg'],
		'hover'   => $media['embosser-press.jpg'],
		'gallery' => array(),
	),
	array(
		'sku'     => 'FOL-BND-ULT',
		'name'    => 'Ultimate Reading Ritual',
		'regular' => 120,
		'sale'    => 96,
		'short'   => $copy['FOL-BND-ULT']['short'],
		'cats'    => array( $cat_ids['bundles'], $cat_ids['gifts'] ),
		'badge'   => '',
		'eyebrow' => 'FOLIORA',
		'image'   => $media['ritual-nook.jpg'],
		'hover'   => $media['hero-nook.jpg'],
		'gallery' => array(),
	),
);

foreach ( $simples as $row ) {
	$pid = foliora_seed_simple( $row );
	if ( ! empty( $row['featured'] ) ) {
		update_post_meta( $pid, '_featured', 'yes' );
		wp_set_object_terms( $pid, 'featured', 'product_visibility', true );
	}
}

$sleeve_id = wc_get_product_id_by_sku( 'FOL-SLV-VIN' );
$sleeve    = $sleeve_id ? wc_get_product( $sleeve_id ) : new WC_Product_Variable();
if ( $sleeve instanceof WC_Product_Simple ) {
	wp_delete_post( $sleeve_id, true );
	$sleeve = new WC_Product_Variable();
}
$sleeve->set_name( 'Vintage Book Sleeve' );
$sleeve->set_sku( 'FOL-SLV-VIN' );
$sleeve->set_short_description( $copy['FOL-SLV-VIN']['short'] );
$sleeve->set_category_ids( array( $cat_ids['book-protection'] ) );
$sleeve->set_catalog_visibility( 'visible' );
$sleeve->set_status( 'publish' );
$sleeve->set_image_id( $media['sleeve-burgundy.jpg'] );
$sleeve->set_gallery_image_ids(
	array_filter(
		array(
			$media['sleeve-feature.jpg'],
			$media['sleeve-blue.jpg'],
			$media['sleeve-sage.jpg'],
			$media['sleeve-brown.jpg'],
			$media['reel-02.jpg'],
		)
	)
);

$attr_color = new WC_Product_Attribute();
$attr_color->set_id( $color_id );
$attr_color->set_name( 'pa_color' );
$attr_color->set_options( array( 'Burgundy', 'Blue', 'Sage', 'Brown' ) );
$attr_color->set_visible( true );
$attr_color->set_variation( true );

$attr_size = new WC_Product_Attribute();
$attr_size->set_id( $size_id );
$attr_size->set_name( 'pa_size' );
$attr_size->set_options( array( 'Paperback', 'Hardcover', 'Kindle' ) );
$attr_size->set_visible( true );
$attr_size->set_variation( true );

$sleeve->set_attributes( array( $attr_color, $attr_size ) );
$sleeve_pid = $sleeve->save();
update_post_meta( $sleeve_pid, '_foliora_badge', 'Bestseller' );
update_post_meta( $sleeve_pid, '_foliora_eyebrow', 'FOLIORA READER FAVORITE' );
update_post_meta( $sleeve_pid, '_foliora_rating_display', '4.8 (126)' );
update_post_meta( $sleeve_pid, '_foliora_hover_image', $media['sleeve-feature.jpg'] );
update_post_meta( $sleeve_pid, '_featured', 'yes' );
wp_set_object_terms( $sleeve_pid, array( 'Burgundy', 'Blue', 'Sage', 'Brown' ), 'pa_color' );
wp_set_object_terms( $sleeve_pid, array( 'Paperback', 'Hardcover', 'Kindle' ), 'pa_size' );

$color_codes = array(
	'Burgundy' => 'BUR',
	'Blue'     => 'BLU',
	'Sage'     => 'SAG',
	'Brown'    => 'BRN',
);
$size_codes  = array(
	'Paperback' => 'PB',
	'Hardcover' => 'HC',
	'Kindle'    => 'KD',
);
$color_img   = array(
	'Burgundy' => $media['sleeve-burgundy.jpg'],
	'Blue'     => $media['sleeve-blue.jpg'],
	'Sage'     => $media['sleeve-sage.jpg'],
	'Brown'    => $media['sleeve-brown.jpg'],
);

foreach ( $color_codes as $color => $cc ) {
	foreach ( $size_codes as $size => $sc ) {
		$vsku = 'FOL-SLV-VIN-' . $cc . '-' . $sc;
		$vid  = wc_get_product_id_by_sku( $vsku );
		$var  = $vid ? wc_get_product( $vid ) : new WC_Product_Variation();
		if ( ! $var instanceof WC_Product_Variation ) {
			$var = new WC_Product_Variation();
		}
		$var->set_parent_id( $sleeve_pid );
		$var->set_sku( $vsku );
		$var->set_regular_price( '32' );
		$var->set_stock_status( 'instock' );
		$var->set_attributes(
			array(
				'pa_color' => sanitize_title( $color ),
				'pa_size'  => sanitize_title( $size ),
			)
		);
		if ( ! empty( $color_img[ $color ] ) ) {
			$var->set_image_id( $color_img[ $color ] );
		}
		$var->save();
	}
}
WC_Product_Variable::sync( $sleeve_pid );

$shop_id      = wc_get_page_id( 'shop' );
$shop_url     = $shop_id > 0 ? get_permalink( $shop_id ) : home_url( '/shop/' );
$account_url  = wc_get_page_permalink( 'myaccount' );

/**
 * Recreate a named menu.
 *
 * @param string                $name Location name used as menu name.
 * @param array<int, array>     $items Items.
 * @param string                $loc  Theme location.
 */
function foliora_seed_menu( $name, $items, $loc ) {
	$existing = wp_get_nav_menu_object( $name );
	if ( $existing ) {
		wp_delete_nav_menu( $existing->term_id );
	}
	$id = wp_create_nav_menu( $name );
	foreach ( $items as $item ) {
		wp_update_nav_menu_item(
			$id,
			0,
			array(
				'menu-item-title'  => $item[0],
				'menu-item-url'    => $item[1],
				'menu-item-status' => 'publish',
			)
		);
	}
	$locations         = get_theme_mod( 'nav_menu_locations', array() );
	$locations[ $loc ] = $id;
	set_theme_mod( 'nav_menu_locations', $locations );
}

$gift_url = get_term_link( $cat_ids['gifts'], 'product_cat' );
if ( is_wp_error( $gift_url ) ) {
	$gift_url = $shop_url;
}

foliora_seed_menu(
	'Primary',
	array(
		array( 'Shop', $shop_url ),
		array( 'Collections', home_url( '/#moods' ) ),
		array( 'Best Sellers', home_url( '/#bestsellers' ) ),
		array( 'Gifts', $gift_url ),
		array( 'Our Story', get_permalink( $story_id ) ),
	),
	'primary'
);

foliora_seed_menu(
	'Footer Shop',
	array(
		array( 'All Products', $shop_url ),
		array( 'Best Sellers', home_url( '/#bestsellers' ) ),
		array( 'New Arrivals', home_url( '/#bestsellers' ) ),
		array( 'Gifts', $gift_url ),
	),
	'footer-shop'
);

$coll_items = array();
foreach ( array( 'bookmarks', 'book-protection', 'book-lights', 'reading-comfort', 'annotations' ) as $slug ) {
	$link = get_term_link( $cat_ids[ $slug ], 'product_cat' );
	$coll_items[] = array( $cats[ $slug ], is_wp_error( $link ) ? $shop_url : $link );
}
foliora_seed_menu( 'Footer Collections', $coll_items, 'footer-collections' );

foliora_seed_menu(
	'Footer Help',
	array(
		array( 'Shipping', home_url( '/shipping/' ) ),
		array( 'Returns', home_url( '/returns/' ) ),
		array( 'FAQ', home_url( '/faq/' ) ),
		array( 'Contact', home_url( '/contact/' ) ),
	),
	'footer-help'
);

foliora_seed_menu(
	'Footer Foliora',
	array(
		array( 'Our Story', get_permalink( $story_id ) ),
		array( 'Reading Journal / Blog', get_permalink( $journal_id ) ),
		array( 'Instagram', '#' ),
		array( 'TikTok', '#' ),
	),
	'footer-brand'
);

$zone_id = 0;
$zones   = WC_Shipping_Zones::get_zones();
foreach ( $zones as $zone_data ) {
	if ( isset( $zone_data['zone_name'] ) && 'United States' === $zone_data['zone_name'] ) {
		$zone_id = $zone_data['id'];
	}
}
if ( ! $zone_id ) {
	$zone = new WC_Shipping_Zone();
	$zone->set_zone_name( 'United States' );
	$zone->add_location( 'US', 'country' );
	$zone_id = $zone->save();
}
$zone    = new WC_Shipping_Zone( $zone_id );
$methods = $zone->get_shipping_methods();
$has_free = false;
foreach ( $methods as $method ) {
	if ( 'free_shipping' === $method->id ) {
		$has_free = true;
	}
}
if ( ! $has_free ) {
	$instance_id = $zone->add_shipping_method( 'free_shipping' );
	$instance    = WC_Shipping_Zones::get_shipping_method( $instance_id );
	if ( $instance ) {
		$settings = $instance->instance_settings;
		$settings['title']      = 'Free shipping';
		$settings['requires']   = 'min_amount';
		$settings['min_amount'] = '50';
		update_option( $instance->get_instance_option_key(), $settings );
	}
}

if ( class_exists( 'WP_CLI' ) ) {
	WP_CLI::success( 'Foliora catalog, pages, menus and $50 free shipping are in place.' );
}
