<?php

namespace WarrantyCart\Admin\Product;

use WC_Product;

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

/**
 * Admin Product Meta Class
 *
 * Handles product meta boxes for warranty settings.
 */
class Meta {

	/**
	 * Constructor
	 */
	public function __construct() {
		\add_filter( 'woocommerce_product_data_tabs', array( $this, 'add_warranty_tab' ) );
		\add_action( 'woocommerce_product_data_panels', array( $this, 'render_warranty_panel' ) );
		\add_action( 'save_post', array( $this, 'save_meta_boxes' ) );
	}

	/**
	 * Add warranty tab to WooCommerce product data
	 *
	 * @param array<string, array<string, mixed> $tabs Existing tabs.
	 *
	 * @return array<string, array<string, mixed> Modified tabs.
	 */
	public function add_warranty_tab( array $tabs ): array {
		/**
		 * Filter warranty tab data
		 *
		 * @param array $tab_data Tab configuration data.
		 */
		$warranty_tab = \apply_filters(
			'warranty_cart_product_warranty_tab',
			array(
				'label'    => \__( 'Warranty', 'warranty-cart' ),
				'target'   => 'warranty_product_data',
				'class'    => array( 'show_if_simple', 'show_if_variable' ),
				'priority' => 60,
			)
		);

		$tabs['warranty'] = $warranty_tab;

		return $tabs;
	}

	/**
	 * Render warranty panel in product data
	 */
	public function render_warranty_panel(): void {
		global $post;

		$product = wc_get_product( $post->ID );
		if ( ! $product instanceof WC_Product ) {
			return;
		}

		wp_nonce_field( 'warranty_product_meta', 'warranty_product_meta_nonce' );

		// Get existing meta values
		$warranty_status        = $product->get_meta( '_warranty_cart_product_status', true ) ? $product->get_meta( '_warranty_cart_product_status', true ) : 'disabled';
		$product_type           = $product->get_meta( '_warranty_cart_product_type', true ) ? $product->get_meta( '_warranty_cart_product_type', true ) : 'additional_service';
		$warranty_duration      = $product->get_meta( '_warranty_cart_duration', true ) ? $product->get_meta( '_warranty_cart_duration', true ) : '';
		$warranty_duration_unit = $product->get_meta( '_warranty_cart_duration_unit', true ) ? $product->get_meta( '_warranty_cart_duration_unit', true ) : 'years';
		$coverage_details       = $product->get_meta( '_warranty_cart_coverage_details', true ) ? $product->get_meta( '_warranty_cart_coverage_details', true ) : '';
		$associated_warranty    = $product->get_meta( '_warranty_cart_associated_warranty', true ) ? $product->get_meta( '_warranty_cart_associated_warranty', true ) : '';
		$service_priority       = $product->get_meta( '_warranty_cart_service_priority', true ) ? $product->get_meta( '_warranty_cart_service_priority', true ) : 'optional';

		// Get available main warranty products for association
		$main_warranties = $this->get_main_warranty_products();

		/**
		 * Filter warranty product meta box data
		 *
		 * @param array      $meta_data Meta box data.
		 * @param WC_Product $product   Product object.
		 */
		$meta_data = apply_filters(
			'warranty_cart_product_meta_data',
			array(
				'warranty_status'        => $warranty_status,
				'product_type'           => $product_type,
				'warranty_duration'      => $warranty_duration,
				'warranty_duration_unit' => $warranty_duration_unit,
				'coverage_details'       => $coverage_details,
				'associated_warranty'    => $associated_warranty,
				'service_priority'       => $service_priority,
				'main_warranties'        => $main_warranties,
			),
			$product
		);

		wc_get_template(
			'admin/product-meta-box.php',
			$meta_data,
			'warranty-cart',
			WARRANTY_CART_PATH . 'templates/'
		);
	}

