<?php
/**
 * Creates and manages public WordPress pages with category plan shortcodes.
 *
 * @package Lucrativeit_Subscription_Recurring_Billing
 */

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

class LUCRSURE_Plan_Pages {

	const OPTION_KEY = 'lucrsure_category_plan_pages';

	public static function definitions() {
		return array(
			'gym-membership'   => array(
				'title'    => __( 'Gym Membership Plans', 'lucrativeit-subscription-recurring-billing' ),
				'slug'     => 'gym-membership-plans',
				'interval' => 'month',
				'popular'  => 'gym-standard',
				'subtitle' => __( 'Pick a membership that fits your fitness goals.', 'lucrativeit-subscription-recurring-billing' ),
				'intro'    => __( 'Flexible gym memberships with daily, monthly, and annual options.', 'lucrativeit-subscription-recurring-billing' ),
			),
			'internet-isp'     => array(
				'title'    => __( 'Internet Plans', 'lucrativeit-subscription-recurring-billing' ),
				'slug'     => 'internet-plans',
				'interval' => 'month',
				'popular'  => 'isp-100mbps',
				'subtitle' => __( 'Fast, reliable broadband for home and office.', 'lucrativeit-subscription-recurring-billing' ),
				'intro'    => __( 'Compare speed tiers and subscribe online in minutes.', 'lucrativeit-subscription-recurring-billing' ),
			),
			'online-coaching'  => array(
				'title'    => __( 'Online Coaching Plans', 'lucrativeit-subscription-recurring-billing' ),
				'slug'     => 'online-coaching-plans',
				'interval' => 'month',
				'popular'  => 'coach-group',
				'subtitle' => __( 'Self-paced, group, or private coaching programs.', 'lucrativeit-subscription-recurring-billing' ),
				'intro'    => __( 'Choose the coaching style that works best for you.', 'lucrativeit-subscription-recurring-billing' ),
			),
			'saas-software'    => array(
				'title'    => __( 'SaaS Software Plans', 'lucrativeit-subscription-recurring-billing' ),
				'slug'     => 'saas-software-plans',
				'interval' => 'month',
				'popular'  => 'saas-growth',
				'subtitle' => __( 'Scale your team with the right software tier.', 'lucrativeit-subscription-recurring-billing' ),
				'intro'    => __( 'Team, growth, and enterprise packages for growing businesses.', 'lucrativeit-subscription-recurring-billing' ),
			),
			'software-license' => array(
				'title'    => __( 'Software License Plans', 'lucrativeit-subscription-recurring-billing' ),
				'slug'     => 'software-license-plans',
				'interval' => 'year',
				'popular'  => 'license-business',
				'subtitle' => __( 'Personal, business, and lifetime license options.', 'lucrativeit-subscription-recurring-billing' ),
				'intro'    => __( 'Annual and lifetime licenses for individuals and agencies.', 'lucrativeit-subscription-recurring-billing' ),
			),
		);
	}

	public static function create_demo_pages( array $category_ids, array $plan_ids, array $selected_slugs = array() ) {
		$created = array();

		foreach ( self::definitions() as $category_slug => $def ) {
			if ( ! isset( $category_ids[ $category_slug ] ) ) {
				continue;
			}
			if ( ! empty( $selected_slugs ) && ! in_array( $category_slug, $selected_slugs, true ) ) {
				continue;
			}

			$popular_id = 0;
			if ( ! empty( $def['popular'] ) && isset( $plan_ids[ $def['popular'] ] ) ) {
				$popular_id = (int) $plan_ids[ $def['popular'] ];
			}

			$page_id = self::create_page(
				$category_slug,
				array(
					'title'    => $def['title'],
					'slug'     => $def['slug'],
					'interval' => $def['interval'],
					'popular'  => $popular_id,
					'subtitle' => $def['subtitle'],
					'intro'    => $def['intro'],
				)
			);

			if ( $page_id ) {
				$created[ $category_slug ] = $page_id;
			}
		}

		$new_map = $created;

		if ( count( $created ) > 1 ) {
			$hub_id = self::create_hub_page( $created );
			if ( $hub_id ) {
				$new_map['__hub__'] = $hub_id;
			}
		}

		update_option( self::OPTION_KEY, $new_map );
		return $created;
	}

