<?php

namespace Fab\Controller;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Fab\Interfaces\JIT_Interface;
use Fab\Metabox\FABMetaboxSetting;

/**
 * Featured Product Type.
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class WC_Featured_Product_Type extends WC_Group implements JIT_Interface {

    /**
     * Constructor.
     */
    public function __construct() {
        parent::__construct();
        $this->type       = 'featured_product';
        $this->dependency = FAB_WOOCOMMERCE_PLUGIN_FILE;
    }

    /**
     * Get labels type.
     *
     * @return array
     */
    public function get_labels_type() {
        return array(
            'name' => __( 'Featured Product', 'floating-awesome-button' ),
        );
    }

    /**
     * AJAX handler to search for WooCommerce products based on a search term.
     *
     * @return void Outputs a JSON response containing an array of products.
     */
    public function ajax_search_products() {
        $search_term = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        $search_term = sanitize_text_field( $search_term );

        // Query WooCommerce products.
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => 10, // Limit the number of results.
            's'              => $search_term, // Search term.
            'post_status'    => 'publish', // Only published products.
        );

        $query = new \WP_Query( $args );

        // Prepare the results.
        $products = array();

        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) {
                $query->the_post();
                $product_title = get_the_title();
                $product_title = html_entity_decode( $product_title, ENT_QUOTES, 'UTF-8' );

                $products[] = array(
                    'id'        => get_the_ID(),
                    'text'      => $product_title,
                    'post_type' => 'product',
                );
            }
        }

        wp_reset_postdata();

        // Return the products as a JSON response.
        wp_send_json( $products );
    }

    /**
     * Add FAB setting inputs for WooCommerce features.
     *
     * @param array $input Existing input settings.
     * @return array Modified input settings with new WooCommerce settings.
     */
    public function add_fab_setting_input( $input ) {
        // Define new WooCommerce input settings.
        $woocommerce_settings = array(
            'fab_setting_woocommerce_featured_product' => array( 'default' => '' ),
        );

        // Merge new settings into the existing inputs.
        return array_merge( $input, $woocommerce_settings );
    }

    /**
     * Add FAB setting post meta for WooCommerce features.
     *
     * @param array $post_metas Existing post meta settings.
     * @return array Modified post meta settings with new WooCommerce meta.
     */
    public function add_fab_setting_post_metas( $post_metas ) {
        // Define new WooCommerce post meta settings.
        $woocommerce_post_metas = array(
            'woocommerce_featured_product' => array(
                'meta_key' => 'fab_setting_woocommerce_featured_product',
            ),
        );

        // Merge new post meta settings into the existing post metas.
        return array_merge( $post_metas, $woocommerce_post_metas );
    }

    /**
     * Filter the FAB template to postmeta.
     *
     * @param array  $postmeta The postmeta.
     * @param string $type The type of FAB.
     * @param object $data The data.
     */
    public function filter_template_postmeta( $postmeta, $type, $data ) {
        // Check if woocommerce is active and type is featured product.
        if ( ! class_exists( 'WooCommerce' ) || 'featured_product' !== $type ) {
            return $postmeta;
        }

        // Check if product id is set.
        if ( isset( $data->product_id ) ) {
            $postmeta['fab_setting_woocommerce_featured_product'] = $data->product_id;
        } else {
            // Get product with most sales.
            $args     = array(
                'post_type'      => 'product',
                'meta_key'       => 'total_sales',
                'orderby'        => 'meta_value_num',
                'order'          => 'DESC',
                'posts_per_page' => 1,
            );
            $products = get_posts( $args );

            // If there no sales, get recent product.
            if ( ! $products ) {
                $args     = array(
                    'post_type'      => 'product',
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                    'posts_per_page' => 1,
                );
                $products = get_posts( $args );
            }

            // Get product ID.
            if ( ! empty( $products ) ) {
                $postmeta['fab_setting_woocommerce_featured_product'] = $products[0]->ID;
            }
        }

        return $postmeta;
    }

    /**
     * Add convert product to FAB action to FAB post type row actions.
     *
     * @param array   $actions Array of row action links.
     * @param WP_Post $post   The post object.
     * @return array
     */
    public function add_fab_convert_product_action( $actions, $post ) {
        if ( 'product' === $post->post_type ) {
            $actions['fab_convert_product'] = sprintf(
                '<a href="%s">%s</a>',
                wp_nonce_url(
                    admin_url( 'admin.php?action=fab_convert_product&product_id=' . $post->ID ),
                    'fab_convert_product_' . $post->ID
                ),
                __( 'Turn into FAB', 'floating-awesome-button' )
            );
        }
        return $actions;
    }

    /**
     * Handle the conversion of product to FAB
     *
     * @return void
     */
    public function convert_product_to_fab() {
        // Check if post ID is provided.
        $product_id = isset( $_GET['product_id'] ) ? intval( $_GET['product_id'] ) : 0;

        // Verify nonce.
        if ( ! wp_verify_nonce( $_GET['_wpnonce'], 'fab_convert_product_' . $product_id ) ) { // phpcs:ignore
            wp_die( esc_html__( 'Security check failed', 'floating-awesome-button' ) );
        }

        // Add new fab.
        $result = \Fab\Helper\FAB_Template::getInstance()->add_new_fab(
            (object) array(
                'id'         => 'woocommerce-featured-product',
                'product_id' => $product_id,
            )
        );

        // Check if there's an error.
        if ( is_wp_error( $result ) ) {
            wp_die( esc_html( $result->get_error_message() ) );
        }

        // Redirect to FAB edit page.
        wp_safe_redirect( admin_url( 'post.php?post=' . $result . '&action=edit' ) );
        exit;
    }

    /**
     * Add convert page-title-action on edit product page.
     *
     * @return void
     */
    public function add_wc_product_integration() {
        $screen = get_current_screen();

        // Early return if not on product edit page.
        if ( ! $screen || ( 'product' !== $screen->post_type ) ) {
            return;
        }

        // Enqueue script.
        \FAB()->Helper->wp_enqueue_script_typescript( 'fab-integration-wc-product', 'assets/ts/integration/wc-product.ts', array(), FAB_VERSION, true );
        wp_localize_script(
            'fab-integration-wc-product',
            'FAB_PRODUCT',
            array(
                'product' => array(
                    'id'          => get_the_ID(),
                    'convert_url' => wp_nonce_url(
                        admin_url( 'admin.php?action=fab_convert_product&product_id=' . get_the_ID() ),
                        'fab_convert_product_' . get_the_ID()
                    ),
                ),
                'label'   => array(
                    'turn_into_fab' => __( 'Turn into FAB', 'floating-awesome-button' ),
                ),
            )
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Fulfill implemented interface contracts
    |--------------------------------------------------------------------------
     */

    /**
     * JIT Method.
     *
     * @return void
     */
    public static function jit() {
        /**
         * |--------------------------------------------------------------------------
         * | WOOCOMMERCE HOOKS
         * | - Prevent error if woocommerce plugin is not active.
         * |--------------------------------------------------------------------------
         */
        if ( ! FAB_WOOCOMMERCE_PLUGIN_ACTIVE ) {
            return;
        }

        // Add fab setting types.
        add_filter( 'fab_setting_types', array( __CLASS__, 'jit_add_fab_setting_types' ), 10, 1 );

        // @backend - Ajax search products
        add_action( 'wp_ajax_fab_search_products', array( __CLASS__, 'jit_ajax_search_products' ) );

        // @backend - Add fab setting input
        add_filter( 'fab_setting_input', array( __CLASS__, 'jit_add_fab_setting_input' ), 10, 1 );

        // @backend - Add fab setting post metas
        add_filter( 'fab_setting_post_metas', array( __CLASS__, 'jit_add_fab_setting_post_metas' ), 10, 1 );

        /**
         * |--------------------------------------------------------------------------
         * | INTEGRATION
         * | - Early return if WooCommerce integration is not enabled.
         * |--------------------------------------------------------------------------
         */
        if ( \Fab\Plugin\Helper::getInstance()->check_plugin_integration( FAB_WOOCOMMERCE_PLUGIN_FILE ) !== 'enabled' ) {
            return;
        }

        // Add convert product to product row action.
        add_filter( 'post_row_actions', array( __CLASS__, 'jit_add_fab_convert_product_action' ), 10, 2 );
        add_action( 'admin_action_fab_convert_product', array( __CLASS__, 'jit_convert_product_to_fab' ) );

        // Add convert page-title-action on edit product page.
        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'jit_add_wc_product_integration' ) );
    }
}
