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

class DC_V2_Field_Template {

	public static function init() {
		add_action( 'init', array( __CLASS__, 'register' ) );
	}

	public static function register() {
		register_post_type(
			DC_V2_TEMPLATE_CPT,
			array(
				'labels'          => array(
					'name'          => 'Plantillas de campos',
					'singular_name' => 'Plantilla',
				),
				'public'          => false,
				'show_ui'         => false,
				'capability_type' => 'post',
				'supports'        => array( 'title' ),
			)
		);
	}

	public static function fields_hash( $product_id, $variation_id, $fields ) {
		$keys = array();
		foreach ( (array) $fields as $f ) {
			$keys[] = $f['key'] ?? $f['id'] ?? '';
		}
		sort( $keys );
		return md5( (int) $product_id . ':' . (int) $variation_id . ':' . implode( ',', $keys ) );
	}

	public static function save_template( $name, $product_id, $variation_id, $fields ) {
		$hash = self::fields_hash( $product_id, $variation_id, $fields );
		$existing = self::find_by_hash( $hash );
		if ( $existing ) {
			return $existing;
		}
		$id = wp_insert_post(
			array(
				'post_type'   => DC_V2_TEMPLATE_CPT,
				'post_title'  => sanitize_text_field( $name ),
				'post_status' => 'publish',
			),
			true
		);
		if ( is_wp_error( $id ) ) {
			return $id;
		}
		update_post_meta( $id, '_dc_v2_tpl_product_id', (int) $product_id );
		update_post_meta( $id, '_dc_v2_tpl_variation_id', (int) $variation_id );
		update_post_meta( $id, '_dc_v2_tpl_fields', $fields );
		update_post_meta( $id, '_dc_v2_tpl_hash', $hash );
		return (int) $id;
	}

	public static function find_by_hash( $hash ) {
		$q = new WP_Query(
			array(
				'post_type'      => DC_V2_TEMPLATE_CPT,
				'post_status'    => 'publish',
				'posts_per_page' => 1,
				'meta_query'     => array(
					array(
						'key'   => '_dc_v2_tpl_hash',
						'value' => $hash,
					),
				),
			)
		);
		return $q->have_posts() ? (int) $q->posts[0]->ID : 0;
	}

	public static function list_templates( $product_id = 0, $variation_id = 0 ) {
		$args = array(
			'post_type'      => DC_V2_TEMPLATE_CPT,
			'post_status'    => 'publish',
			'posts_per_page' => 50,
			'orderby'        => 'date',
			'order'          => 'DESC',
		);
		if ( $product_id ) {
			$args['meta_query'] = array(
				array(
					'key'   => '_dc_v2_tpl_product_id',
					'value' => (int) $product_id,
				),
			);
		}
		$q   = new WP_Query( $args );
		$out = array();
		$seen = array();
		foreach ( $q->posts as $post ) {
			$hash = get_post_meta( $post->ID, '_dc_v2_tpl_hash', true );
			if ( isset( $seen[ $hash ] ) ) {
				continue;
			}
			$seen[ $hash ] = true;
			$vid = (int) get_post_meta( $post->ID, '_dc_v2_tpl_variation_id', true );
			if ( $variation_id && $vid && $vid !== $variation_id ) {
				continue;
			}
			$out[] = array(
				'id'           => $post->ID,
				'name'         => $post->post_title,
				'product_id'   => (int) get_post_meta( $post->ID, '_dc_v2_tpl_product_id', true ),
				'variation_id' => $vid,
				'fields'       => get_post_meta( $post->ID, '_dc_v2_tpl_fields', true ) ?: array(),
				'hash'         => $hash,
			);
		}
		return $out;
	}

	public static function list_recent( $limit = 20 ) {
		$q = new WP_Query(
			array(
				'post_type'      => DC_V2_TEMPLATE_CPT,
				'post_status'    => 'publish',
				'posts_per_page' => (int) $limit,
				'orderby'        => 'date',
				'order'          => 'DESC',
			)
		);
		$out  = array();
		$seen = array();
		foreach ( $q->posts as $post ) {
			$hash = get_post_meta( $post->ID, '_dc_v2_tpl_hash', true );
			if ( isset( $seen[ $hash ] ) ) {
				continue;
			}
			$seen[ $hash ] = true;
			$out[] = array(
				'id'           => $post->ID,
				'name'         => $post->post_title,
				'product_id'   => (int) get_post_meta( $post->ID, '_dc_v2_tpl_product_id', true ),
				'variation_id' => (int) get_post_meta( $post->ID, '_dc_v2_tpl_variation_id', true ),
				'fields'       => get_post_meta( $post->ID, '_dc_v2_tpl_fields', true ) ?: array(),
				'hash'         => $hash,
			);
		}
		return $out;
	}

	public static function get_template( $id ) {
		$post = get_post( (int) $id );
		if ( ! $post || DC_V2_TEMPLATE_CPT !== $post->post_type ) {
			return null;
		}
		return array(
			'id'           => $post->ID,
			'name'         => $post->post_title,
			'product_id'   => (int) get_post_meta( $post->ID, '_dc_v2_tpl_product_id', true ),
			'variation_id' => (int) get_post_meta( $post->ID, '_dc_v2_tpl_variation_id', true ),
			'fields'       => get_post_meta( $post->ID, '_dc_v2_tpl_fields', true ) ?: array(),
		);
	}
}