	/**
	 * Save meta box data
	 *
	 * @param int $post_id Post ID.
	 */
	public function save_meta_boxes( int $post_id ): void {
		if ( ! isset( $_POST['warranty_product_meta_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['warranty_product_meta_nonce'] ) ), 'warranty_product_meta' ) ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		$product = wc_get_product( $post_id );
		if ( ! $product ) {
			return;
		}

		/**
		 * Action before saving warranty product meta
		 *
		 * @param WC_Product $product Product object.
		 * @param int        $post_id Post ID.
		 */
		do_action( 'warranty_cart_before_save_product_meta', $product, $post_id );

		// Save warranty status
		$warranty_status = isset( $_POST['warranty_cart_product_status'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['warranty_cart_product_status'] ) ) ? 'enabled' : 'disabled';
		$product->update_meta_data( '_warranty_cart_product_status', $warranty_status );

		// Only save other warranty fields if warranty is enabled
		if ( 'enabled' !== $warranty_status ) {
			$product->save();

			return;
		}

		// Save product type
		$product_type = isset( $_POST['warranty_cart_product_type'] ) ? sanitize_text_field( wp_unslash( $_POST['warranty_cart_product_type'] ) ) : 'additional_service';
		if ( in_array( $product_type, array( 'main_warranty', 'additional_service' ), true ) ) {
			$product->update_meta_data( '_warranty_cart_product_type', $product_type );
		}

		// Save warranty duration
		$warranty_duration = isset( $_POST['warranty_cart_duration'] ) ? absint( $_POST['warranty_cart_duration'] ) : '';
		$product->update_meta_data( '_warranty_cart_duration', $warranty_duration );

		// Save warranty duration unit
		$warranty_duration_unit = isset( $_POST['warranty_cart_duration_unit'] ) ? sanitize_text_field( wp_unslash( $_POST['warranty_cart_duration_unit'] ) ) : 'years';
		if ( in_array( $warranty_duration_unit, array( 'days', 'months', 'years' ), true ) ) {
			$product->update_meta_data( '_warranty_cart_duration_unit', $warranty_duration_unit );
		}

		// Save coverage details
		$coverage_details = isset( $_POST['warranty_cart_coverage_details'] ) ? sanitize_textarea_field( wp_unslash( $_POST['warranty_cart_coverage_details'] ) ) : '';
		$product->update_meta_data( '_warranty_cart_coverage_details', $coverage_details );

		// Save associated warranty (only for additional services)
		if ( 'additional_service' === $product_type ) {
			$associated_warranty = isset( $_POST['warranty_cart_associated_warranty'] ) ? absint( $_POST['warranty_cart_associated_warranty'] ) : '';
			$product->update_meta_data( '_warranty_cart_associated_warranty', $associated_warranty );
		} else {
			$product->delete_meta_data( '_warranty_cart_associated_warranty' );
		}

		// Save service priority
		$service_priority = isset( $_POST['warranty_cart_service_priority'] ) ? sanitize_text_field( wp_unslash( $_POST['warranty_cart_service_priority'] ) ) : 'optional';
		if ( in_array( $service_priority, array( 'required', 'recommended', 'optional' ), true ) ) {
			$product->update_meta_data( '_warranty_cart_service_priority', $service_priority );
		}

		$product->save();

		/**
		 * Action after saving warranty product meta
		 *
		 * @param WC_Product $product Product object.
		 * @param int        $post_id Post ID.
		 */
		do_action( 'warranty_cart_after_save_product_meta', $product, $post_id );
	}

	/**
	 * Get main warranty products for association dropdown
	 *
	 * @return array Array of main warranty products.
	 */
	private function get_main_warranty_products(): array {
		$args = array(
			'post_type'      => 'product',
			'posts_per_page' => - 1,
			'meta_query'     => array(
				array(
					'key'     => '_warranty_product_type',
					'value'   => 'main_warranty',
					'compare' => '=',
				),
			),
			'tax_query'      => array(
				array(
					'taxonomy' => 'product_type',
					'field'    => 'slug',
					'terms'    => 'simple',
				),
			),
		);

		$products = get_posts( $args );
		$options  = array( '' => __( 'Select a main warranty...', 'warranty-cart' ) );

		foreach ( $products as $product ) {
			$options[ $product->ID ] = $product->post_title;
		}

		return $options;
	}
}
