<?php
/**
 * WooCommerce product data tab integration for FoodOrd allergens.
 *
 * @package FoodOrd
 */

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

/**
 * Class Foodord_Product_Data_Allergens
 *
 * Handles the "Allergens" tab in WooCommerce product edit page.
 */
class Foodord_Product_Data_Allergens
{

    /**
     * Meta key for "Contains" field.
     */
    const META_CONTAINS = '_foodord_allergens_contains';

    /**
     * Meta key for "Not contain" field.
     */
    const META_NOT_CONTAIN = '_foodord_allergens_not_contain';

    /**
     * Meta key for "May contain" field.
     */
    const META_MAY_CONTAIN = '_foodord_allergens_may_contain';

    /**
     * Bootstrap hooks for WooCommerce product data integration.
     */
    public function init()
    {
        if (!is_admin()) {
            return;
        }

        add_filter('woocommerce_product_data_tabs', array($this, 'register_product_data_tab'), 99, 1);
        add_action('woocommerce_product_data_panels', array($this, 'render_product_data_panel'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_product_data_assets'), 999);
        add_action('woocommerce_process_product_meta', array($this, 'save_product_allergens'));
    }

    /**
     * Register Allergens tab under WooCommerce product data.
     *
     * @param array $tabs Existing product data tabs.
     *
     * @return array
     */
    public function register_product_data_tab($tabs)
    {
        $tabs['foodord_allergens'] = array(
            'label' => esc_html__('Allergens', 'foodord'),
            'target' => 'foodord_allergens_data',
            'class' => array('show_if_simple', 'show_if_variable', 'show_if_grouped', 'show_if_external'),
            'priority' => 85,
        );

        return $tabs;
    }

    /**
     * Enqueue scripts and styles for product data panel.
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_product_data_assets($hook)
    {
        if ('post.php' !== $hook && 'post-new.php' !== $hook) {
            return;
        }

        global $post;
        if (!$post || 'product' !== $post->post_type) {
            return;
        }

        wp_enqueue_style(
            'foodord-product-data-allergens',
            plugin_dir_url(__FILE__) . 'css/foodord-product-data-allergens.css',
            array('woocommerce_admin_styles'),
            FOODORD_VERSION
        );
    }

    /**
     * Save product allergens when product is saved.
     *
     * @param int $post_id Product ID.
     */
    public function save_product_allergens($post_id)
    {
        if (!isset($_POST['woocommerce_meta_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['woocommerce_meta_nonce'])), 'woocommerce_save_data')) {
            return;
        }

        if (!current_user_can('edit_posts')) {
            return;
        }

        $contains = '';
        if (isset($_POST[self::META_CONTAINS])) {
            $contains = sanitize_textarea_field(wp_unslash($_POST[self::META_CONTAINS]));
        }

        $not_contain = '';
        if (isset($_POST[self::META_NOT_CONTAIN])) {
            $not_contain = sanitize_textarea_field(wp_unslash($_POST[self::META_NOT_CONTAIN]));
        }

        $may_contain = '';
        if (isset($_POST[self::META_MAY_CONTAIN])) {
            $may_contain = sanitize_textarea_field(wp_unslash($_POST[self::META_MAY_CONTAIN]));
        }

        if ('' !== $contains) {
            update_post_meta($post_id, self::META_CONTAINS, $contains);
        } else {
            delete_post_meta($post_id, self::META_CONTAINS);
        }

        if ('' !== $not_contain) {
            update_post_meta($post_id, self::META_NOT_CONTAIN, $not_contain);
        } else {
            delete_post_meta($post_id, self::META_NOT_CONTAIN);
        }

        if ('' !== $may_contain) {
            update_post_meta($post_id, self::META_MAY_CONTAIN, $may_contain);
        } else {
            delete_post_meta($post_id, self::META_MAY_CONTAIN);
        }
    }

    /**
     * Output the Allergens panel markup.
     */
    public function render_product_data_panel()
    {
        global $post;

        $product_id = $post->ID;
        $contains = get_post_meta($product_id, self::META_CONTAINS, true);
        $not_contain = get_post_meta($product_id, self::META_NOT_CONTAIN, true);
        $may_contain = get_post_meta($product_id, self::META_MAY_CONTAIN, true);

        $contains = is_string($contains) ? $contains : '';
        $not_contain = is_string($not_contain) ? $not_contain : '';
        $may_contain = is_string($may_contain) ? $may_contain : '';
        ?>
		<div id="foodord_allergens_data" class="panel woocommerce_options_panel hidden">
			<div class="options_group">
				<p class="form-field foodord-allergens-intro">
					<span class="description">
						<?php esc_html_e( 'Enter product-specific allergen information. This overrides the global Allergy Info setting.', 'foodord' ); ?>
					</span>
				</p>
                <?php
                woocommerce_wp_textarea_input(
                    array(
                        'id' => self::META_CONTAINS,
                        'label' => __('Contains', 'foodord'),
                        'placeholder' => __('e.g., Gluten, Milk, Eggs, Nuts', 'foodord'),
                        'desc_tip' => true,
                        'description' => __('List allergens that this product contains.', 'foodord'),
                        'value' => $contains,
                    )
                );

                woocommerce_wp_textarea_input(
                    array(
                        'id' => self::META_NOT_CONTAIN,
                        'label' => __('Does Not Contain', 'foodord'),
                        'placeholder' => __('e.g., Gluten-free, Dairy-free', 'foodord'),
                        'desc_tip' => true,
                        'description' => __('List allergens that this product does not contain.', 'foodord'),
                        'value' => $not_contain,
                    )
                );

                woocommerce_wp_textarea_input(
                    array(
                        'id' => self::META_MAY_CONTAIN,
                        'label' => __('May Contain (Shared Equipment)', 'foodord'),
                        'placeholder' => __('e.g., Traces of peanuts, Tree nuts', 'foodord'),
                        'desc_tip' => true,
                        'description' => __('List potential cross-contamination allergens from shared equipment.', 'foodord'),
                        'value' => $may_contain,
                    )
                );
                ?>
            </div>
        </div>
        <?php
    }

    /**
     * Check if a product has any allergen data.
     *
     * @param int $product_id Product ID.
     * @return bool
     */
    public static function has_product_allergens($product_id)
    {
        $contains = get_post_meta($product_id, self::META_CONTAINS, true);
        $not_contain = get_post_meta($product_id, self::META_NOT_CONTAIN, true);
        $may_contain = get_post_meta($product_id, self::META_MAY_CONTAIN, true);

        $contains = is_string($contains) ? trim($contains) : '';
        $not_contain = is_string($not_contain) ? trim($not_contain) : '';
        $may_contain = is_string($may_contain) ? trim($may_contain) : '';

        return '' !== $contains || '' !== $not_contain || '' !== $may_contain;
    }

    /**
     * Get product allergens data.
     *
     * @param int $product_id Product ID.
     * @return array
     */
    public static function get_product_allergens($product_id)
    {
        $contains = get_post_meta($product_id, self::META_CONTAINS, true);
        $not_contain = get_post_meta($product_id, self::META_NOT_CONTAIN, true);
        $may_contain = get_post_meta($product_id, self::META_MAY_CONTAIN, true);

        return array(
            'contains' => is_string($contains) ? trim($contains) : '',
            'not_contain' => is_string($not_contain) ? trim($not_contain) : '',
            'may_contain' => is_string($may_contain) ? trim($may_contain) : '',
        );
    }

    /**
     * Get formatted HTML for product allergens.
     *
     * @param int $product_id Product ID.
     * @return string
     */
    public static function get_product_allergens_html($product_id)
    {
        $allergens = self::get_product_allergens($product_id);

        if ('' === $allergens['contains'] && '' === $allergens['not_contain'] && '' === $allergens['may_contain']) {
            return '';
        }

        $html = '';

        if ('' !== $allergens['contains']) {
            $html .= '<div class="foodord-allergens-item foodord-allergens-item--contains">';
            $html .= '<strong>' . esc_html__('Contains:', 'foodord') . '</strong> ';
            $html .= esc_html($allergens['contains']);
            $html .= '</div>';
        }

        if ('' !== $allergens['not_contain']) {
            $html .= '<div class="foodord-allergens-item foodord-allergens-item--not-contain">';
            $html .= '<strong>' . esc_html__('Does Not Contain:', 'foodord') . '</strong> ';
            $html .= esc_html($allergens['not_contain']);
            $html .= '</div>';
        }

        if ('' !== $allergens['may_contain']) {
            $html .= '<div class="foodord-allergens-item foodord-allergens-item--may-contain">';
            $html .= '<strong>' . esc_html__('May Contain (Shared Equipment):', 'foodord') . '</strong> ';
            $html .= esc_html($allergens['may_contain']);
            $html .= '</div>';
        }

        return $html;
    }
}
