<?php
/**
 * Elementor page builder tools for public reference URLs.
 *
 * @package Niwa_AI
 */

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

trait Niwa_AI_Tools_Elementor_URL_Builder {
	private function preview_elementor_build_page_from_url( $args ) {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		if ( ! is_plugin_active( 'elementor/elementor.php' ) ) {
			return array( 'success' => false, 'error' => 'Elementor plugin nije aktivan.' );
		}

		$url = isset( $args['url'] ) ? esc_url_raw( trim( (string) $args['url'] ) ) : '';
		if ( '' === $url ) {
			return array( 'success' => false, 'error' => 'url je obavezan.' );
		}

		$post_id = isset( $args['post_id'] ) ? intval( $args['post_id'] ) : 0;
		$mode    = isset( $args['mode'] ) ? sanitize_key( (string) $args['mode'] ) : ( $post_id > 0 ? 'replace' : 'create' );
		if ( ! in_array( $mode, array( 'create', 'replace', 'append' ), true ) ) {
			$mode = $post_id > 0 ? 'replace' : 'create';
		}

		$status = isset( $args['status'] ) && in_array( (string) $args['status'], array( 'draft', 'publish', 'pending', 'private' ), true )
			? (string) $args['status']
			: 'draft';

		$title = isset( $args['title'] ) ? sanitize_text_field( trim( (string) $args['title'] ) ) : '';
		if ( $post_id > 0 ) {
			$post = get_post( $post_id );
			if ( ! $post ) {
				return array( 'success' => false, 'error' => 'Post ID ' . $post_id . ' nije pronadjen.' );
			}
			if ( 'create' === $mode ) {
				$mode = 'replace';
			}
			if ( '' === $title ) {
				$title = (string) $post->post_title;
			}
		}

		if ( 0 === $post_id && 'create' !== $mode ) {
			return array( 'success' => false, 'error' => 'post_id je obavezan za replace/append mode.' );
		}
		if ( '' === $title ) {
			$title = $this->elementor_url_builder_title_from_url( $url );
		}

		$summary = 'Izgradnja native Elementor stranice iz reference URL-a: ' . $url . '. Mode: ' . $mode . '.';
		if ( $post_id > 0 ) {
			$summary .= ' Target post ID: ' . $post_id . '.';
		} else {
			$summary .= ' Nova stranica: "' . $title . '" (' . $status . ').';
		}

		return array(
			'success' => true,
			'action'  => array(
				'type'             => 'elementor_build_page_from_url',
				'label'            => 'Build native Elementor page from URL',
				'summary'          => $summary,
				'rollback_plan'    => $post_id > 0 ? 'Vraca prethodni _elementor_data i post_content.' : 'Novokreirana stranica se premesta u korpu.',
				'rollback_support' => 'full',
				'targets'          => array(
					array(
						'type'    => $post_id > 0 ? 'post' : 'new_page',
						'post_id' => $post_id,
						'label'   => $title,
					),
				),
				'args'             => array(
					'url'          => $url,
					'post_id'      => $post_id,
					'title'        => $title,
					'status'       => $status,
					'mode'         => $mode,
					'instructions' => isset( $args['instructions'] ) ? (string) $args['instructions'] : '',
				),
			),
		);
	}