	public static function sync_all_categories() {
		$cat_repo = new LUCRSURE_Plan_Category_Repository();
		$cat_repo->consolidate_duplicates();

		$plan_repo = new LUCRSURE_Plan_Repository();
		$map       = self::get_map();
		$created   = array();
		$defs      = self::definitions();

		foreach ( $cat_repo->active() as $category ) {
			$slug = $category['slug'];
			$def  = isset( $defs[ $slug ] ) ? $defs[ $slug ] : array();

			$popular_id = 0;
			if ( ! empty( $def['popular'] ) ) {
				$popular_plan = $plan_repo->find_by_slug( $def['popular'] );
				if ( $popular_plan ) {
					$popular_id = (int) $popular_plan['id'];
				}
			}

			$page_id = self::create_page(
				$slug,
				array(
					'title'    => ! empty( $def['title'] ) ? $def['title'] : $category['name'] . ' ' . __( 'Plans', 'lucrativeit-subscription-recurring-billing' ),
					'slug'     => ! empty( $def['slug'] ) ? $def['slug'] : sanitize_title( $slug . '-plans' ),
					'interval' => ! empty( $def['interval'] ) ? $def['interval'] : 'month',
					'popular'  => $popular_id,
					'subtitle' => ! empty( $def['subtitle'] ) ? $def['subtitle'] : '',
					'intro'    => ! empty( $def['intro'] ) ? $def['intro'] : (string) $category['description'],
				)
			);

			if ( $page_id ) {
				$created[ $slug ] = $page_id;
				$map[ $slug ]     = $page_id;
			}
		}

		$hub_id = self::create_hub_page( $created );
		if ( $hub_id ) {
			$map['__hub__'] = $hub_id;
		}

		update_option( self::OPTION_KEY, $map );
		return $created;
	}

	protected static function create_page( $category_slug, array $args ) {
		$map     = self::get_map();
		$page_id = 0;

		if ( isset( $map[ $category_slug ] ) ) {
			$existing = get_post( (int) $map[ $category_slug ] );
			if ( $existing && 'trash' !== $existing->post_status ) {
				$page_id = (int) $map[ $category_slug ];
			}
		}

		if ( ! $page_id ) {
			$by_path = get_page_by_path( $args['slug'] );
			if ( $by_path && 'trash' !== $by_path->post_status ) {
				$page_id               = (int) $by_path->ID;
				$map[ $category_slug ] = $page_id;
				update_option( self::OPTION_KEY, $map );
			}
		}

		$shortcode = self::build_shortcode( $category_slug, $args );
		$content   = '';
		if ( ! empty( $args['intro'] ) ) {
			$content .= '<p>' . esc_html( $args['intro'] ) . "</p>\n\n";
		}
		$content .= $shortcode;

		if ( $page_id ) {
			wp_update_post( array( 'ID' => $page_id, 'post_content' => $content ) );
			return $page_id;
		}

		$page_id = wp_insert_post(
			array(
				'post_title'   => $args['title'],
				'post_name'    => $args['slug'],
				'post_content' => $content,
				'post_status'  => 'publish',
				'post_type'    => 'page',
				'post_author'  => get_current_user_id() ? get_current_user_id() : 1,
			),
			true
		);

		return is_wp_error( $page_id ) ? 0 : (int) $page_id;
	}

	protected static function build_shortcode( $category_slug, array $args ) {
		$parts   = array( 'category="' . esc_attr( $category_slug ) . '"' );
		$parts[] = 'interval="' . esc_attr( ! empty( $args['interval'] ) ? $args['interval'] : 'month' ) . '"';
		if ( ! empty( $args['popular'] ) ) {
			$parts[] = 'popular="' . (int) $args['popular'] . '"';
		}
		return '[lucrsure_locations_plans ' . implode( ' ', $parts ) . ']';
	}

	protected static function create_hub_page( array $category_pages ) {
		if ( empty( $category_pages ) ) {
			return 0;
		}

		$map    = self::get_map();
		$hub_id = isset( $map['__hub__'] ) ? (int) $map['__hub__'] : 0;
		$links  = array();
		$defs   = self::definitions();

		foreach ( $category_pages as $slug => $page_id ) {
			$title = isset( $defs[ $slug ]['title'] ) ? $defs[ $slug ]['title'] : get_the_title( $page_id );
			$url   = get_permalink( $page_id );
			if ( $url ) {
				$links[] = '<li><a href="' . esc_url( $url ) . '">' . esc_html( $title ) . '</a></li>';
			}
		}

		$content  = '<p>' . esc_html__( 'Browse subscription plans by category:', 'lucrativeit-subscription-recurring-billing' ) . '</p>';
		$content .= '<ul class="lucrsure-plan-hub-links">' . implode( '', $links ) . '</ul>';

		if ( $hub_id ) {
			wp_update_post( array( 'ID' => $hub_id, 'post_content' => $content ) );
			return $hub_id;
		}

		$hub_id = wp_insert_post(
			array(
				'post_title'   => __( 'Subscription Plans', 'lucrativeit-subscription-recurring-billing' ),
				'post_name'    => 'subscription-plans',
				'post_content' => $content,
				'post_status'  => 'publish',
				'post_type'    => 'page',
			),
			true
		);

		return is_wp_error( $hub_id ) ? 0 : (int) $hub_id;
	}

	public static function get_map() {
		$map = get_option( self::OPTION_KEY, array() );
		return is_array( $map ) ? $map : array();
	}

	public static function get_url( $category_slug ) {
		$map = self::get_map();
		if ( empty( $map[ $category_slug ] ) ) {
			return '';
		}
		$url = get_permalink( (int) $map[ $category_slug ] );
		return $url ? $url : '';
	}

	public static function get_hub_url() {
		$map = self::get_map();
		if ( empty( $map['__hub__'] ) ) {
			return '';
		}
		$url = get_permalink( (int) $map['__hub__'] );
		return $url ? $url : '';
	}
}
