<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Avision_Pages_Admin {
	public static function init(): void {
		add_action( 'admin_notices', array( __CLASS__, 'maybe_show_edit_notice' ), 20 );
	}

	public static function render_page(): void {
		$seed = array(
			'home' => array(
				'hero_title_en' => 'The Ultimate Fleet Management Platform for Local SEO Agencies',
				'hero_sub_en'   => 'Protect your clients\' local presence 24/7. Automate bulk actions across your entire fleet. Scale to 500+ locations without adding headcount.',
				'cta_label_en'  => 'AGENCY LOGIN / PARTNER ACCESS',
				'cta_url_en'    => '/connexion/',
				'meta_title_en' => 'Fleet Management Platform for Local SEO Agencies — Avision',
				'meta_desc_en'  => 'Scale your agency. Protect your clients local presence 24/7. Wholesale pricing from $3/location/month.',
			),
			'local-business' => array(
				'hero_title_en'       => 'Stop Losing Customers to Better-Optimized Competitors',
				'hero_sub_en'         => 'Most local businesses have fixable blind spots in their local presence. Find yours in 60 seconds — free, no account required.',
				'form_placeholder_en' => 'Enter your business name...',
				'form_btn_label_en'   => 'Start Free Analysis →',
				'meta_title_en'       => 'Free Local Business Presence Audit — Avision',
				'meta_desc_en'        => 'Find what is blocking your local visibility. Free analysis in 60 seconds. No account required.',
			),
			'about' => array(
				'hero_title_en' => 'Built for Local SEO Professionals',
				'hero_sub_en'   => 'Avision is the intelligence platform built by practitioners, for practitioners. Helping agencies protect and grow their clients local presence.',
				'meta_title_en' => 'About Avision — Local SEO Intelligence Platform',
				'meta_desc_en'  => 'Advantage Synergies LLP. Registered in England and Wales, London. Building the future of local SEO intelligence.',
			),
			'api-security' => array(
				'hero_title_en' => 'How Avision Handles Your Google Data',
				'hero_sub_en'   => 'Built on OAuth 2.0. Your data, your control. Always.',
				'meta_title_en' => 'API Security and OAuth — Avision',
				'meta_desc_en'  => 'How Avision uses Google OAuth 2.0 to access Google Business Profile data only with explicit user consent.',
			),
			'how-it-works' => array(
				'hero_title_en' => 'Local SEO Intelligence, Running 24/7',
				'hero_sub_en'   => 'Connect your Google Business Profile. AVI Intelligence does the rest.',
				'meta_title_en' => 'How Avision Works — Local SEO Automation',
				'meta_desc_en'  => 'Guardian Mode, Growth Radar, and AVI Intelligence work together to protect and grow your local presence.',
			),
			'pricing' => array(
				'hero_title_en'         => 'Plans That Grow With You',
				'hero_sub_en'           => 'Start with a free audit. Upgrade when ready. No contracts, cancel anytime.',
				'launch_banner_text_en' => '🎉 Launch offer — 30% off all plans · Code: LAUNCH_BTOC',
				'meta_title_en'         => 'Pricing — Local SEO Plans for Every Business',
				'meta_desc_en'          => 'Guardian Mode from $34/month. Growth Radar from $6/month. No contracts.',
			),
			'agency-pricing' => array(
				'hero_title_en'         => 'Scale Your Agency with Fleet Intelligence',
				'hero_sub_en'           => 'Wholesale pricing that rewards your growth. From $3 per location per month.',
				'launch_banner_text_en' => '🎉 Launch offer — 38% off · Code: LAUNCH_BTOB',
				'meta_title_en'         => 'Agency Pricing — Wholesale Local SEO at Scale',
				'meta_desc_en'          => 'Manage 1 to 500+ Google Business Profiles. Wholesale pricing from $3/location/month.',
			),
			'nonprofits' => array(
				'hero_title_en' => '50% Off for Organizations That Matter',
				'hero_sub_en'   => 'Registered nonprofits and associations get half off, forever.',
				'meta_title_en' => 'Avision for Nonprofits — 50% Discount Program',
				'meta_desc_en'  => 'Registered nonprofits and associations get 50% off all Avision plans.',
			),
			'refer' => array(
				'hero_title_en' => 'Refer Friends, Earn Free Months',
				'hero_sub_en'   => 'Our referral program is launching soon. Leave your email to be notified first.',
				'meta_title_en' => 'Refer a Friend — Earn Free Months',
				'meta_desc_en'  => 'Invite a friend to Avision and earn free subscription months. Coming soon.',
			),
			'legal' => array(
				'meta_title_en' => 'Legal and Privacy — Avision',
				'meta_desc_en'  => 'Advantage Synergies LLP — Privacy Policy, Terms of Use, API Data Policy, GDPR.',
			),
		);

		// Seed only empty options — never overwrite existing values
		foreach ( $seed as $page_slug => $fields ) {
			foreach ( $fields as $key_with_lang => $value ) {
				$key_with_lang = (string) $key_with_lang;
				$value         = (string) $value;
				if ( ! preg_match( '/^(.*)_(en|fr|es)$/', $key_with_lang, $m ) ) {
					continue;
				}
				$sec  = sanitize_key( (string) $m[1] );
				$lang = sanitize_key( (string) $m[2] );
				if ( $sec === '' || $lang === '' ) {
					continue;
				}
				$opt_key = 'avi_page_' . sanitize_key( (string) $page_slug ) . '_' . $sec . '_' . $lang;
				if ( get_option( $opt_key, '__EMPTY__' ) === '__EMPTY__' ) {
					update_option( $opt_key, $value, false );
				}
			}
		}

		self::render();
	}

	public static function register_menu(): void {
		add_submenu_page(
			'avision-dashboard',
			'Pages Content',
			'📄 Pages',
			'manage_options',
			'avi-pages-admin',
			array( __CLASS__, 'render' )
		);
	}

	public static function maybe_show_edit_notice(): void {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return;
		}
		$screen = get_current_screen();
		if ( ! $screen || $screen->base !== 'post' || $screen->post_type !== 'page' ) {
			return;
		}
		$post = get_post();
		if ( ! $post instanceof \WP_Post ) {
			return;
		}

		$avi_pages = array(
			'home',
			'local-business',
			'about',
			'how-it-works',
			'api-security',
			'legal',
			'pricing',
			'agency-pricing',
			'nonprofits',
			'refer',
		);
		if ( ! in_array( $post->post_name, $avi_pages, true ) ) {
			return;
		}
		$admin_url = admin_url( 'admin.php?page=avi-pages-admin' );
		echo '<div class="notice notice-info"><p><strong>Avision Page</strong> — This page uses an Avision template. To edit its content, use the <a href="' . esc_url( $admin_url ) . '">Avision Pages editor</a>.</p></div>';
	}

	public static function render(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$pages = array(
			'home'           => 'Homepage (B2B)',
			'local-business' => 'Local Business (B2C)',
			'about'          => 'About',
			'how-it-works'   => 'How It Works',
			'api-security'   => 'API Security',
			'legal'          => 'Legal',
			'pricing'        => 'Pricing',
			'agency-pricing' => 'Agency Pricing',
			'nonprofits'     => 'Nonprofits',
			'refer'          => 'Refer',
		);
		$page_sections = array(
			'home'           => array(
				'hero_title'             => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'               => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'stats_json'             => array( 'label' => 'Stats JSON', 'type' => 'textarea' ),
				'cta_label'              => array( 'label' => 'CTA Button Label', 'type' => 'text' ),
				'cta_url'                => array( 'label' => 'CTA Button URL', 'type' => 'text' ),
				'section_products_title' => array( 'label' => 'Products Section Title', 'type' => 'text' ),
				'section_products_sub'   => array( 'label' => 'Products Section Subtitle', 'type' => 'textarea' ),
				'meta_title'             => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'              => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'local-business' => array(
				'hero_title'          => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'            => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'form_placeholder'    => array( 'label' => 'Form Placeholder', 'type' => 'text' ),
				'form_btn_label'      => array( 'label' => 'Form Button Label', 'type' => 'text' ),
				'section_what_we_check' => array( 'label' => 'Section — What We Check (HTML)', 'type' => 'html' ),
				'section_then_what'   => array( 'label' => 'Section — Then What (HTML)', 'type' => 'html' ),
				'meta_title'          => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'           => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'about'          => array(
				'hero_title'    => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'      => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'mission_text'  => array( 'label' => 'Mission (HTML)', 'type' => 'html' ),
				'company_text'  => array( 'label' => 'Company Info (HTML)', 'type' => 'html' ),
				'meta_title'    => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'     => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'api-security'   => array(
				'hero_title'    => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'      => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'body'          => array( 'label' => 'Main Content (HTML)', 'type' => 'html' ),
				'meta_title'    => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'     => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'how-it-works'   => array(
				'hero_title'    => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'      => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'body'          => array( 'label' => 'Main Content (HTML)', 'type' => 'html' ),
				'meta_title'    => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'     => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'legal'          => array(
				'privacy_html'  => array( 'label' => 'Privacy Policy (HTML)', 'type' => 'html' ),
				'terms_html'    => array( 'label' => 'Terms of Use (HTML)', 'type' => 'html' ),
				'api_data_html' => array( 'label' => 'API Data Policy (HTML)', 'type' => 'html' ),
				'gdpr_html'     => array( 'label' => 'GDPR (HTML)', 'type' => 'html' ),
				'meta_title'    => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'     => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'pricing'        => array(
				'hero_title'         => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'           => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'launch_banner_text' => array( 'label' => 'Launch Banner', 'type' => 'text' ),
				'faq_json'           => array( 'label' => 'FAQ JSON', 'type' => 'textarea' ),
				'meta_title'         => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'          => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'agency-pricing' => array(
				'hero_title'         => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'           => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'launch_banner_text' => array( 'label' => 'Launch Banner', 'type' => 'text' ),
				'meta_title'         => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'          => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'nonprofits'     => array(
				'hero_title'    => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'      => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'body'          => array( 'label' => 'Main Content (HTML)', 'type' => 'html' ),
				'meta_title'    => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'     => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
			'refer'          => array(
				'hero_title'    => array( 'label' => 'Hero Title', 'type' => 'text' ),
				'hero_sub'      => array( 'label' => 'Hero Subtitle', 'type' => 'textarea' ),
				'body'          => array( 'label' => 'Main Content (HTML)', 'type' => 'html' ),
				'meta_title'    => array( 'label' => 'SEO Title', 'type' => 'text' ),
				'meta_desc'     => array( 'label' => 'SEO Description', 'type' => 'textarea' ),
			),
		);
		$langs = array( 'en' => '🇬🇧 EN', 'fr' => '🇫🇷 FR', 'es' => '🇪🇸 ES' );

		if ( isset( $_POST['avi_pages_save'], $_POST['_wpnonce'] ) && wp_verify_nonce( (string) $_POST['_wpnonce'], 'avi_pages_save' ) ) {
			$incoming = isset( $_POST['avi_content'] ) && is_array( $_POST['avi_content'] ) ? $_POST['avi_content'] : array();
			foreach ( $incoming as $key => $value ) {
				$opt_key = sanitize_key( (string) $key );
				$opt_val = is_string( $value ) ? wp_unslash( $value ) : '';
				$type    = 'html';
				if ( preg_match( '/^avi_page_([a-z0-9\-]+)_([a-z0-9_]+)_(en|fr|es)$/', $opt_key, $m ) ) {
					$p_slug = (string) $m[1];
					$s_key  = (string) $m[2];
					if ( isset( $page_sections[ $p_slug ][ $s_key ]['type'] ) ) {
						$type = (string) $page_sections[ $p_slug ][ $s_key ]['type'];
					}
				}
				if ( $type === 'text' ) {
					$opt_val = sanitize_text_field( (string) $opt_val );
				} elseif ( $type === 'textarea' ) {
					$opt_val = sanitize_textarea_field( (string) $opt_val );
				} else {
					$opt_val = wp_kses_post( (string) $opt_val );
				}
				update_option( $opt_key, $opt_val, false );
			}
			echo '<div class="notice notice-success"><p>✓ Content saved.</p></div>';
		}

		$current_page = isset( $_GET['avi_page'] ) ? sanitize_key( (string) $_GET['avi_page'] ) : 'home';
		$current_lang = isset( $_GET['avi_lang'] ) ? sanitize_key( (string) $_GET['avi_lang'] ) : 'en';
		if ( ! isset( $pages[ $current_page ] ) ) {
			$current_page = 'home';
		}
		if ( ! isset( $langs[ $current_lang ] ) ) {
			$current_lang = 'en';
		}
		$sections = isset( $page_sections[ $current_page ] ) ? $page_sections[ $current_page ] : array();

		// One-time defaults seeder (fills empty options only)
		$seed_guard = (string) get_option( 'avi_pages_defaults_seeded_v1', '' );
		if ( $seed_guard !== '1' ) {
			$defaults_map = array(
				'home' => array(
					'en' => array(
						'hero_title' => 'The Ultimate Fleet Management Platform for Local SEO Agencies',
						'hero_sub'   => 'Protect your clients\' local presence 24/7. Automate bulk actions. Scale to 500+ locations without adding headcount.',
						'cta_label'  => 'AGENCY LOGIN / PARTNER ACCESS',
						'cta_url'    => '/connexion/',
						'meta_title' => 'Fleet Management Platform for Local SEO Agencies — Avision',
						'meta_desc'  => 'Scale your agency. Protect your clients\' GBP 24/7. Wholesale pricing.',
					),
				),
				'local-business' => array(
					'en' => array(
						'hero_title'       => 'Stop Losing Customers to Better-Optimized Competitors',
						'hero_sub'         => 'Find your local presence blind spots in 60 seconds — free.',
						'form_placeholder' => 'Enter your business name...',
						'form_btn_label'   => 'Start Free Analysis →',
						'meta_title'       => 'Local Business SEO — Free Audit',
						'meta_desc'        => 'Free local presence audit in 60 seconds. No account required.',
					),
				),
			);

			foreach ( $defaults_map as $page_slug => $langs_defaults ) {
				foreach ( $langs_defaults as $lang_code => $defaults ) {
					foreach ( $defaults as $sec_key => $default_val ) {
						$opt_key = 'avi_page_' . $page_slug . '_' . $sec_key . '_' . $lang_code;
						if ( (string) get_option( $opt_key, '' ) === '' ) {
							update_option( $opt_key, (string) $default_val, false );
						}
					}
				}
			}

			update_option( 'avi_pages_defaults_seeded_v1', '1', false );
		}
		?>
		<div class="wrap">
			<h1>📄 Avision Pages Content</h1>

			<div style="display:flex;gap:6px;flex-wrap:wrap;margin:16px 0">
				<?php foreach ( $pages as $slug => $label ) : ?>
					<?php $active = $slug === $current_page; ?>
					<a href="<?php echo esc_url( add_query_arg( array( 'page' => 'avi-pages-admin', 'avi_page' => $slug, 'avi_lang' => $current_lang ), admin_url( 'admin.php' ) ) ); ?>"
					   style="padding:6px 14px;border-radius:20px;font-size:13px;text-decoration:none;font-weight:500;<?php echo $active ? 'background:#6B46E8;color:#fff' : 'background:#f0f0f0;color:#333'; ?>">
						<?php echo esc_html( $label ); ?>
					</a>
				<?php endforeach; ?>
			</div>

			<div style="display:flex;gap:6px;margin-bottom:20px">
				<?php foreach ( $langs as $code => $label ) : ?>
					<?php $active = $code === $current_lang; ?>
					<a href="<?php echo esc_url( add_query_arg( array( 'page' => 'avi-pages-admin', 'avi_page' => $current_page, 'avi_lang' => $code ), admin_url( 'admin.php' ) ) ); ?>"
					   style="padding:5px 12px;border-radius:15px;font-size:13px;text-decoration:none;<?php echo $active ? 'background:#1DB88A;color:#fff' : 'background:#f0f0f0;color:#333'; ?>">
						<?php echo esc_html( $label ); ?>
					</a>
				<?php endforeach; ?>
			</div>

			<form method="post">
				<?php wp_nonce_field( 'avi_pages_save' ); ?>
				<input type="hidden" name="avi_pages_save" value="1" />

				<?php foreach ( $sections as $sec_key => $sec_cfg ) : ?>
					<?php
					$opt_key = 'avi_page_' . $current_page . '_' . $sec_key . '_' . $current_lang;
					$value   = (string) get_option( $opt_key, '' );
					$label   = isset( $sec_cfg['label'] ) ? (string) $sec_cfg['label'] : (string) $sec_key;
					$type    = isset( $sec_cfg['type'] ) ? (string) $sec_cfg['type'] : 'text';
					?>
					<div style="margin-bottom:20px;background:#fff;padding:16px;border-radius:8px;border:1px solid #e0e0e0">
						<label style="display:block;font-weight:600;margin-bottom:6px;font-size:13px">
							<?php echo esc_html( $label ); ?>
							<code style="font-weight:400;color:#888;font-size:11px;margin-left:6px"><?php echo esc_html( $opt_key ); ?></code>
						</label>
						<?php if ( $type === 'html' ) : ?>
							<textarea name="avi_content[<?php echo esc_attr( $opt_key ); ?>]" rows="12" class="wp-editor-area" style="width:100%;font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;font-size:13px;padding:10px;border:1px solid #ddd;border-radius:4px"><?php echo esc_textarea( $value ); ?></textarea>
						<?php elseif ( $type === 'textarea' ) : ?>
							<textarea name="avi_content[<?php echo esc_attr( $opt_key ); ?>]" rows="6" style="width:100%;font-family:inherit;font-size:13px;padding:8px;border:1px solid #ddd;border-radius:4px"><?php echo esc_textarea( $value ); ?></textarea>
						<?php else : ?>
							<input type="text" name="avi_content[<?php echo esc_attr( $opt_key ); ?>]" value="<?php echo esc_attr( $value ); ?>" style="width:100%;padding:8px;font-size:13px;border:1px solid #ddd;border-radius:4px" />
						<?php endif; ?>
					</div>
				<?php endforeach; ?>

				<button type="submit" class="button button-primary" style="background:#6B46E8;border-color:#5030C0;font-size:14px;padding:8px 24px">
					💾 Save Content
				</button>

				<?php
				$public_path = $current_page === 'home' ? '/' : '/' . $current_page . '/';
				?>
				<a href="<?php echo esc_url( home_url( $public_path ) ); ?>" target="_blank" class="button" style="margin-left:10px">
					👁 View Page
				</a>
			</form>
		</div>
		<?php
	}
}