	private function validate_elementor_build_page_from_url_args( $args ) {
		$url = isset( $args['url'] ) ? trim( (string) $args['url'] ) : '';
		if ( '' === $url ) {
			return array( 'success' => false, 'error' => 'url je obavezan.' );
		}
		$parts = wp_parse_url( $url );
		if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) || ! in_array( strtolower( (string) $parts['scheme'] ), array( 'http', 'https' ), true ) ) {
			return array( 'success' => false, 'error' => 'url mora biti javni http/https URL.' );
		}
		$post_id = isset( $args['post_id'] ) ? intval( $args['post_id'] ) : 0;
		$mode    = isset( $args['mode'] ) ? sanitize_key( (string) $args['mode'] ) : ( $post_id > 0 ? 'replace' : 'create' );
		if ( in_array( $mode, array( 'replace', 'append' ), true ) && $post_id <= 0 ) {
			return array( 'success' => false, 'error' => 'post_id je obavezan za replace/append.' );
		}
		return array( 'success' => true );
	}

	private function execute_elementor_build_page_from_url_action( $action ) {
		$args = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
		$url  = isset( $args['url'] ) ? esc_url_raw( trim( (string) $args['url'] ) ) : '';
		if ( '' === $url ) {
			return array( 'success' => false, 'error' => 'url je obavezan.' );
		}

		$builder = new Niwa_AI_Elementor_URL_Blueprint_Builder( $this->eval_openai_client, $this->eval_auth_manager, $this->eval_model_router );
		$built   = $builder->build_elements_from_url( $url, isset( $args['instructions'] ) ? (string) $args['instructions'] : '' );
		if ( empty( $built['success'] ) ) {
			return $built;
		}

		$elements     = isset( $built['elements'] ) && is_array( $built['elements'] ) ? $built['elements'] : array();
		$post_content = isset( $built['post_content'] ) ? (string) $built['post_content'] : '';
		$post_id      = isset( $args['post_id'] ) ? intval( $args['post_id'] ) : 0;
		$mode         = isset( $args['mode'] ) ? sanitize_key( (string) $args['mode'] ) : ( $post_id > 0 ? 'replace' : 'create' );
		$status       = isset( $args['status'] ) && in_array( (string) $args['status'], array( 'draft', 'publish', 'pending', 'private' ), true ) ? (string) $args['status'] : 'draft';
		$title        = isset( $args['title'] ) && '' !== trim( (string) $args['title'] ) ? sanitize_text_field( (string) $args['title'] ) : $this->elementor_url_builder_title_from_url( $url );

		if ( $post_id <= 0 ) {
			$post_id = wp_insert_post(
				array(
					'post_type'      => 'page',
					'post_title'     => $title,
					'post_status'    => $status,
					'post_content'   => $post_content,
					'comment_status' => 'closed',
				),
				true
			);
			if ( is_wp_error( $post_id ) ) {
				return array( 'success' => false, 'error' => $post_id->get_error_message() );
			}
			$this->elementor_url_builder_mark_post_as_elementor( $post_id );
			if ( ! empty( $built['blueprint']['specialized_blueprint'] ) ) {
				update_post_meta( $post_id, '_wp_page_template', 'elementor_canvas' );
			}
			$this->save_elementor_data( $post_id, $elements );

			return $this->elementor_url_builder_result( $post_id, $built, 'created', array( array( 'type' => 'page_delete', 'page_id' => $post_id ) ) );
		}

		$post = get_post( $post_id );
		if ( ! $post ) {
			return array( 'success' => false, 'error' => 'Post ID ' . $post_id . ' nije pronadjen.' );
		}

		$current_raw  = (string) get_post_meta( $post_id, '_elementor_data', true );
		$current_data = json_decode( $current_raw, true );
		if ( ! is_array( $current_data ) ) {
			$current_data = array();
		}

		$updated_data = 'append' === $mode ? array_merge( array_values( $current_data ), array_values( $elements ) ) : array_values( $elements );

		$this->elementor_url_builder_mark_post_as_elementor( $post_id );
		$result = $this->execute_elementor_update_page_data_action(
			array(
				'args' => array(
					'post_id'                 => $post_id,
					'elementor_data_json'     => wp_json_encode( $updated_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ),
					'expected_current_sha256' => hash( 'sha256', $current_raw ),
					'post_content'            => $post_content,
					'has_post_content'        => true,
				),
			)
		);
		if ( empty( $result['success'] ) ) {
			return $result;
		}

		$summary = $this->elementor_url_builder_result( $post_id, $built, 'updated_' . $mode, isset( $result['rollback_entries'] ) ? $result['rollback_entries'] : array() );
		$summary['current_sha256'] = isset( $result['current_sha256'] ) ? (string) $result['current_sha256'] : '';
		return $summary;
	}

	private function elementor_url_builder_mark_post_as_elementor( $post_id ) {
		update_post_meta( $post_id, '_elementor_edit_mode', 'builder' );
		update_post_meta( $post_id, '_elementor_template_type', 'wp-page' );
		if ( defined( 'ELEMENTOR_VERSION' ) ) {
			update_post_meta( $post_id, '_elementor_version', ELEMENTOR_VERSION );
		}
	}

	private function elementor_url_builder_result( $post_id, $built, $operation, $rollback_entries ) {
		$counts = $this->elementor_url_builder_count_elements( isset( $built['elements'] ) ? $built['elements'] : array() );
		$link   = get_permalink( $post_id );
		$edit   = admin_url( 'post.php?post=' . intval( $post_id ) . '&action=elementor' );

		return array(
			'success'          => true,
			'summary'          => 'Niwa je izgradila native Elementor stranicu iz reference URL-a. Operacija: ' . $operation . '. Sekcije: ' . $counts['sections'] . ', widgeti: ' . $counts['widgets'] . ', html widgeti: ' . $counts['html_widgets'] . '.',
			'post_id'          => intval( $post_id ),
			'view_url'         => $link,
			'elementor_edit_url' => $edit,
			'source_url'       => isset( $built['blueprint']['source_url'] ) ? (string) $built['blueprint']['source_url'] : '',
			'sections'         => $counts['sections'],
			'widgets'          => $counts['widgets'],
			'widget_types'     => $counts['widget_types'],
			'html_widgets'     => $counts['html_widgets'],
			'llm_used'         => ! empty( $built['llm_used'] ),
			'llm_error'        => isset( $built['llm_error'] ) ? (string) $built['llm_error'] : '',
			'blueprint_title'  => isset( $built['blueprint']['title'] ) ? (string) $built['blueprint']['title'] : '',
			'executed_actions' => array(
				array(
					'type'      => 'elementor_build_page_from_url',
					'post_id'   => intval( $post_id ),
					'operation' => $operation,
				),
			),
			'rollback_entries' => is_array( $rollback_entries ) ? $rollback_entries : array(),
		);
	}

	private function elementor_url_builder_count_elements( $elements ) {
		$result = array(
			'sections'     => 0,
			'widgets'      => 0,
			'html_widgets' => 0,
			'widget_types' => array(),
		);
		$this->elementor_url_builder_count_elements_walk( $elements, $result, true );
		$result['widget_types'] = array_keys( $result['widget_types'] );
		sort( $result['widget_types'] );
		return $result;
	}

	private function elementor_url_builder_count_elements_walk( $elements, &$result, $top_level = false ) {
		if ( ! is_array( $elements ) ) {
			return;
		}
		foreach ( $elements as $element ) {
			if ( ! is_array( $element ) ) {
				continue;
			}
			$el_type = isset( $element['elType'] ) ? (string) $element['elType'] : '';
			if ( $top_level && 'container' === $el_type ) {
				$result['sections']++;
			}
			if ( 'widget' === $el_type ) {
				$result['widgets']++;
				$widget_type = isset( $element['widgetType'] ) ? sanitize_key( (string) $element['widgetType'] ) : '';
				if ( '' !== $widget_type ) {
					$result['widget_types'][ $widget_type ] = true;
					if ( 'html' === $widget_type ) {
						$result['html_widgets']++;
					}
				}
			}
			if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
				$this->elementor_url_builder_count_elements_walk( $element['elements'], $result, false );
			}
		}
	}

	private function elementor_url_builder_title_from_url( $url ) {
		$host = wp_parse_url( (string) $url, PHP_URL_HOST );
		$host = $host ? preg_replace( '/^www\./', '', (string) $host ) : 'reference';
		return 'Niwa reference rebuild - ' . sanitize_text_field( $host );
	}
}
