<?php
/**
 * Visual editor extensions – tour, undo revisions, globals, menu, licensing, client role.
 *
 * @package EasySite_Pro
 */

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

/* ── Layout revisions ─────────────────────────────────────── */

/**
 * Save layout revision before overwrite.
 *
 * @param int   $post_id Post ID.
 * @param array $layout  Layout array.
 */
function easysite_ve_save_revision( $post_id, $layout ) {
	$revs = get_post_meta( $post_id, '_easysite_layout_revisions', true );
	if ( ! is_array( $revs ) ) {
		$revs = array();
	}
	array_unshift( $revs, array(
		'time'   => time(),
		'layout' => $layout,
	) );
	$revs = array_slice( $revs, 0, 20 );
	update_post_meta( $post_id, '_easysite_layout_revisions', $revs );
}

/**
 * AJAX: list layout revisions.
 */
function easysite_ajax_ve_get_revisions() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error();
	}
	$revs = get_post_meta( $post_id, '_easysite_layout_revisions', true );
	wp_send_json_success( array( 'revisions' => is_array( $revs ) ? $revs : array() ) );
}
add_action( 'wp_ajax_easysite_ve_get_revisions', 'easysite_ajax_ve_get_revisions' );

/**
 * AJAX: restore a layout revision into the editor.
 */
function easysite_ajax_ve_restore_revision() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
	$index   = isset( $_POST['index'] ) ? absint( $_POST['index'] ) : 0;
	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error();
	}
	$revs = get_post_meta( $post_id, '_easysite_layout_revisions', true );
	if ( ! is_array( $revs ) || ! isset( $revs[ $index ]['layout'] ) ) {
		wp_send_json_error( array( 'message' => __( 'Revision not found.', 'easysite-pro' ) ) );
	}
	wp_send_json_success( array( 'layout' => $revs[ $index ]['layout'] ) );
}
add_action( 'wp_ajax_easysite_ve_restore_revision', 'easysite_ajax_ve_restore_revision' );

/**
 * Generate demo AI copy when no API key is configured.
 *
 * @param string $type    Suggestion type.
 * @param string $context Existing draft text.
 * @return string
 */
function easysite_ve_ai_demo_text( $type, $context = '' ) {
	$site     = get_bloginfo( 'name' );
	$industry = function_exists( 'easysite_get_industry_key' ) ? easysite_get_industry_key() : 'business';

	$industry_samples = array(
		'beauty'     => __( 'Treat yourself to expert care in a relaxing salon atmosphere. Book your appointment today.', 'easysite-pro' ),
		'fitness'    => __( 'Personal training programs built around your goals. Start your fitness journey with a free consultation.', 'easysite-pro' ),
		'coach'      => __( 'Unlock clarity and confidence with one-on-one coaching tailored to your life and business.', 'easysite-pro' ),
		'realestate' => __( 'Find your perfect home with a trusted local agent who knows the market inside and out.', 'easysite-pro' ),
		'restaurant' => __( 'Fresh ingredients, warm hospitality, and flavours you will remember. Reserve your table tonight.', 'easysite-pro' ),
		'shop'       => __( 'Discover quality products handpicked for you. Fast shipping and friendly support on every order.', 'easysite-pro' ),
	);

	if ( 'meta' === $type ) {
		return sprintf(
			/* translators: %s: site name */
			__( '%s — friendly local service you can trust. Contact us today to get started.', 'easysite-pro' ),
			$site
		);
	}

	if ( 'alt' === $type ) {
		return __( 'Team member smiling in a bright office', 'easysite-pro' );
	}

	if ( 'seo_title' === $type ) {
		return sprintf( '%s | %s', $site, __( 'Home', 'easysite-pro' ) );
	}

	if ( 'shorter' === $type && $context ) {
		return wp_trim_words( $context, 12, '…' );
	}

	if ( 'friendlier' === $type && $context ) {
		return $context . ' ' . __( 'We would love to help!', 'easysite-pro' );
	}

	if ( 'professional' === $type && $context ) {
		return $context;
	}

	$text = isset( $industry_samples[ $industry ] ) ? $industry_samples[ $industry ] : __( 'We help local customers get great results — friendly service, fair prices, and work you can trust.', 'easysite-pro' );

	if ( $context ) {
		$text = sprintf(
			/* translators: 1: site name, 2: short draft hint */
			__( '%1$s — %2$s Let us help you take the next step with confidence.', 'easysite-pro' ),
			$site,
			wp_trim_words( $context, 8, '…' )
		);
	}

	return apply_filters( 'easysite_ve_ai_demo_text', $text, $type, $context );
}

/* ── Global sections library ──────────────────────────────── */

/**
 * Get saved global sections.
 *
 * @return array
 */
function easysite_get_global_sections() {
	$sections = get_option( 'easysite_global_sections', array() );
	return is_array( $sections ) ? $sections : array();
}

