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

class DC_V2_Document_CPT {

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

	public static function register() {
		register_post_type(
			DC_V2_CPT,
			array(
				'labels'          => array(
					'name'          => 'Pedidos compartidos',
					'singular_name' => 'Pedido compartido',
				),
				'public'          => false,
				'show_ui'         => false,
				'show_in_menu'    => false,
				'capability_type' => 'post',
				'supports'        => array( 'title' ),
			)
		);
	}

	public static function normalize_copy( $copy ) {
		return wp_parse_args( is_array( $copy ) ? $copy : array(), dc_v2_default_copy() );
	}

	public static function normalize_appearance( $appearance ) {
		$raw = is_array( $appearance ) ? $appearance : array();
		$app = wp_parse_args( $raw, dc_v2_default_appearance() );
		$speed = isset( $app['typing_speed'] ) ? (int) $app['typing_speed'] : 45;
		$app['typing_speed'] = (string) max( 0, min( 100, $speed ) );
		$app['badge_text'] = dc_v2_badge_text();
		$app['preset']     = sanitize_key( $app['preset'] ?? '' );
		if ( 'order4dm' === $app['preset'] ) {
			$app['preset'] = 'orderfromdm';
		}
		$theme_keys        = array( 'primary_foreground', 'card', 'card_foreground', 'muted', 'muted_foreground', 'border', 'input', 'footer', 'header', 'shadow' );
		$needs_theme       = false;
		foreach ( $theme_keys as $key ) {
			if ( ! isset( $raw[ $key ] ) || '' === $raw[ $key ] ) {
				$needs_theme = true;
				break;
			}
		}
		if ( $needs_theme ) {
			$tokens = self::theme_tokens_for_appearance( $app );
			$app    = array_merge( $app, $tokens );
		}
		return $app;
	}

	private static function theme_tokens_for_appearance( $app ) {
		$preset = sanitize_key( $app['preset'] ?? '' );
		if ( 'orderfromdm' === $preset ) {
			return dc_v2_orderfromdm_appearance_tokens();
		}
		if ( 'dark' === $preset || self::is_dark_hex( $app['background'] ?? '' ) ) {
			return dc_v2_dark_appearance_tokens();
		}
		return dc_v2_light_appearance_tokens();
	}

	private static function is_dark_hex( $hex ) {
		$hex = ltrim( (string) $hex, '#' );
		if ( 3 === strlen( $hex ) ) {
			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
		}
		if ( 6 !== strlen( $hex ) || ! ctype_xdigit( $hex ) ) {
			return false;
		}
		$r = hexdec( substr( $hex, 0, 2 ) );
		$g = hexdec( substr( $hex, 2, 2 ) );
		$b = hexdec( substr( $hex, 4, 2 ) );
		return ( ( $r * 299 + $g * 587 + $b * 114 ) / 1000 ) < 128;
	}

	public static function get_meta( $post_id ) {
		$lines = get_post_meta( $post_id, '_dc_v2_lines', true );
		if ( ! is_array( $lines ) ) {
			$lines = array();
		}
		$payment_methods = get_post_meta( $post_id, '_dc_v2_payment_methods', true );
		return array(
			'slug'             => get_post_meta( $post_id, '_dc_v2_slug', true ) ?: '',
			'status'           => get_post_meta( $post_id, '_dc_v2_status', true ) ?: 'draft',
			'copy'             => self::normalize_copy( get_post_meta( $post_id, '_dc_v2_copy', true ) ),
			'appearance'       => self::normalize_appearance( get_post_meta( $post_id, '_dc_v2_appearance', true ) ),
			'lines'            => $lines,
			'payment_methods'  => class_exists( 'DC_V2_Payment_Methods', false )
				? DC_V2_Payment_Methods::normalize( $payment_methods )
				: array( 'bacs' ),
		);
	}

