<?php
/**
 * Data access for Niwa template cards.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Template_Repository {
	public function list_templates( $type = '', $limit = 40 ) {
		$type  = '' !== (string) $type ? Niwa_AI_Template_Library_Types::normalize_template_type( $type ) : '';
		$limit = max( 1, min( 100, intval( $limit ) ) );

		$args = array(
			'post_type'      => Niwa_AI_Template_Library_Types::CPT_TEMPLATE,
			'post_status'    => array( 'publish', 'draft' ),
			'posts_per_page' => $limit,
			'orderby'        => array(
				'menu_order' => 'ASC',
				'title'      => 'ASC',
			),
		);

		if ( '' !== $type ) {
			$args['meta_query'] = array(
				array(
					'key'   => Niwa_AI_Template_Library_Types::META_TYPE,
					'value' => $type,
				),
			);
		}

		$posts = get_posts( $args );
		return array_map( array( $this, 'format_template' ), $posts );
	}

	public function get_template( $template_id ) {
		$post = get_post( intval( $template_id ) );
		if ( ! $post || Niwa_AI_Template_Library_Types::CPT_TEMPLATE !== $post->post_type ) {
			return null;
		}
		return $this->format_template( $post );
	}

	public function find_by_slug( $slug ) {
		$slug  = sanitize_title( (string) $slug );
		$posts = get_posts(
			array(
				'name'           => $slug,
				'post_type'      => Niwa_AI_Template_Library_Types::CPT_TEMPLATE,
				'post_status'    => array( 'publish', 'draft' ),
				'posts_per_page' => 1,
			)
		);
		return ! empty( $posts ) ? $posts[0] : null;
	}

	public function upsert_seed_template( $seed, $order = 0 ) {
		$slug = isset( $seed['slug'] ) ? sanitize_title( $seed['slug'] ) : '';
		if ( '' === $slug ) {
			return 0;
		}

		$post = $this->find_by_slug( $slug );
		$data = array(
			'post_title'   => sanitize_text_field( isset( $seed['title'] ) ? $seed['title'] : $slug ),
			'post_name'    => $slug,
			'post_type'    => Niwa_AI_Template_Library_Types::CPT_TEMPLATE,
			'post_status'  => 'publish',
			'menu_order'   => intval( $order ),
			'post_content' => '',
		);

		if ( $post ) {
			$data['ID'] = $post->ID;
			$post_id    = wp_update_post( $data, true );
		} else {
			$post_id = wp_insert_post( $data, true );
		}

		if ( is_wp_error( $post_id ) || intval( $post_id ) <= 0 ) {
			return 0;
		}

		$post_id = intval( $post_id );
		$type    = Niwa_AI_Template_Library_Types::normalize_template_type( isset( $seed['type'] ) ? $seed['type'] : '' );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_TYPE, $type );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_SUBTITLE, sanitize_text_field( isset( $seed['subtitle'] ) ? $seed['subtitle'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_PROMPT, wp_kses_post( isset( $seed['prompt'] ) ? $seed['prompt'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_AGENT_PROMPT, sanitize_textarea_field( isset( $seed['agent_prompt'] ) ? $seed['agent_prompt'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_PREVIEW_URL, esc_url_raw( isset( $seed['preview_url'] ) ? $seed['preview_url'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_PREVIEW_PROMPT, sanitize_textarea_field( isset( $seed['preview_prompt'] ) ? $seed['preview_prompt'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_OUTPUT_MODE, sanitize_key( isset( $seed['output_mode'] ) ? $seed['output_mode'] : Niwa_AI_Template_Library_Types::default_output_mode_for_type( $type ) ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_ORIGIN, 'seeded' );
		if ( ! empty( $seed['elementor_schema'] ) && is_array( $seed['elementor_schema'] ) ) {
			update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_ELEMENTOR_SCHEMA, $seed['elementor_schema'] );
		}
		if ( ! empty( $seed['manifest'] ) && is_array( $seed['manifest'] ) ) {
			update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_MANIFEST, $seed['manifest'] );
		}
		wp_set_object_terms( $post_id, $type, Niwa_AI_Template_Library_Types::TAXONOMY, false );

		return $post_id;
	}

	public function create_custom_template( $args ) {
		$type  = Niwa_AI_Template_Library_Types::normalize_template_type( isset( $args['type'] ) ? $args['type'] : '' );
		$title = sanitize_text_field( isset( $args['title'] ) ? $args['title'] : '' );
		if ( '' === $title ) {
			return new WP_Error( 'missing_title', __( 'Template title is required.', 'niwa-ai' ) );
		}

		$post_id = wp_insert_post(
			array(
				'post_title'  => $title,
				'post_type'   => Niwa_AI_Template_Library_Types::CPT_TEMPLATE,
				'post_status' => 'publish',
			),
			true
		);
		if ( is_wp_error( $post_id ) ) {
			return $post_id;
		}

		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_TYPE, $type );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_SUBTITLE, sanitize_text_field( isset( $args['subtitle'] ) ? $args['subtitle'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_PROMPT, wp_kses_post( isset( $args['prompt'] ) ? $args['prompt'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_AGENT_PROMPT, sanitize_textarea_field( isset( $args['agent_prompt'] ) ? $args['agent_prompt'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_PREVIEW_URL, esc_url_raw( isset( $args['preview_url'] ) ? $args['preview_url'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_PREVIEW_PROMPT, sanitize_textarea_field( isset( $args['preview_prompt'] ) ? $args['preview_prompt'] : '' ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_OUTPUT_MODE, sanitize_key( isset( $args['output_mode'] ) ? $args['output_mode'] : Niwa_AI_Template_Library_Types::default_output_mode_for_type( $type ) ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_ORIGIN, 'ai_created' );
		if ( ! empty( $args['elementor_schema'] ) && is_array( $args['elementor_schema'] ) ) {
			update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_ELEMENTOR_SCHEMA, $args['elementor_schema'] );
		}
		if ( ! empty( $args['manifest'] ) && is_array( $args['manifest'] ) ) {
			update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_MANIFEST, $args['manifest'] );
		}
		wp_set_object_terms( $post_id, $type, Niwa_AI_Template_Library_Types::TAXONOMY, false );

		return $this->format_template( get_post( $post_id ) );
	}

	public function format_template( $post ) {
		if ( ! $post ) {
			return array();
		}
		$type       = Niwa_AI_Template_Library_Types::normalize_template_type( get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_TYPE, true ) );
		$preview_id = intval( get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_PREVIEW_ID, true ) );
		$preview    = $preview_id > 0 ? wp_get_attachment_image_url( $preview_id, 'large' ) : '';
		if ( ! $preview ) {
			$preview = (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_PREVIEW_URL, true );
		}

		return array(
			'id'             => intval( $post->ID ),
			'slug'           => (string) $post->post_name,
			'title'          => (string) $post->post_title,
			'subtitle'       => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_SUBTITLE, true ),
			'type'           => $type,
			'type_label'     => Niwa_AI_Template_Library_Types::label( $type ),
			'prompt'         => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_PROMPT, true ),
			'agent_prompt'   => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_AGENT_PROMPT, true ),
			'preview_url'    => $preview,
			'preview_prompt' => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_PREVIEW_PROMPT, true ),
			'output_mode'    => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_OUTPUT_MODE, true ),
			'elementor_schema' => $this->read_array_meta( $post->ID, Niwa_AI_Template_Library_Types::META_ELEMENTOR_SCHEMA ),
			'manifest'       => $this->read_array_meta( $post->ID, Niwa_AI_Template_Library_Types::META_MANIFEST ),
			'origin'         => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_ORIGIN, true ),
			'updated_at'     => (string) $post->post_modified_gmt,
		);
	}

	private function read_array_meta( $post_id, $key ) {
		$value = get_post_meta( $post_id, $key, true );
		return is_array( $value ) ? $value : array();
	}
}
