<?php
namespace MosPress\StoreAddonsForWoocommerce\API;
if ( ! defined( 'ABSPATH' ) ) exit;
use MosPress\StoreAddonsForWoocommerce\API\LogsController;
use MosPress\StoreAddonsForWoocommerce\Helpers\Utils;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
use WP_Query;

use RecursiveIteratorIterator;
use RecursiveArrayIterator;

use MosPress\StoreAddonsForWoocommerce\Helpers\CryptoHelper;
/**
 * Rest API Router
 *
 * Registers all REST API endpoints and routes them to appropriate controllers
 */
class Rest_API
{
    
    private const NAMESPACE = 'store-addons-for-woocommerce/v1';
    private static $instance = null;
    public static function get_instance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function __construct()
    {        
        add_action('rest_api_init', [$this, 'rest_api_init']);
    }
    public function rest_api_init()
    {
        // self::register_settings_theme_endpoints();
        $this->register_settings_theme_endpoints();
        $this->register_feedback_endpoints();
        $this->register_options_endpoints();
        $this->register_logs_endpoints();
        $this->register_necessary_endpoints();
    }

    /**
     * Register settings theme endpoints
     */
    private function register_settings_theme_endpoints()
    {  
		register_rest_route(self::NAMESPACE, '/set-settings-theme',
			array(
				'methods'  => 'GET',
				'callback' => [$this, 'rest_set_settings_theme'],
				'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
                'args' => [
                    'id' => [
                        'required' => true,
                        'type'     => 'string',
                        'items'    => [ 'type' => 'integer' ],
                    ],
                    
                    'settings_theme' => [
                        'required' => true,
                        'type'     => 'string',
                        'enum'     => [ 'light', 'dark' ],
                    ],
                ],
			)
		); 
        register_rest_route(self::NAMESPACE, '/get-settings-theme',
			array(
				'methods'  => 'GET',
				'callback' => [$this, 'rest_get_settings_theme'],
				'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
			)
		);       
    }

