<?php

namespace DEVELUXSCT\Options;


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

class Ajax_Handler
{

    use Global_Timer_Styles_Fields;

    public function __construct()
    {
        add_action('wp_ajax_develuxsct_create_timer', [$this, 'create_timer_handler']);
        add_action('wp_ajax_develuxsct_delete_timer', [$this, 'delete_timer_handler']);
        add_action('wp_ajax_develux_timer_builder_form', [$this, 'timer_builder_form_handler']);
        add_action('wp_ajax_develux_search_products', [$this, 'develux_search_products']);
        add_action('wp_ajax_develux_timer_deactivate_confirm', [$this, 'develux_timer_deactivate_confirm']);
        add_action('wp_ajax_develuxsct_dismiss_help_info_notice', [$this, 'develuxsct_dismiss_help_info_notice']);

    }
    public function delete_develux_meta(): void
    {
        $posts = get_posts([
            'post_type'      => 'any',
            'posts_per_page' => -1,
            'fields'         => 'ids',
        ]);

        foreach ($posts as $post_id) {
            $meta_keys = array_keys(get_post_meta($post_id));

            foreach ($meta_keys as $meta_key) {
                if (strpos($meta_key, 'develux_') === 0) {
                    delete_post_meta($post_id, $meta_key);
                }
            }
        }
    }

    public function delete_develux_options(): void
    {
        $all_options = wp_load_alloptions();

        foreach ($all_options as $option_name => $value) {
            if (strpos($option_name, 'develux_') === 0) {
                delete_option($option_name);
            }
        }
    }


    public function timer_builder_form_handler(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'develux_timer_builder_form')) {
            wp_send_json_error('Invalid nonce');
        }

        $title = isset($_POST['develux_timer_new_title']) ? sanitize_text_field(wp_unslash($_POST['develux_timer_new_title'])) : '';
        $id = isset($_POST['develux_current_timer_id']) ? sanitize_text_field(wp_unslash($_POST['develux_current_timer_id'])) : '';
        $post = get_post($id);
        if (!$post || $post->post_type !== 'develuxsct_timer') {
            wp_send_json_error('Timer not found or invalid post type.');
        }
        $update_result = '';
        if ($title) {
            $update_result = wp_update_post([
                'ID' => $id,
                'post_title' => $title,
            ], true);
        }


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

        if (!$post_id) {
            wp_send_json_error('Invalid timer ID specified.');
        }


        $allowed_meta_keys = $this->get_global_timer_styles_fields_names();

        foreach ($allowed_meta_keys as $meta_key) {
            if (isset($_POST[$meta_key])) {
                update_post_meta($post_id, $meta_key, sanitize_text_field(wp_unslash($_POST[$meta_key])));
            }
        }

        wp_send_json_success([
            'id' => $post_id,
            'update_result' => $update_result
        ]);
    }

    public function develux_timer_deactivate_confirm(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'develux_timer_deactivate_confirm')) {
            wp_send_json_error('Invalid nonce');
        }
        $args = [
            'post_type' => 'develuxsct_timer',
            'posts_per_page' => -1,
            'post_status' => 'any',
        ];
        $posts = get_posts($args);

        foreach ($posts as $post) {
            wp_delete_post($post->ID, true);
        }

        $this->develux_delete_image_attachment_by_option('develux_coming_soon_space_icon_id');
        $this->develux_delete_image_attachment_by_option('develux_new_proposition_icon_id');
        $this->develux_delete_image_attachment_by_option('develux_big_sale_icon_id');
        $this->develux_delete_image_attachment_by_option('develux_3_for_2_icon_id');
        $this->develux_delete_image_attachment_by_option('develux_hurry_up_icon_id');
        $this->develux_delete_image_attachment_by_option('develux_new_year_sale_icon_id');
        $this->develux_delete_image_attachment_by_option('develux_sale_time_icon_id');


        $this->delete_develux_meta();
        $this->delete_develux_options();

        foreach ($posts as $post) {
            wp_delete_post($post->ID, true);
        }

        wp_send_json_success([
            'message' => 'Custom data deleted successfully.',
            'deleted_timer' => count($posts),
        ]);

    }

    public function develux_delete_image_attachment_by_option($option_key): void
    {
        $attachment_id = get_option($option_key);

        if ($attachment_id) {
            wp_delete_attachment((int) $attachment_id, true);
            delete_option($option_key);
        }
    }

    public function create_timer_handler(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'create_timer')) {
            wp_send_json_error('Invalid nonce');
        }

        if (!isset($_POST['title'])) {
            wp_send_json_error('No label title specified.');
        }

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

        $new_post_id = wp_insert_post([
            'post_type' => $post_type,
            'post_title' => $title,
            'post_status' => 'publish'
        ]);
        $develux_timer_fields = $this->get_global_timer_default_data_set();
        $fields = [];
        if ($post_type === 'develuxsct_timer') {
            $fields = $develux_timer_fields;
        }

        if (!empty($fields) && $new_post_id && !is_wp_error($new_post_id)) {
            foreach ($fields as $meta_key => $meta_value) {
                update_post_meta($new_post_id, $meta_key, $meta_value);
            }
        }


        if (!is_wp_error($new_post_id)) {
            wp_send_json_success(['id' => $new_post_id]);
        } else {
            wp_send_json_error('Failed to create a new Label.');
        }


    }

    public function delete_timer_handler(): void
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'delete_timer')) {
            wp_send_json_error('Invalid nonce');
        }

        if (!isset($_POST['id'])) {
            wp_send_json_error('No timer id specified.');
        }

        $id = isset($_POST['id']) ? sanitize_text_field(wp_unslash($_POST['id'])) : '';
        if (get_post($id)) {
            $result = wp_delete_post($id, true);

            if ($result) {
                wp_send_json_success("Timer with ID $id has been deleted successfully.");
            } else {
                wp_send_json_error('Failed to delete timer.');
            }
        } else {
            wp_send_json_error('Timer not found.');
        }
    }

    public function develux_search_products(): void
    {
        if (empty($_POST['query'])) {
            wp_send_json_error(['message' => 'No query provided']);
        }
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'develux_search_products')) {
            wp_send_json_error(['message' => 'Invalid nonce']);
        }

        $query = sanitize_text_field(wp_unslash($_POST['query']));
        $args = [
            'post_type' => 'product',
            'posts_per_page' => 25,
            's' => $query,
        ];
        $results = get_posts($args);
        $formatted_results = array_map(static function ($product) {
            $product_id = $product->ID;
            $thumbnail = get_the_post_thumbnail_url($product_id, 'thumbnail');
            $product_obj = wc_get_product($product_id);
            $price = $product_obj->get_regular_price(); // Regular price
            $sale_price = $product_obj->get_sale_price(); // Sale price (if set)
            $currency_symbol = get_woocommerce_currency_symbol();
            return [
                'id' => $product_id,
                'name' => $product->post_title,
                'thumbnail' => $thumbnail ?: '',
                'price' => $price ?: '',
                'sale_price' => $sale_price ?: '',
                'currency_symbol' => $currency_symbol ?: '$',
            ];
        }, $results);


        wp_send_json_success($formatted_results);

    }

    public function develuxsct_dismiss_help_info_notice(): void
    {
        check_ajax_referer('develuxsct_notice_help_info_nonce', 'security');

        update_option('develuxsct_help_info_notice_timestap', time());
    }
}