/**
 * AJAX: save global section.
 */
function easysite_ajax_ve_save_global_section() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	if ( ! current_user_can( 'edit_theme_options' ) ) {
		wp_send_json_error();
	}
	$label = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : __( 'Saved section', 'easysite-pro' );
	$raw   = isset( $_POST['block'] ) ? wp_unslash( $_POST['block'] ) : ''; // phpcs:ignore
	$block = json_decode( $raw, true );
	if ( ! is_array( $block ) ) {
		wp_send_json_error();
	}
	$sections   = easysite_get_global_sections();
	$sections[] = array(
		'id'    => 'global_' . wp_generate_password( 8, false ),
		'label' => $label,
		'block' => $block,
	);
	update_option( 'easysite_global_sections', $sections );
	wp_send_json_success( array( 'sections' => $sections ) );
}
add_action( 'wp_ajax_easysite_ve_save_global_section', 'easysite_ajax_ve_save_global_section' );

/**
 * AJAX: AI suggest for visual editor.
 */
function easysite_ajax_ve_ai_suggest() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	if ( ! current_user_can( 'edit_posts' ) ) {
		wp_send_json_error();
	}
	$type    = isset( $_POST['suggest_type'] ) ? sanitize_key( wp_unslash( $_POST['suggest_type'] ) ) : 'general';
	$context = isset( $_POST['context'] ) ? sanitize_textarea_field( wp_unslash( $_POST['context'] ) ) : '';
	if ( ! function_exists( 'easysite_ai_request_suggestion' ) || ! function_exists( 'easysite_ai_uses_live_api' ) || ! easysite_ai_uses_live_api() ) {
		wp_send_json_success( array( 'text' => easysite_ve_ai_demo_text( $type, $context ), 'demo' => true ) );
	}
	$result = easysite_ai_request_suggestion( $type, $context );
	if ( is_wp_error( $result ) ) {
		wp_send_json_success( array( 'text' => easysite_ve_ai_demo_text( $type, $context ), 'demo' => true ) );
	}
	wp_send_json_success( array( 'text' => $result, 'demo' => false ) );
}
add_action( 'wp_ajax_easysite_ve_ai_suggest', 'easysite_ajax_ve_ai_suggest' );

/**
 * AJAX: get primary menu items for VE editor.
 */
function easysite_ajax_ve_get_menu() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	if ( ! current_user_can( 'edit_theme_options' ) ) {
		wp_send_json_error();
	}
	$locations = get_nav_menu_locations();
	$items     = array();
	if ( ! empty( $locations['primary'] ) ) {
		$menu_items = wp_get_nav_menu_items( $locations['primary'] );
		if ( $menu_items ) {
			foreach ( $menu_items as $item ) {
				if ( 0 !== (int) $item->menu_item_parent ) {
					continue;
				}
				$items[] = array(
					'id'    => $item->ID,
					'title' => $item->title,
					'url'   => $item->url,
				);
			}
		}
	}
	wp_send_json_success( array( 'items' => $items, 'menu_id' => $locations['primary'] ?? 0 ) );
}
add_action( 'wp_ajax_easysite_ve_get_menu', 'easysite_ajax_ve_get_menu' );

/**
 * AJAX: update menu item from VE.
 */
function easysite_ajax_ve_update_menu_item() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	if ( ! current_user_can( 'edit_theme_options' ) ) {
		wp_send_json_error();
	}
	$item_id = isset( $_POST['item_id'] ) ? absint( $_POST['item_id'] ) : 0;
	$title   = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
	$url     = isset( $_POST['url'] ) ? esc_url_raw( wp_unslash( $_POST['url'] ) ) : '';
	if ( ! $item_id ) {
		wp_send_json_error();
	}
	wp_update_nav_menu_item( 0, $item_id, array(
		'menu-item-title'  => $title,
		'menu-item-url'    => $url,
		'menu-item-status' => 'publish',
	) );
	wp_send_json_success();
}
add_action( 'wp_ajax_easysite_ve_update_menu_item', 'easysite_ajax_ve_update_menu_item' );

/**
 * AJAX: save popup settings from VE.
 */
function easysite_ajax_ve_save_popup() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	if ( ! current_user_can( 'edit_theme_options' ) ) {
		wp_send_json_error();
	}
	$fields = array( 'easysite_popup_title', 'easysite_popup_text', 'easysite_popup_button_text', 'easysite_popup_button_link' );
	foreach ( $fields as $key ) {
		if ( isset( $_POST[ $key ] ) ) {
			set_theme_mod( $key, sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) );
		}
	}
	if ( isset( $_POST['easysite_popup_enabled'] ) ) {
		set_theme_mod( 'easysite_popup_enabled', ! empty( $_POST['easysite_popup_enabled'] ) );
	}
	wp_send_json_success();
}
add_action( 'wp_ajax_easysite_ve_save_popup', 'easysite_ajax_ve_save_popup' );

