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

class Sifency_Addons_Editor_Template_Importer {
	private $remote_api_url = 'https://data-delta-five.vercel.app/data/';
	public function __construct() {
		add_action( 'elementor/editor/after_enqueue_scripts', array( $this, 'enqueue_editor_scripts' ) );
		add_action( 'elementor/preview/enqueue_styles', array( $this, 'enqueue_preview_styles' ) );
		add_action( 'elementor/editor/footer', array( $this, 'render_modal_html' ) );
		add_action( 'wp_ajax_sifency_fetch_library', array( $this, 'ajax_fetch_library' ) );
		add_action( 'wp_ajax_sifency_import_template', array( $this, 'ajax_import_template' ) );
	}

	public function enqueue_editor_scripts() {
		$base_url = plugin_dir_url( __FILE__ );
		wp_enqueue_style( 'sifency-editor-css', $base_url . 'assets/editor.css', array(), '2.0' );
		wp_enqueue_script( 'sifency-editor-js', $base_url . 'assets/editor.js', array( 'jquery', 'elementor-editor' ), '2.0', true );
		$logo_url = $base_url . 'assets/logo.png';

		$is_pro_active = class_exists( 'Sifency_Addons_Theme_Builder_Master' )
			? Sifency_Addons_Theme_Builder_Master::sync_environment_state()
			: false;

		wp_localize_script(
			'sifency-editor-js',
			'SifencyData',
			array(
				'ajaxurl'   => admin_url( 'admin-ajax.php' ),
				'nonce'     => wp_create_nonce( 'sifency_nonce' ),
				'logoUrl'   => $logo_url,
				'isPro'     => $is_pro_active,
				'proNotice' => esc_html__( 'Please activate your license to import this PRO template.', 'sifency-addons' ),
			)
		);
	}

	public function enqueue_preview_styles() {
		wp_enqueue_style( 'sifency-preview-css', plugin_dir_url( __FILE__ ) . 'assets/editor.css', array(), '2.0' );
	}

	public function ajax_fetch_library() {

		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
		}
		$cache_key = 'sifency_remote_library_v2';
		$cached    = get_transient( $cache_key );

		if ( $cached && is_array( $cached ) ) {
			wp_send_json_success( $cached );
		}

		$request_url = $this->remote_api_url . 'library.json';

		$response = wp_remote_get(
			$request_url,
			array(
				'timeout'     => 4,
				'redirection' => 3,
				'sslverify'   => true,
				'headers'     => array(
					'Accept' => 'application/json',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array( 'message' => 'Internet connection required.' ) );
		}

		if ( wp_remote_retrieve_response_code( $response ) !== 200 ) {
			wp_send_json_error( array( 'message' => 'Server response error.' ) );
		}

		$body = wp_remote_retrieve_body( $response );
		if ( empty( $body ) ) {
			wp_send_json_error( array( 'message' => 'Empty response.' ) );
		}

		$data = json_decode( $body, true );

		if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $data ) ) {
			wp_send_json_error( array( 'message' => 'Invalid library data.' ) );
		}

		set_transient( $cache_key, $data, 12 * HOUR_IN_SECONDS );

		wp_send_json_success( $data );
	}
	public function ajax_import_template() {
		// Verify nonce properly
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Security verification failed.' ) );
		}

		$template_id = isset( $_POST['template_id'] ) ? sanitize_text_field( $_POST['template_id'] ) : '';

		if ( empty( $template_id ) ) {
			wp_send_json_error( 'ID missing' );
		}

		$is_user_pro = class_exists( 'Sifency_Addons_Theme_Builder_Master' )
			? Sifency_Addons_Theme_Builder_Master::sync_environment_state()
			: false;

		$is_template_pro = isset( $_POST['is_pro'] ) && $_POST['is_pro'] === 'true';

		if ( $is_template_pro && ! $is_user_pro ) {
			wp_send_json_error( 'License Required: This is a PRO template. Please activate your license.' );
		}

		$file_url = $this->remote_api_url . 'templates/' . $template_id . '.json';

		$response = wp_remote_get(
			$file_url,
			array(
				'timeout'     => 5,
				'redirection' => 3,
				'sslverify'   => true,
				'headers'     => array(
					'Accept' => 'application/json',
				),
			)
		);

		if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) {
			wp_send_json_error( array( 'message' => 'Template download failed.' ) );
		}

		$body = wp_remote_retrieve_body( $response );
		if ( empty( $body ) ) {
			wp_send_json_error( array( 'message' => 'Empty template data.' ) );
		}

		$json_data = json_decode( $body, true );

		if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $json_data ) ) {
			wp_send_json_error( array( 'message' => 'Invalid template format.' ) );
		}

		$content = isset( $json_data['content'] ) ? $json_data['content'] : $json_data;

		wp_send_json_success( array( 'content' => $content ) );
	}

	public function render_modal_html() {
		?>
		<div id="sifency-modal" style="display:none;">
			<div class="sifency-modal-wrap">

				<div class="sifency-get-template-header">
					<div class="sifency-logo-area">
						<i class="eicon-library-upload"></i> <span>Sifency Library</span>
					</div>
					<div class="sifency-get-template-header-actions">
						<div class="sifency-search">
							<i class="eicon-search"></i>
							<input type="text" id="sifency-search-input" placeholder="Search templates...">
						</div>
						<label class="sifency-btn-upload">
							<i class="eicon-upload-circle-o"></i> Import JSON
							<input type="file" id="sifency-local-import" accept=".json" style="display:none;">
						</label>
						<div class="sifency-close" id="sifency-modal-close"><i class="eicon-close"></i></div>
					</div>
				</div>

				<div class="sifency-body">
					
					<div class="sifency-sidebar">
						<div class="sifency-nav-types">
							<button class="sifency-tab active" data-tab="block">Blocks</button>
							<button class="sifency-tab" data-tab="page">Pages</button>
							<button class="sifency-tab" data-tab="saved">My Favorites</button>
						</div>

						<div class="sifency-filter-label">Categories</div>
						
						<ul class="sifency-categories" id="sifency-cat-list">
							<li class="active" data-cat="all">All</li>

						</ul>
					</div>

					<div class="sifency-content">
						<div id="sifency-loader" style="display:none;">Loading...</div>
						<div id="sifency-grid" class="sifency-grid"></div>
					</div>

				</div>
			</div>
		</div>
		<?php
	}
}
new Sifency_Addons_Editor_Template_Importer();
