<?php
namespace Xxxwraithxxx\PayraCashCryptoPayment;

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

use \stdClass;

class Update extends Constants
{
    public static function run()
    {
        global $wpdb;
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $installed_db_version   = get_option(Constants::INSTALLED_DB_VERSION, 1);
        $transactions_table     = Constants::get_table('transactions');
        $networks_table         = Constants::get_table('networks');
        $settings_table         = Constants::get_table('settings');

        // Miration to v2
        if (version_compare($installed_db_version, '2', '<')) {

            $column_exists = $wpdb->get_results(
                $wpdb->prepare(
                    "SHOW COLUMNS FROM {$transactions_table} LIKE %s",
                    'fee_in_wei'
                )
            );

            if (empty($column_exists)) {
                $wpdb->query("
                    ALTER TABLE {$transactions_table}
                    ADD COLUMN fee_in_wei BIGINT UNSIGNED NOT NULL AFTER amount_in_wei
                ");
            }

            update_option(Constants::INSTALLED_DB_VERSION, '2');
        }
        
        // Miration to v3
        if (version_compare($installed_db_version, '3', '<')) {

            // Get curent index
            $existing_indexes = $wpdb->get_results("SHOW INDEX FROM {$transactions_table}", ARRAY_A);
            $index_names = wp_list_pluck($existing_indexes, 'Key_name');

            // Index list to add (index_name => colimn_name)
            $indexes_to_add = [
                'idx_created_at'      => 'created_at',
                'idx_order_prefix_id' => 'order_prefix_id',
                'idx_tx_hash'         => 'tx_hash',
                'idx_sender'          => 'sender',
            ];

            foreach ($indexes_to_add as $index_name => $column_name) {
                if (!in_array($index_name, $index_names)) {
                    // add index if not exists
                    $wpdb->query("ALTER TABLE {$transactions_table} ADD INDEX {$index_name} ({$column_name})");
                }
            }
            
            // Update contract
            $new_contract = '0xc56c55D9cF0FF05c85A2DF5BFB9a65b34804063b';
            $wpdb->update(
                $networks_table,
                ['payra_contract_address' => $new_contract],
                ['chain_id' => 137],
                ['%s'],
                ['%d']
            );

            // Update settings
            $raw_settings = $wpdb->get_var($wpdb->prepare(
                "SELECT settings FROM {$settings_table} WHERE symbol = %s", 
                Constants::DICT_SETTINGS_SYMBOL
            )) ?? '';

            $json_settings = json_decode($raw_settings, true);

            if (!is_array($json_settings)) {
                $json_settings = [];
            }

            if (!isset($json_settings['network_rpcs_urls'])) {
                $json_settings['network_rpcs_urls'] = [];
            }

            if (!isset($json_settings['network_rpcs_urls']['polygon']) || empty($json_settings['network_rpcs_urls']['polygon'])) {
                $json_settings['network_rpcs_urls']['polygon'] = ['https://polygon-rpc.com'];
            }

            $wpdb->update(
                $settings_table,
                ['settings' => wp_json_encode($json_settings)],
                ['symbol' => Constants::DICT_SETTINGS_SYMBOL]
            );

            update_option(Constants::INSTALLED_DB_VERSION, '3');
        }

        update_option(Constants::INSTALLED_DB_VERSION, PAYRACACR_CASH_DB_VERSION);
    }

}
