<?PHP

class CcpwRestApi
{
    public static $instanceApi;

    public static function getInstance()
    {
        if (!isset(self::$instanceApi)) {
            self::$instanceApi = new self();
        }
        return self::$instanceApi;
    }

    public function __construct()
    {
        add_action('rest_api_init', array($this, 'registerRestApi'));
        add_filter('ccpw_allowed_origin', array($this,'set_ccpw_allowed_origin'));
    }

    public function registerRestApi()
    {
        register_rest_route('crypto-widget-pro', 'calculatorData', array(
            'methods' => 'POST',
            'callback' => array($this, 'ccpwCalcData'),
            'permission_callback' =>  array($this, 'ccpwPermissionCheck'),
        ));

        register_rest_route('crypto-widget-pro', 'allData', array(
            'methods' => 'POST',
            'callback' => array($this, 'ccpwAllData'),
            'permission_callback' => array($this, 'ccpwPermissionCheck'),
        ));
        register_rest_route('crypto-widget-pro', 'saveTransaction', array(
            'methods' => 'POST',
            'callback' => array($this, 'saveTransaction'),
            'permission_callback' => array($this, 'ccpwPermissionCheck'),
        ));
    }

    public function ccpwPermissionCheck($request)
    {
        // Get allowed origin dynamically
        $allowed_origin = apply_filters('ccpw_allowed_origin', '');

        if (empty($allowed_origin)) {
            return new WP_Error('invalid_origin', 'Allowed origin is not set', array('status' => 403));
        }

        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

        if ((strpos($origin, $allowed_origin) !== 0) && (strpos($referer, $allowed_origin) !== 0)) {
            return new WP_Error('invalid_referer', 'Invalid referer', array('status' => 403));
        }

        return true;
    }

    public function set_ccpw_allowed_origin($origin)
    {
        // Replace with logic to dynamically determine the allowed origin
        // For example, you can fetch this from the database or use a constant
        return get_site_url(); // Replace with your actual website URL
    }

    public function saveTransaction($request)
    {
        // Security check: Verify user capabilities
        if (!current_user_can('manage_options')) {
            return new WP_Error('insufficient_permissions', 'Insufficient permissions to save transactions', array('status' => 403));
        }
        
        $data = $request->get_json_params();
        
        // Verify the nonce
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field($_POST['_wpnonce']) : (isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field($_SERVER['HTTP_X_WP_NONCE']): '');

        if (!wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error('invalid_nonce', 'Nonce verification failed', array('status' => 403));
        }

        // Validate required data
        if (empty($data) || !is_array($data)) {
            return new WP_Error('invalid_data', 'Invalid transaction data', array('status' => 400));
        }

        $transactions = get_option('ccpwp_savetransaction', array());

        if (!empty($data['hash'])) {
            // Sanitize the transaction data
            $sanitized_data = array();
            $sanitized_data['hash'] = sanitize_text_field($data['hash']);
            $sanitized_data['timestamp'] = date('Y-m-d H:i:s');
            
            // Add other fields if they exist
            if (isset($data['amount'])) {
                $sanitized_data['amount'] = sanitize_text_field($data['amount']);
            }
            if (isset($data['currency'])) {
                $sanitized_data['currency'] = sanitize_text_field($data['currency']);
            }
            if (isset($data['status'])) {
                $sanitized_data['status'] = sanitize_text_field($data['status']);
            }
            
            $transactions[] = $sanitized_data;
            update_option('ccpwp_savetransaction', $transactions);
        }

        return new WP_REST_Response(array('status' => 'success', 'data' => 'saved'));

    }

    public function ccpwAllData($request)
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field($_POST['_wpnonce']) : (isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field($_SERVER['HTTP_X_WP_NONCE']) : '');

        if (!wp_verify_nonce(esc_html($nonce), 'wp_rest')){
            if (!wp_verify_nonce($request->get_param('_wpnonce'), 'your_action_nonce')) {
                wp_send_json_error('Nonce verification failed.');
            }
        }
        $ccpwAllCoins = '';
        $urlcoinData = $request->get_json_params();

        $coinslist = new ccpwp_database();
        $coinslistap = new CCPWP_api_data();
        $bitcoin = ccpwp_coins_data("bitcoin");
        $btc_price = !empty($bitcoin[0]['price']) ? $bitcoin[0]['price'] : 1;
        $ccpwCurrency = $coinslistap->ccpwp_usd_conversions('all');
        $ccpwCurrency['BTC'] = (float) $btc_price;

        if(isset($urlcoinData['coin']) && is_array($urlcoinData['coin']) && count($urlcoinData['coin']) > 0){
            $custom_coins = !empty($urlcoinData['coin']) ? array_map('sanitize_text_field', $urlcoinData['coin']) : [];
            $ccpwAllCoins = $coinslist->get_coins(array('coin_id' => esc_sql($custom_coins)));
        }else{
            $ccpwAllCoins = $coinslist->get_coins(array('number' => 100));
        }
        $finalArray = [];
        foreach ($ccpwAllCoins as $coin) {
            $response = array();
            $response['coin_id'] = $coin->coin_id;
            $response['name'] = $coin->name;
            $response['symbol'] = $coin->symbol;
            $response['price'] = $coin->price;
            $response['percent_change_24h'] = $coin->percent_change_24h;
            $response['percent_change_1y'] = $coin->percent_change_1y;
            $response['percent_change_30d'] = $coin->percent_change_30d;
            $response['percent_change_7d'] = $coin->percent_change_7d;
            $response['market_cap'] = $coin->market_cap;
            $response['total_volume'] = $coin->total_volume;
            $response['circulating_supply'] = $coin->circulating_supply;
            $response['weekly_price_data'] = unserialize($coin->weekly_price_data);
            $response['logo'] = ccpwp_coin_logo_html($coin->coin_id, $size = 128, false);
            $response['extradata'] = isset($coin->extradata) ? maybe_unserialize($coin->extradata) : "";

            $finalArray[] = $response;
        }

        return array("fiat" => $ccpwCurrency, "crypto" => $finalArray);
    }

    public function ccpwCalcData($request)
    {  
          $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field($_POST['_wpnonce']) : (isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field($_SERVER['HTTP_X_WP_NONCE']) : '');

        if (!wp_verify_nonce(esc_html($nonce), 'wp_rest')){
            wp_send_json_error('Nonce verification failed.');
        }

        $coinslist = new ccpwp_database();
        $coinslistap = new CCPWP_api_data();

        $calcDataArray = [];
        $coinIdArray = [];
        $finalArray = [];

        $ccpwAllCoins = $coinslist->get_column_specific_data(array('number' => -1, 'column' => 'symbol,coin_id,price,name'));
        $ccpwCurrency = $coinslistap->ccpwp_usd_conversions('all');

        foreach ($ccpwAllCoins as $value) {
            $coinIdArray[] = $value->coin_id;
            $calcDataArray1 = array("coin_id" => $value->coin_id, "symbol" => $value->symbol, "price" => $value->price, "name" => $value->name);
            array_push($calcDataArray, $calcDataArray1);
        }

        $finalArray = $calcDataArray;

        return array("fiat" => $ccpwCurrency, "crypto" => $finalArray);
    }
}

CcpwRestApi::getInstance();