    /**
     * Register feedback endpoints
     */
    private function register_feedback_endpoints(){
        register_rest_route(self::NAMESPACE, '/feedback',
            array(
                'methods' => 'POST',
                'callback' => [$this, 'rest_feedback'],
				// 'permission_callback' => '__return_true'
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );
    }

    /**
     * Register options endpoints
     */
    private function register_options_endpoints() {        
		register_rest_route(self::NAMESPACE, '/options',
			array(
				'methods'  => 'GET',
				'callback' => [$this, 'get_settings'],
				// 'permission_callback' => '__return_true', // Allow public access
				'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
			)
		);
		register_rest_route(self::NAMESPACE, '/options',
			array(
				'methods'             => 'POST',
				'callback'            => [$this, 'update_settings'],
				// 'permission_callback' => '__return_true'
				'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
			)
		);
		register_rest_route(self::NAMESPACE, '/options/reset-settings',
            array(
                'methods' => 'POST',
                'callback' => [$this, 'reset_settings'],
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );
		register_rest_route(self::NAMESPACE, '/options/reset-settings-all',
            array(
                'methods' => 'POST',
                'callback' => [$this, 'reset_settings_all'],
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );        
		register_rest_route(self::NAMESPACE, '/options/import-settings', 
            [
                'methods' => 'POST',
                'callback' => function ($request) {
                    $data = $request->get_json_params();
                    update_option('store_addons_for_woocommerce_options', $data);
                    return rest_ensure_response(['success' => true]);
                },
                // 'permission_callback' => '__return_true',
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            ]
        );
		register_rest_route(self::NAMESPACE, '/options-details',
			array(
				'methods'  => 'GET',
				'callback' => [$this, 'get_settings_details'],
				// 'permission_callback' => '__return_true', // Allow public access
				'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
                'args' => [
                    'per_page' => ['sanitize_callback' => 'absint', 'default' => 5],
                    'search' => ['sanitize_callback' => 'sanitize_text_field'],
                ],
			)
		);
    }

    /**
     * Register logs endpoints
     */
    private function register_logs_endpoints() {        
        // Get logs with filters
        register_rest_route( self::NAMESPACE, '/logs',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( LogsController::class, 'get_logs' ),
                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
                'args' => [
                    'page' => ['sanitize_callback' => 'absint', 'default' => 1],
                    'per_page' => ['sanitize_callback' => 'absint', 'default' => 5],
                    'search' => ['sanitize_callback' => 'sanitize_text_field'],
                    'filter' => ['sanitize_callback' => 'sanitize_text_field'],
                    'sort_field' => ['sanitize_callback' => 'sanitize_text_field'],
                    'sort_order' => ['sanitize_callback' => 'sanitize_text_field'],
                    'date_from' => ['sanitize_callback' => 'sanitize_text_field'],
                    'date_to' => ['sanitize_callback' => 'sanitize_text_field'],
                ],
            )
        );

        // Delete log by ID
        register_rest_route( self::NAMESPACE, '/logs/(?P<id>\d+)',
            array(
                'methods'             => WP_REST_Server::DELETABLE,
                'callback'            => array( LogsController::class, 'delete_log' ),                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
                'args'                => array(
                    'id' => array(
                        'required'          => true,
                        'sanitize_callback' => 'absint',
                    ),
                ),
            )
        );

        // Bulk Delete Logs
        register_rest_route( self::NAMESPACE, '/logs/bulk-delete',
            array(
                'methods'             => WP_REST_Server::DELETABLE,
                'callback'            => array( LogsController::class, 'bulk_delete_logs' ),
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
                'args'                => array(
                    'ids' => array(
                        'required'          => true,
                        'type'     => 'array',
                        'items'    => array( 'type' => 'integer' ),
                    ),
                ),
            )
        );

        // Delete all logs
        register_rest_route( self::NAMESPACE, '/logs/',
            array(
                'methods'             => WP_REST_Server::DELETABLE,
                'callback'            => array( LogsController::class, 'delete_all_logs' ),                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

        // Logs Over Time Chart
        register_rest_route( self::NAMESPACE,'/logs/stats/over-time',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( LogsController::class, 'get_logs_over_time' ),                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

        // Logs by Category Chart
        register_rest_route( self::NAMESPACE,'/logs/stats/by-category',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( LogsController::class, 'get_logs_by_category' ),                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

        // Logs by User (Top Users) Chart
        register_rest_route( self::NAMESPACE,'/logs/stats/top-users',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( LogsController::class, 'get_logs_top_users' ),                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

        // Logs by IP Address (Top IPs) Chart
        register_rest_route( self::NAMESPACE,'/logs/stats/top-ips',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( LogsController::class, 'get_logs_top_ips' ),                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

        // Hourly Activity Chart
        register_rest_route( self::NAMESPACE,'/logs/stats/hourly-activity',
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( LogsController::class, 'get_logs_hourly_activity' ),                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );
    }
    
    /**
     * Register logs endpoints
     */
    private function register_necessary_endpoints() {        
        // Get sale badges
        register_rest_route( self::NAMESPACE, '/sale-badges',
            array(
                'methods'             => WP_REST_Server::READABLE,                
				'callback' => [$this, 'get_sale_badges'],                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );       
        // Get sold badges
        register_rest_route( self::NAMESPACE, '/sold-badges',
            array(
                'methods'             => WP_REST_Server::READABLE,                
				'callback' => [$this, 'get_sold_badges'],                
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

		register_rest_route( self::NAMESPACE, '/products', 
			array(	
				'methods'             => WP_REST_Server::READABLE, 
				'callback'            => [$this, 'get_products'],  
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
				'args'                => [
					'search' => [
						'required'          => false,
						'sanitize_callback' => 'sanitize_text_field',
						'default'           => '',
					],
					'limit' => [
						'required'          => false,
						'sanitize_callback' => 'sanitize_text_field',
						'default'           => -1,
					],
				],
			)
		);
    }


    // callback for settings theme endpoints
    public function rest_set_settings_theme(WP_REST_Request $request)
    {
        $user_id = sanitize_text_field(wp_unslash($request->get_param('id')));
        // $user_id = get_current_user_id();
        $settings_theme = sanitize_text_field(wp_unslash($request->get_param('settings_theme')));
        // get_user_meta($user_id, 'store_addons_for_woocommerce_settings_theme', $settings_theme);
        update_user_meta( $user_id, 'store_addons_for_woocommerce_settings_theme', $settings_theme );
                
        $response = [
            'success' => true,
            'msg' => esc_html__('Theme set successfully.', 'store-addons-for-woocommerce'),
        ];

        return new WP_REST_Response($response, 200);
    }
    public function rest_get_settings_theme(WP_REST_Request $request)
    {
        $user_id = sanitize_text_field(wp_unslash($request->get_param('id')));
        $settings_theme = get_user_meta($user_id, 'store_addons_for_woocommerce_settings_theme', true);
        // return $settings_theme??'light';
        return $settings_theme?$settings_theme:'light';
    }

    // callback for feedback endpoints	
    public function rest_feedback($request)
    {
        $name = sanitize_text_field(wp_unslash($request->get_param('name')));
        $email = sanitize_email(wp_unslash($request->get_param('email')));
        $phone = sanitize_text_field(wp_unslash($request->get_param('phone')));
        $subject = sanitize_text_field(wp_unslash($request->get_param('subject')));
        $message = sanitize_textarea_field(wp_unslash($request->get_param('message')));

        if (empty($email)) {
            return new WP_Error('empty_email', __('Email cannot be empty.', 'store-addons-for-woocommerce'), array('status' => 400));
        }

        if (empty($message)) {
            return new WP_Error('empty_message', __('Message cannot be empty.', 'store-addons-for-woocommerce'), array('status' => 400));
        }

        $email = 'mostak.shahid@gmail.com';
        $output = '<strong>Name:</strong> ' . $name;
        $output .= '<br/><strong>Email:</strong> ' . $email;
        $output .= '<br/><strong>Phone:</strong> ' . $phone;
        $output .= '<br/><strong>Subject:</strong> ' . $subject;
        $output .= '<br/><strong>Message:</strong> ' . $message;
        $headers = array(
            'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>',
            'Content-Type: text/html; charset=UTF-8'
        );

        wp_mail($email, 'Feedback from Store Addons for WooCommerce', $output, $headers);
        $response = [
            'success' => true,
            'msg' => esc_html__('Email Send successfully.', 'store-addons-for-woocommerce'),
            'subject' => $subject,
            'message' => $message
        ];
        return new WP_REST_Response($response, 200);
    }

    // callback for options enpoints    
	public function get_settings(WP_REST_Request $request)
	{
		if (!current_user_can('manage_options')) {
			return new WP_Error(
				'rest_update_error',
				'Sorry, you are not allowed to update the DAEXT UI Test options.',
				array('status' => 403)
			);
		}
		$store_addons_for_woocommerce_options = Utils::store_addons_for_woocommerce_get_option();
		return new WP_REST_Response($store_addons_for_woocommerce_options, 200);
	}
    public function get_settings_details(WP_REST_Request $request)
    {
        $store_addons_for_woocommerce_options_details = Utils::store_addons_for_woocommerce_get_option_details();
        // $output = $this->flatten_options_details($store_addons_for_woocommerce_options_details);

        $search   = $request->get_param('search');
        $per_page = $request->get_param('per_page');

        if ( ! empty( $search ) ) {
            // 1. Flatten the option details
            $flat_details = $this->flatten_options_details($store_addons_for_woocommerce_options_details);

            // 2. Filter items case-insensitively by specified keys
            $filtered_details = [];
            $search_keys = [
                'title', 
                'intro', 
                'hints', 
                'before', 
                'after', 
                'url'
            ];

            foreach ($flat_details as $item) {
                $matched = false;
                foreach ($search_keys as $key) {
                    if (isset($item[$key]) && is_string($item[$key]) && stripos($item[$key], $search) !== false) {
                        $matched = true;
                        break;
                    }
                }
                if ($matched) {
                    $filtered_details[] = $item;
                }
            }

            // 3. Paginate/Slice the results
            $limit = ! empty($per_page) ? intval($per_page) : 5;
            $store_addons_for_woocommerce_options_details = array_slice($filtered_details, 0, $limit);
        }

        return new WP_REST_Response($store_addons_for_woocommerce_options_details, 200);
    }
	public function update_settings(WP_REST_Request $request) //WP_REST_Request $request
	{
		if (!current_user_can('manage_options')) {
			return new WP_Error(
				'rest_update_error',
				'Sorry, you are not allowed to update options.'.get_current_user_id(),
				array('status' => 403)
			);
		}
		$store_addons_for_woocommerce_options_old = Utils::store_addons_for_woocommerce_get_option();

		$store_addons_for_woocommerce_options = map_deep(wp_unslash($request->get_param('store_addons_for_woocommerce_options')), 'wp_kses_post');

		$store_addons_for_woocommerce_options ? update_option('store_addons_for_woocommerce_options', $store_addons_for_woocommerce_options) : '';

		LogsController::log_settings_change($store_addons_for_woocommerce_options_old, $store_addons_for_woocommerce_options);

		$response = [
			'success' => true,
			'msg'	=> esc_html__('Data successfully added.', 'store-addons-for-woocommerce')
		];
		return new WP_REST_Response($response, 200);
	}
    private function reset_option_by_path(&$options, $defaults, $path)
	{
		$keys = explode('.', $path);
		$target = &$options;
		$default = $defaults;

		foreach ($keys as $key) {
			if (!isset($target[$key]) || !isset($default[$key])) {
				return false; // path not found
			}
			$target = &$target[$key];
			$default = $default[$key];
		}

		// Set the value at the final nested level
		$target = $default;
		return true;
	}
    public function reset_settings(WP_REST_Request $request)
	{
        if (!current_user_can('manage_options')) {
            return new WP_Error(
                'rest_update_error',
                'Sorry, you are not allowed to reset the settings.',
                array('status' => 403)
            );
        }
        $name = sanitize_text_field(wp_unslash($request->get_param('name')));
        $store_addons_for_woocommerce_options_old = Utils::store_addons_for_woocommerce_get_option();
        $store_addons_for_woocommerce_options = Utils::store_addons_for_woocommerce_get_option();
        $store_addons_for_woocommerce_default_options = Utils::store_addons_for_woocommerce_get_default_options();

        $success = $this->reset_option_by_path($store_addons_for_woocommerce_options, $store_addons_for_woocommerce_default_options, $name);
        
        if ($success) {
            update_option('store_addons_for_woocommerce_options', $store_addons_for_woocommerce_options);
            LogsController::log_settings_change($store_addons_for_woocommerce_options_old, $store_addons_for_woocommerce_default_options, 'reset');
            wp_send_json_success(['message' => __('Settings reset successfully.', 'store-addons-for-woocommerce')]);
        } else {
            wp_send_json_error(['error_message' => __('Invalid settings path.', 'store-addons-for-woocommerce')]);
        }

		$response = [
			'success' => true,
			'msg'	=> esc_html__('Data successfully added.', 'store-addons-for-woocommerce')
		];

		// return $response;
		return new WP_REST_Response($response, 200);
	}
    public function reset_settings_all(WP_REST_Request $request)
	{
        if (!current_user_can('manage_options')) {
            return new WP_Error(
                'rest_update_error',
                'Sorry, you are not allowed to reset the settings.',
                array('status' => 403)
            );
        }
        $store_addons_for_woocommerce_options_old = Utils::store_addons_for_woocommerce_get_option();
        $store_addons_for_woocommerce_default_options = Utils::store_addons_for_woocommerce_get_default_options();

        update_option('store_addons_for_woocommerce_options', $store_addons_for_woocommerce_default_options);
        LogsController::log_settings_change($store_addons_for_woocommerce_options_old, $store_addons_for_woocommerce_default_options, 'reset-all');
        wp_send_json_success(['message' => __('Settings reset successfully.', 'store-addons-for-woocommerce')]);

		$response = [
			'success' => true,
			'msg'	=> esc_html__('Data successfully added.', 'store-addons-for-woocommerce')
		];

		// return $response;
		return new WP_REST_Response($response, 200);
	}

    // callback for necessary endpoints
    public function get_sale_badges(WP_REST_Request $request)
    {
        $store_addons_for_woocommerce_default_sale_badges = Utils::store_addons_for_woocommerce_get_default_sale_badges();
        return new WP_REST_Response($store_addons_for_woocommerce_default_sale_badges, 200);
    }
    public function get_sold_badges(WP_REST_Request $request)
    {
        $store_addons_for_woocommerce_default_sold_badges = Utils::store_addons_for_woocommerce_get_default_sold_badges();
        return new WP_REST_Response($store_addons_for_woocommerce_default_sold_badges, 200);
    }

	public function get_products(WP_REST_Request $request) {
		$data = $request->get_params();
		$search_query = $data['search'];
		$limit_query = $data['limit'];

		// Define query arguments
		$args = [
			'post_type'      => 'product', // Uses WooCommerce 'product' post type
			'post_status'    => 'publish',
			'posts_per_page' => $limit_query,         // Limit results for better performance
			's'              => $search_query, // The search keyword
		];

		// Execute the query
		$query = new WP_Query($args);
		$products = [];

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

				// Build a clean, lightweight payload for your React frontend
				$products[] = [
					'id'    => get_the_ID(),
					'name'  => get_the_title(),
					'price' => function_exists('wc_get_product') ? wc_get_product(get_the_ID())->get_price() : '',
					'image' => get_the_post_thumbnail_url(get_the_ID(), 'thumbnail') ?: '',
				];
			}
			wp_reset_postdata();
		}

		// Return the clean array. WordPress automatically encodes this to JSON with proper headers.
		return new WP_REST_Response($products, 200);
	}

    /**
     * Recursively flattens nested option details into a single list of items.
     *
     * @param array $options_details Nested option details array.
     * @return array Flattened list of options.
     */
    private function flatten_options_details($options_details)
    {
        $flat = [];
        if (!is_array($options_details)) {
            return $flat;
        }
        foreach ($options_details as $key => $value) {
            if (is_array($value)) {
                if (isset($value['title'])) {
                    $flat[] = $value;
                } else {
                    $flat = array_merge($flat, $this->flatten_options_details($value));
                }
            }
        }
        return $flat;
    }
}