<?php
global $wp_query;
$msg = '';
$sts = 'error';
$transaction = $wp_query->get('transaction');
if (!empty($transaction)) {
    $payment_info = yascode_vip::get_payment_info_by_transaction($transaction);
    if (!empty($payment_info)) {
        $authority = (!empty($payment_info->authority)) ? $payment_info->authority : '';
        $price = (!empty($payment_info->price)) ? $payment_info->price : '';
        $gateway_id = (!empty($payment_info->gateway_id)) ? $payment_info->gateway_id : '';
        $payment_status = (!empty($payment_info->status)) ? $payment_info->status : '';
        $user_id = (!empty($payment_info->user_id)) ? $payment_info->user_id : 0;
        $days = (!empty($payment_info->days)) ? $payment_info->days : 0;
        if ($payment_status == 'pending') {
            $gateways = yascode_gateway::get_subscription_gateways();
            if (!empty($gateways)) {
                foreach ($gateways as $gateway) {
                    if (!empty($gateway['id']) && $gateway['id'] == $gateway_id) {
                        if (file_exists(THEME_TEMPLATE_URL_PATH . '/app/class/gateways/' . $gateway_id . '-gateway.php')) {
                            $gateway_api = (!empty($gateway['api'])) ? $gateway['api'] : '';
                            if (!empty($gateway_api)) {
                                require_once(THEME_TEMPLATE_URL_PATH . '/app/class/gateways/' . $gateway_id . '-gateway.php');
                                $verify = $gateway_id::verify_request($gateway_api, $price, $authority, $transaction);
                                if ($verify['success'] == true) {
                                    yascode_vip::add_subscriber($user_id, $days);
                                    yascode_vip::update_payment_status($transaction, 'success');
                                    $sts = 'success';
                                    $msg = 'پرداخت شما با موفقیت ثبت شد';
                                } else {
                                    yascode_vip::update_payment_status($transaction, 'failed');
                                    $msg = 'تراکنش لغو شده است ';
                                }
                                if (!empty($verify['error_code'])) $msg .= 'کد خطا : ' . $verify['error_code'];
                            } else $msg = 'کلید دسترسی یافت نشد';
                        } else $msg = 'درگاه یافت نشد';
                    }
                }
            } else $msg = 'درگاهی ثبت نشده است';
        } else $msg = 'پرداخت شما قبلا پردازش شده است';
    } else $msg = 'تراکنش یافت نشد';
    wp_redirect(PANEL_URL . '/plans?status=' . $sts . '&msg=' . $msg);
} else wp_redirect(SITE_URL);
