<?php

class PrimerPaymentsActions {

    public function __construct() {
        add_action('rest_api_init', array($this, 'piraeus_create_route'));
        add_action("wp_ajax_primer_piraeus_transactions", array($this, 'primer_piraeusbank_transactions'));
        add_filter('woocommerce_payment_gateways', array($this, 'add_primer_payment_gateway'));
        add_action('admin_enqueue_scripts', array($this, 'transaction_log_scripts'));

        $this->PrimerHelpers = new PrimerPaymentHelpers();

    }

    public function add_primer_payment_gateway($methods) {
        $methods[] = 'WC_Piraeusbank_Gateway';

        return $methods;
    }

    public function piraeus_create_route(): void {
        register_rest_route('piraeus', 'send3dsMethodNotification', array(
            array(
                'methods'             => 'POST',
                'callback'            => array($this, 'threeDSMethodNotificationURL_callback'),
                'permission_callback' => function() {
                    return '';
                },
            )
        ));
        register_rest_route('piraeus', 'sendTerms', array(
            array(
                'methods'             => 'POST',
                'callback'            => array($this, 'termUrlCallback'),
                'permission_callback' => function() {
                    return '';
                },
            )
        ));
    }

    public function threeDSMethodNotificationURL_callback(\WP_REST_Request $req) {
        $MerchantReference = (string) $req->get_param('MerchantReference');

        global $wpdb;

        if ($MerchantReference) {
            $findOrder = 'SELECT post_id FROM `' . $wpdb->postmeta . '`WHERE `meta_key` = "MerchantReference" AND `meta_value` = "' . $MerchantReference . '"	;';
            $tt        = $wpdb->get_results($findOrder);
            $order_id  = $tt['0']->post_id;
            $trans_id  = (string) $req->get_param('threeDSMethodData');
            update_post_meta($order_id, 'threeDSMethodResponseData', base64_decode($trans_id));
        }

        $response_data   = 'Success';
        $response_string = strval($response_data);
        $response        = new \WP_REST_Response($response_string);
        $response->set_status(200);

        return $response;
    }

    public function termUrlCallback(\WP_REST_Request $req) {
        global $wpdb;

        $all_params         = $req->get_params();
        $pares              = null;
        $cres               = null;
        $md                 = null;
        $threeDSSessionData = null;

        foreach ($all_params as $param_name => $param_value) {
            if (strcasecmp($param_name, 'pares') === 0) {
                $pares = $param_value;
            } elseif (strcasecmp($param_name, 'cres') === 0) {
                $cres = $param_value;
            } elseif (strcasecmp($param_name, 'md') === 0) {
                $md = $param_value;
            } elseif (strcasecmp($param_name, 'threeDSSessionData') === 0) {
                $threeDSSessionData = $param_value;
            }
        }

        if ($pares != null && $md != null) {
            $findOrder = 'SELECT post_id FROM `' . $wpdb->postmeta . '`WHERE `meta_key` = "MerchantReference" AND `meta_value` = "' . $md . '"	;';
            $tt        = $wpdb->get_results($findOrder);
            $order_id  = $tt['0']->post_id;
            update_post_meta($order_id, 'pares', $pares);
        } elseif ($cres != null && $threeDSSessionData != null) {
            $findOrder = 'SELECT post_id FROM `' . $wpdb->postmeta . '`WHERE `meta_key` = "MerchantReference" AND `meta_value` = "' . $threeDSSessionData . '"	;';
            $tt        = $wpdb->get_results($findOrder);
            $order_id  = $tt['0']->post_id;
            update_post_meta($order_id, 'cres', $cres);
        }

        $response_data = 'Authentication Procceed Successfully';
        $response      = new \WP_REST_Response($response_data);
        $response->set_status(200);

        return $response;
    }

    public function primer_piraeusbank_transactions() {
        if (is_admin()) {
            global $wpdb;

            $rows = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}piraeusbank_transactions ORDER BY id DESC LIMIT 20", ARRAY_A);
            wp_send_json([
                'type' => 'success',
                'data' => $rows
            ]);
        }
    }

    public function transaction_log_scripts() {
        wp_enqueue_script('primer-woocommerce-piraeus-payment-gateway-transactions', plugin_dir_url(dirname(__FILE__)) . '/includes/js/transactions.js', array('jquery'), PRIMER_VERSION);
        wp_localize_script('primer-woocommerce-piraeus-payment-gateway-transactions', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
    }


}

new PrimerPaymentsActions();

function primer_payments_piraeusbank_transactions_table_check(): void {
    global $wpdb;

    if ($wpdb->get_var("SHOW TABLES LIKE '" . $wpdb->prefix . "piraeusbank_transactions'") === $wpdb->prefix . 'piraeusbank_transactions') {
        $check_merch_ref = $wpdb->get_row("describe " . $wpdb->prefix . "piraeusbank_transactions merch_ref", ARRAY_A);
        if (isset($check_merch_ref['Type']) && $check_merch_ref['Type'] != "varchar(150)") {
            $wpdb->query("ALTER TABLE " . $wpdb->prefix . "piraeusbank_transactions MODIFY merch_ref varchar(150)");
        }
    } else {
        $query = 'CREATE TABLE IF NOT EXISTS ' . $wpdb->prefix . 'piraeusbank_transactions (id int(11) unsigned NOT NULL AUTO_INCREMENT, merch_ref varchar(50) not null, trans_ticket varchar(32) not null , order_id varchar(320) not null , timestamp datetime default null, PRIMARY KEY (id))';
        $wpdb->query($query);
    }
}

