<?php

namespace CodeConfig\EAW\Ajax;

use CodeConfig\EAW\Utils\Helpers;

defined('ABSPATH') || exit('No direct script access allowed');

class Product
{
    public static function get()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        if (isset($_POST['productId'])) {
            wp_send_json_error([
                'success' => false,
                'message' => __('Product id is required', 'essential-addons-for-woocommerce')
            ]);
        }

        $productId = sanitize_text_field(wp_unslash($_POST['productId']) ?? '');

        $productId = intval($productId) ?? null;

        wp_send_json_success([
            'success' => true,
            'data'    => Helpers::getProduct($productId),
            'message' => __('Settings fetched successfully', 'essential-addons-for-woocommerce')
        ]);
    }

    public static function set()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        if (isset($_POST['productId']) || isset($_POST['quantity'])) {
            wp_send_json_error([
                'success' => false,
                'message' => __('Product id is required', 'essential-addons-for-woocommerce')
            ]);
        }

        $productId = sanitize_text_field(wp_unslash($_POST['productId']) ?? '');
        $quantity  = sanitize_text_field(wp_unslash($_POST['quantity']) ?? '');

        if (empty($productId) || empty($quantity)) {
            wp_send_json_error([
                'message' => __('Product id is required', 'essential-addons-for-woocommerce'),
                'success' => false
            ]);
        }

        // check product purchase and stock status
        $product = wc_get_product($productId);

        if (!$product || !$product->is_in_stock() || !$product->is_purchasable()) {
            wp_send_json_error([
                'message' => __('Product is not purchasable or out of stock', 'essential-addons-for-woocommerce'),
                'success' => false,
                'status'  => __('Error', 'essential-addons-for-woocommerce')
            ]);
        }

        $setCartData = Helpers::setToCart($productId, $quantity);

        if (!$setCartData) {
            wp_send_json_error([
                'success' => false,
                'message' => __('Something went wrong', 'essential-addons-for-woocommerce'),
            ], 400);
        }
        wp_send_json_success([
            'success' => true,
            'data'    => Helpers::getProduct($productId),
            'cart'    => $setCartData,
            'message' => __('Added to cart successfully', 'essential-addons-for-woocommerce')
        ]);
    }

    public static function getProducts()
    {

        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $product_list = Helpers::getAllProducts();

        return wp_send_json_success([
            'success' => true,
            'data'    => $product_list
        ]);
    }

    public static function getProductsByTitle()
    {

        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $product_title = sanitize_text_field(wp_unslash($_POST['searchProducts'] ?? ''));

        $product_list = Helpers::getAllProductsByTitle($product_title);

        return wp_send_json_success([
            'success' => true,
            'data'    => $product_list
        ]);
    }

    public static function getCategoryByTitle()
    {
        // Verify nonce for security
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        // Get and sanitize category name from request
        $category_name = sanitize_text_field(wp_unslash($_POST['name'] ?? ''));

        // Ensure a name is provided
        if (empty($category_name)) {
            return wp_send_json_error(['message' => 'Category name is required.']);
        }

        // Query categories that match the given name (or part of it)
        $categories = get_terms([
            'taxonomy'   => 'product_cat', // Change to 'category' for post categories
            'hide_empty' => false,
            'name__like' => $category_name, // Supports partial matching
        ]);

        // Check if categories are found
        if (is_wp_error($categories) || empty($categories)) {
            return wp_send_json_error(['message' => 'No categories found.']);
        }

        // Format category list
        $category_list = array_map(function ($cat) {
            return [
                'value' => $cat->term_id,
                'label' => $cat->name,
            ];
        }, $categories);

        // Return JSON response
        return wp_send_json_success([
            'success' => true,
            'data'    => $category_list,
        ]);
    }
    public static function getCategoryById()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $category_ids = isset($_POST['ids']) ? array_map('intval', (array) $_POST['ids']) : [];

        if (empty($category_ids)) {
            return wp_send_json_error(['message' => 'Category IDs are required.']);
        }

        $categories = get_terms([
            'taxonomy'   => 'product_cat',
            'hide_empty' => false,
            'include'    => $category_ids,
        ]);

        if (is_wp_error($categories) || empty($categories)) {
            return wp_send_json_error(['message' => 'No categories found for the given IDs.']);
        }

        $category_list = array_map(function ($cat) {
            return [
                'value' => $cat->term_id,
                'label' => $cat->name,
            ];
        }, $categories);

        return wp_send_json_success([
            'success' => true,
            'data'    => $category_list,
        ]);
    }

    public static function getProductsById()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        // Ensure IDs are provided
        if (! isset($_POST['ids'])) {
            wp_send_json_error(['message' => 'No product IDs provided.']);
        }

        // Unslash then sanitize the IDs array
        $raw_ids     = sanitize_text_field(wp_unslash($_POST['ids']));
        $product_ids = array_map('absint', (array) $raw_ids);

        // Remove any zero values (invalid IDs) and duplicates
        $product_ids = array_values(array_filter(array_unique($product_ids)));

        if (empty($product_ids)) {
            wp_send_json_error(['message' => 'No valid product IDs provided.']);
        }

        $args = [
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'post__in'       => $product_ids,
            'orderby'        => 'title',
            'order'          => 'ASC',
            'posts_per_page' => -1,
            'fields'         => ['ID', 'post_title'],
        ];

        $query = new \WP_Query($args);

        $product_list = array_map(function ($post) {
            return [
                'ID'         => $post->ID,
                'post_title' => $post->post_title,
            ];
        }, $query->posts);

        wp_send_json_success([
            'success' => true,
            'data'    => $product_list,
        ]);


        wp_send_json_success([
            'success' => true,
            'data'    => is_array($product_list) ? $product_list : []
        ]);
    }


    public static function getCategories()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $categories = Helpers::getCategories();

        return wp_send_json_success([
            'success' => true,
            'data'    => $categories
        ]);
    }

    public static function getProductVariationById()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $product_id = intval(sanitize_text_field(wp_unslash($_POST['productId'] ?? '')));

        $variations = Helpers::getVariationByProductId($product_id);

        if (!empty($variations)) {

            return wp_send_json_success([
                'success'    => true,
                'variations' => $variations,
            ]);
        }
    }

    public static function getProductVariations()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $variations = Helpers::getProductVariations();

        return wp_send_json_success([
            'success' => true,
            'data'    => $variations,
        ]);
    }

    public static function getSelectedVariationImg()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $variation_id = intval(sanitize_text_field(wp_unslash($_POST['variationId'] ?? '')));

        $image_data = '';

        return wp_send_json_success([
            'success' => true,
            'data'    => $image_data,
        ]);
    }

    public static function getProductAttributes()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $attributes = Helpers::getProductAttributes();

        return wp_send_json_success([
            'success' => true,
            'data'    => $attributes,
        ]);
    }

    public static function addProductAttribute()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $attrName        = sanitize_text_field(wp_unslash($_POST['label'] ?? ''));
        $attrType        = sanitize_text_field(wp_unslash($_POST['type'] ?? ''));
        $showInProduct   = filter_var(wp_unslash($_POST['showInProduct'] ?? true), FILTER_VALIDATE_BOOLEAN);
        $showInVariation = filter_var(wp_unslash($_POST['showInVariation'] ?? true), FILTER_VALIDATE_BOOLEAN);

        // Unslash and sanitize array

        if (empty($attrName) || empty($attrTerms) || empty($attrType)) {
            wp_send_json_error([
                'message' => __('Attribute name, type, and terms are required.', 'essential-addons-for-woocommerce'),
                'success' => false,
            ]);
        }
    }

    public static function deleteProductAttribute()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $attrName = isset($_POST['attrName']) ? sanitize_text_field(wp_unslash($_POST['attrName'])) : '';

        if (empty($attrName)) {
            wp_send_json_error([
                'message' => __('Attribute id is required', 'essential-addons-for-woocommerce'),
                'success' => false
            ]);
        }

        $attributes = Helpers::deleteProductAttribute($attrName);

        if (!$attributes) {
            wp_send_json_error([
                'message' => __('Something went wrong', 'essential-addons-for-woocommerce'),
                'success' => false
            ]);
        }

        return wp_send_json_success([
            'success' => true,
            'data'    => $attributes,
        ]);
    }

    public static function getProductSkus()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $sku = Helpers::getProductSkus();

        return wp_send_json_success([
            'success' => true,
            'data'    => $sku,
        ]);
    }

    public static function getSearchProduct()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        if (! current_user_can('manage_options')) {
            wp_send_json_error([
                'message' => esc_html__('Unauthorized access.', 'essential-addons-for-woocommerce'),
                'status'  => 'error'
            ]);
        }

        $keyword = isset($_GET['keyword']) ? sanitize_text_field(wp_unslash($_GET['keyword'])) : '';

        if (empty($keyword)) {
            wp_send_json_error([
                'message' => esc_html__('Please enter a keyword.', 'essential-addons-for-woocommerce'),
                'status'  => 'error'
            ]);
        }

        $query = new \WP_Query([
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => 50,
            's'              => $keyword,
        ]);

        $results = [];

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();

                $product_id = get_the_ID();
                $product    = wc_get_product($product_id);

                if (! $product || ! $product->is_in_stock()) {
                    continue;
                }

                $product_title = get_the_title() . ' (#' . $product_id . ')';

                if ($product->is_type('variable') && $product->has_child()) {
                    $results[] = [
                        'id'   => $product_id,
                        'text' => $product_title . ' (#VARIABLE)',
                    ];

                    foreach ($product->get_children() as $child_id) {

                        /**
                         * @var WC_Product $child_product
                         */
                        $child_product = wc_get_product($child_id);

                        if (! $child_product) {
                            continue;
                        }

                        $variation_attributes = $child_product->get_variation_attributes();
                        $attr_label           = implode(', ', array_values($variation_attributes));

                        $results[] = [
                            'id'   => $child_id,
                            'text' => get_the_title($product_id) . ' - ' . $attr_label,
                        ];
                    }
                } else {
                    $results[] = [
                        'id'   => $product_id,
                        'text' => $product_title,
                    ];
                }
            }
            wp_reset_postdata();
        }

        wp_send_json_success($results);
    }

    public static function getSearchCats()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        if (! current_user_can('manage_options')) {
            wp_send_json_error([
                'message' => esc_html__('Unauthorized access.', 'essential-addons-for-woocommerce'),
                'status'  => 'error'
            ]);
        }

        $keyword = isset($_GET['keyword']) ? sanitize_text_field(wp_unslash($_GET['keyword'])) : '';

        if (empty($keyword)) {
            wp_send_json_error([
                'message' => esc_html__('Please enter a keyword.', 'essential-addons-for-woocommerce'),
                'status'  => 'error'
            ]);
        }

        $categories = get_terms([
            'taxonomy'   => 'product_cat',
            'orderby'    => 'name',
            'order'      => 'ASC',
            'search'     => $keyword,
            'hide_empty' => false,
            'number'     => 100
        ]);

        $items = array_map(fn ($category) => [
            'id'   => $category->term_id,
            'text' => $category->name
        ], $categories ?: []);

        wp_send_json_success($items);
    }

    public function getProductUrl()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $result     = [
            'status'  => '',
            'message' => '',
        ];

        $product_id = sanitize_text_field(wp_unslash($_POST['product_id'] ?? ''));
        if (empty($product_id)) {

            $args = [
                'post_type'      => 'product',
                'post_status'    => 'any',
                'posts_per_page' => 1,
            ];

            $the_query = new \WP_Query($args);
            if ($the_query->have_posts()) {
                while ($the_query->have_posts()) {
                    $the_query->the_post();
                    $product_id = get_the_ID();
                    $product    = wc_get_product($product_id);
                    if ($product) {
                        $url = $product->get_permalink();
                        break;
                    }
                }
            }
            wp_reset_postdata();
        } elseif ($product = wc_get_product($product_id)) {
            $url = $product->get_permalink();
        }

        if (! empty($url)) {
            $result['status']  = 'success';
            $result['message'] = $url;
        }
        wp_send_json($result);
    }

    // Get viewed products
    public static function getViewedProducts()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $currentProductId =  sanitize_text_field(wp_unslash($_POST['currentProductId'] ?? ''));

        $settings = [
            'delete'    => Helpers::getSetting('vpEnableDeleteItem')
        ];

        $viewed_products = Helpers::getViewedProducts($currentProductId);

        if (empty($viewed_products)) {
            wp_send_json_error([
                'message' => __('No viewed products found.', 'essential-addons-for-woocommerce'),
            ]);
        }

        ob_start();

        foreach ($viewed_products as $product_id) {
            $post_object = get_post($product_id);

            if (!$post_object) {
                continue;
            }

            global $post;
            $post = $post_object;
            setup_postdata($post);

            ccpeaw_get_template('products/recently-viewed', [
                'product_id' => $product_id,
                'product'    => wc_get_product($product_id),
                'settings'   => $settings
            ], 'product');
        }

        wp_reset_postdata();

        $output = ob_get_clean();
        $output = apply_filters('eaw_viewed_products_output', $output, $viewed_products);

        wp_send_json_success([
            'html'    => $output,
            'success' => true,
            'count'   => count($viewed_products),
        ]);
    }

    // Delete viewed products
    public static function deleteViewedProducts()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $currentProductId =  sanitize_text_field(wp_unslash($_POST['productId'] ?? ''));

        Helpers::deleteViewedProducts($currentProductId);

        wp_send_json_success([
            'message' => __('Viewed products deleted successfully.', 'essential-addons-for-woocommerce'),
        ]);
    }

    public static function getProductVideo()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $product_id = sanitize_text_field(wp_unslash($_POST['productId'] ?? ''));

        $product = wc_get_product($product_id);

        if (!$product) {
            wp_send_json_error([
                'message' => __('Product not found.', 'essential-addons-for-woocommerce'),
            ]);
        }

        $videoData      = get_post_meta($product_id, '_product_video_data', true);

        if ($videoData['type'] == 'custom' && $videoData['videoid']) {
            $videoData['videoid'] = wp_get_attachment_url($videoData['videoid']);
        }

        wp_send_json_success([
            'success'        => true,
            'data'           => $videoData,
        ]);
    }
}