	public static function save_meta( $post_id, $data ) {
		$slug = sanitize_title( $data['slug'] ?? '' );
		update_post_meta( $post_id, '_dc_v2_slug', $slug );
		// Keep WP post_name aligned with checkout slug (tickets / URLs use _dc_v2_slug).
		if ( $slug !== '' ) {
			$current = get_post( $post_id );
			if ( $current && (string) $current->post_name !== $slug ) {
				wp_update_post(
					array(
						'ID'        => (int) $post_id,
						'post_name' => $slug,
					)
				);
			}
		}
		$allowed_status = array( 'active', 'draft', 'trash' );
		$status         = in_array( $data['status'] ?? '', $allowed_status, true ) ? $data['status'] : 'draft';
		update_post_meta( $post_id, '_dc_v2_status', $status );
		update_post_meta( $post_id, '_dc_v2_copy', self::normalize_copy( $data['copy'] ?? array() ) );
		update_post_meta( $post_id, '_dc_v2_appearance', self::normalize_appearance( $data['appearance'] ?? array() ) );
		update_post_meta( $post_id, '_dc_v2_lines', is_array( $data['lines'] ?? null ) ? $data['lines'] : array() );
		$methods = class_exists( 'DC_V2_Payment_Methods', false )
			? DC_V2_Payment_Methods::normalize( $data['payment_methods'] ?? array() )
			: array( 'bacs' );
		update_post_meta( $post_id, '_dc_v2_payment_methods', $methods );
	}

	public static function find_by_slug( $slug ) {
		$slug = sanitize_title( $slug );
		if ( ! $slug ) {
			return null;
		}
		$q = new WP_Query(
			array(
				'post_type'      => DC_V2_CPT,
				'post_status'    => 'publish',
				'posts_per_page' => 1,
				'meta_query'     => array(
					array(
						'key'   => '_dc_v2_slug',
						'value' => $slug,
					),
				),
			)
		);
		if ( $q->have_posts() ) {
			return $q->posts[0];
		}
		// Fallback: older docs / mismatched meta vs post_name.
		$by_name = new WP_Query(
			array(
				'post_type'      => DC_V2_CPT,
				'post_status'    => 'publish',
				'posts_per_page' => 1,
				'name'           => $slug,
			)
		);
		if ( $by_name->have_posts() ) {
			$post = $by_name->posts[0];
			update_post_meta( $post->ID, '_dc_v2_slug', $slug );
			return $post;
		}
		return null;
	}

	public static function unique_slug( $base, $exclude_id = 0 ) {
		$base = sanitize_title( $base ) ?: 'pedido';
		$slug = $base;
		$i    = 2;
		while ( true ) {
			$found = self::find_by_slug( $slug );
			if ( ! $found || (int) $found->ID === (int) $exclude_id ) {
				return $slug;
			}
			$slug = $base . '-' . $i;
			$i++;
		}
	}

	public static function public_url( $slug ) {
		return home_url( '/c/' . rawurlencode( $slug ) . '/' );
	}

	public static function line_product_payload( $line ) {
		$pid = (int) ( $line['product_id'] ?? 0 );
		$vid = (int) ( $line['variation_id'] ?? 0 );
		$p   = $vid ? wc_get_product( $vid ) : wc_get_product( $pid );
		if ( ! $p ) {
			return null;
		}
		$image_id  = $p->get_image_id();
		$image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'thumbnail' ) : wc_placeholder_img_src();
		$attrs     = array();
		if ( ! empty( $line['selected_attributes'] ) && is_array( $line['selected_attributes'] ) ) {
			$attrs = $line['selected_attributes'];
		} elseif ( $p->is_type( 'variation' ) ) {
			$raw    = array_filter( $p->get_variation_attributes() );
			$parent = wc_get_product( $pid );
			if ( $parent instanceof WC_Product_Variable ) {
				foreach ( $parent->get_variation_attributes() as $label => $options ) {
					$key = 'attribute_' . sanitize_title( $label );
					if ( ! empty( $raw[ $key ] ) ) {
						$attrs[ $label ] = $raw[ $key ];
					}
				}
			} else {
				$attrs = $raw;
			}
		}
		return array(
			'product_id'          => $pid,
			'variation_id'        => $vid,
			'quantity'            => max( 1, (int) ( $line['quantity'] ?? 1 ) ),
			'skip_fields'         => ! empty( $line['skip_fields'] ),
			'fields'              => is_array( $line['fields'] ?? null ) ? $line['fields'] : array(),
			'name'                => $p->get_name(),
			'price'               => $p->get_price(),
			'image'               => $image_url,
			'url'                 => $p->get_permalink(),
			'attributes'          => $attrs,
			'selected_attributes' => $attrs,
		);
	}
}