/**
 * AJAX: dismiss guided tour.
 */
function easysite_ajax_ve_dismiss_tour() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	$user_id = get_current_user_id();
	if ( $user_id ) {
		update_user_meta( $user_id, 'easysite_ve_tour_done', 1 );
	}
	wp_send_json_success();
}
add_action( 'wp_ajax_easysite_ve_dismiss_tour', 'easysite_ajax_ve_dismiss_tour' );

/**
 * Page layout templates for VE.
 *
 * @return array
 */
function easysite_ve_page_templates() {
	return array(
		'landing' => array(
			'label'  => __( 'Landing page', 'easysite-pro' ),
			'layout' => array(
				array( 'id' => 'tpl_hero', 'type' => 'hero', 'fields' => array( 'title' => __( 'Your Big Idea Starts Here', 'easysite-pro' ), 'subtitle' => __( 'Tell visitors what you do and why it matters.', 'easysite-pro' ), 'button_text' => __( 'Get Started', 'easysite-pro' ), 'button_url' => '/contact', 'style' => 'gradient-overlay', 'gradient' => 'brand' ), 'design' => easysite_get_default_block_design() ),
				array( 'id' => 'tpl_services', 'type' => 'services', 'fields' => array( 'title' => __( 'What We Offer', 'easysite-pro' ), 'item1_title' => __( 'Service One', 'easysite-pro' ), 'item1_text' => __( 'Describe your first service.', 'easysite-pro' ) ), 'design' => easysite_get_default_block_design() ),
				array( 'id' => 'tpl_cta', 'type' => 'cta', 'fields' => array( 'title' => __( 'Ready to begin?', 'easysite-pro' ), 'subtitle' => __( 'Contact us today.', 'easysite-pro' ), 'button_text' => __( 'Contact Us', 'easysite-pro' ), 'button_url' => '/contact', 'style' => 'gradient', 'gradient' => 'brand' ), 'design' => easysite_get_default_block_design() ),
			),
		),
		'about' => array(
			'label'  => __( 'About page', 'easysite-pro' ),
			'layout' => array(
				array( 'id' => 'tpl_about', 'type' => 'image_text', 'fields' => array( 'title' => __( 'About Us', 'easysite-pro' ), 'content' => __( 'Share your story and build trust with visitors.', 'easysite-pro' ), 'layout' => 'right' ), 'design' => easysite_get_default_block_design() ),
				array( 'id' => 'tpl_team', 'type' => 'team', 'fields' => array( 'title' => __( 'Meet the Team', 'easysite-pro' ), 'm1_name' => __( 'Team Member', 'easysite-pro' ), 'm1_role' => __( 'Founder', 'easysite-pro' ) ), 'design' => easysite_get_default_block_design() ),
			),
		),
		'pricing' => array(
			'label'  => __( 'Pricing page', 'easysite-pro' ),
			'layout' => array(
				array( 'id' => 'tpl_pricing', 'type' => 'pricing', 'fields' => array( 'title' => __( 'Our Plans', 'easysite-pro' ), 'p1_name' => __( 'Starter', 'easysite-pro' ), 'p1_price' => '£25/mo', 'p1_desc' => __( 'Perfect for getting started.', 'easysite-pro' ), 'p2_name' => __( 'Pro', 'easysite-pro' ), 'p2_price' => '£49/mo', 'p2_desc' => __( 'Most popular choice.', 'easysite-pro' ) ), 'design' => easysite_get_default_block_design() ),
				array( 'id' => 'tpl_faq', 'type' => 'faq', 'fields' => array( 'title' => __( 'FAQ', 'easysite-pro' ), 'q1' => __( 'How do I get started?', 'easysite-pro' ), 'a1' => __( 'Contact us for a free consultation.', 'easysite-pro' ) ), 'design' => easysite_get_default_block_design() ),
			),
		),
	);
}

/**
 * AJAX: save brand colors from visual editor.
 */
function easysite_ajax_ve_save_brand_colors() {
	check_ajax_referer( 'easysite_ve_nonce', 'nonce' );
	if ( ! current_user_can( 'edit_theme_options' ) ) {
		wp_send_json_error();
	}
	if ( isset( $_POST['main_color'] ) ) {
		set_theme_mod( 'easysite_main_color', easysite_sanitize_hex_color( wp_unslash( $_POST['main_color'] ) ) );
	}
	if ( isset( $_POST['accent_color'] ) ) {
		set_theme_mod( 'easysite_accent_color', easysite_sanitize_hex_color( wp_unslash( $_POST['accent_color'] ) ) );
	}
	wp_send_json_success();
}
add_action( 'wp_ajax_easysite_ve_save_brand_colors', 'easysite_ajax_ve_save_brand_colors' );
