<?php
/**
 * کلاس مدیریت درگاه‌های پرداخت
 */
if (!defined('ABSPATH')) exit;

class Dima_Gateway {
    
    /**
     * پردازش پرداخت
     */
    public static function process_payment($order_id, $gateway = null) {
        if (!$gateway) {
            $gateway = get_option('dima_payment_gateway', 'zarinpal');
        }
        
        global $wpdb;
        $table = $wpdb->prefix . 'dima_orders';
        $order = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id = %d", $order_id));
        
        if (!$order) {
            return new WP_Error('order_not_found', 'سفارش یافت نشد');
        }
        
        $token = Dima_Security::generate_transaction_token($order_id);
        
        switch ($gateway) {
            case 'zarinpal':
                return self::zarinpal_request($order, $token);
            case 'idpay':
                return self::idpay_request($order, $token);
            case 'mellat':
                return self::mellat_request($order, $token);
            default:
                return new WP_Error('invalid_gateway', 'درگاه پرداخت نامعتبر است');
        }
    }
    
    /**
     * زرین‌پال
     */
    private static function zarinpal_request($order, $token) {
        $merchant_id = get_option('dima_zarinpal_merchant');
        
        if (empty($merchant_id)) {
            return new WP_Error('no_merchant', 'Merchant ID زرین‌پال تنظیم نشده است');
        }
        
        $callback_url = add_query_arg(array(
            'dima_callback' => '1',
            'gateway' => 'zarinpal',
            'order_id' => $order->id,
            'token' => $token
        ), home_url('/'));
        
        $customer_data = json_decode($order->customer_data, true);
        
        $data = array(
            'MerchantID' => $merchant_id,
            'Amount' => intval($order->final_amount),
            'CallbackURL' => $callback_url,
            'Description' => 'خرید از ' . get_bloginfo('name') . ' - سفارش #' . $order->id,
            'Email' => isset($customer_data['email']) ? sanitize_email($customer_data['email']) : '',
            'Mobile' => isset($customer_data['phone']) ? Dima_Security::sanitize_phone($customer_data['phone']) : ''
        );
        
        $response = wp_remote_post('https://api.zarinpal.com/pg/v4/payment/request.json', array(
            'body' => wp_json_encode($data),
            'headers' => array('Content-Type' => 'application/json', 'Accept' => 'application/json'),
            'timeout' => 30,
            'sslverify' => true
        ));
        
        if (is_wp_error($response)) {
            Dima_Security::get_instance()->log_security_event('payment_error', array(
                'gateway' => 'zarinpal',
                'order_id' => $order->id,
                'error' => $response->get_error_message()
            ), 'error');
            return $response;
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['data']['authority'])) {
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'dima_orders',
                array('transaction_id' => $body['data']['authority']),
                array('id' => $order->id)
            );
            return 'https://www.zarinpal.com/pg/StartPay/' . $body['data']['authority'];
        }
        
        $error_msg = isset($body['errors']['message']) ? $body['errors']['message'] : 'خطای ناشناخته';
        Dima_Security::get_instance()->log_security_event('payment_request_failed', array(
            'gateway' => 'zarinpal',
            'order_id' => $order->id,
            'error' => $error_msg
        ), 'error');
        
        return new WP_Error('payment_error', $error_msg);
    }
    
    /**
     * IDPay
     */
    private static function idpay_request($order, $token) {
        $api_key = get_option('dima_idpay_api_key');
        
        if (empty($api_key)) {
            return new WP_Error('no_api_key', 'API Key IDPay تنظیم نشده است');
        }
        
        $callback_url = add_query_arg(array(
            'dima_callback' => '1',
            'gateway' => 'idpay',
            'order_id' => $order->id,
            'token' => $token
        ), home_url('/'));
        
        $customer_data = json_decode($order->customer_data, true);
        
        $data = array(
            'order_id' => $order->id,
            'amount' => intval($order->final_amount),
            'callback' => $callback_url,
            'name' => isset($customer_data['name']) ? sanitize_text_field($customer_data['name']) : '',
            'phone' => isset($customer_data['phone']) ? Dima_Security::sanitize_phone($customer_data['phone']) : '',
            'mail' => isset($customer_data['email']) ? sanitize_email($customer_data['email']) : '',
            'desc' => 'پرداخت سفارش #' . $order->id
        );
        
        $response = wp_remote_post('https://api.idpay.ir/v1.1/payment', array(
            'body' => wp_json_encode($data),
            'headers' => array(
                'Content-Type' => 'application/json',
                'X-API-KEY' => $api_key,
                'X-SANDBOX' => '0'
            ),
            'timeout' => 30,
            'sslverify' => true
        ));
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['id']) && isset($body['link'])) {
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'dima_orders',
                array('transaction_id' => $body['id']),
                array('id' => $order->id)
            );
            return $body['link'];
        }
        
        $error_msg = isset($body['error_message']) ? $body['error_message'] : 'خطای ناشناخته';
        return new WP_Error('payment_error', $error_msg);
    }
    
    /**
     * بانک ملت
     */
    private static function mellat_request($order, $token) {
        $terminal_id = get_option('dima_mellat_terminal_id');
        $username = get_option('dima_mellat_username');
        $password = get_option('dima_mellat_password');
        
        if (empty($terminal_id) || empty($username) || empty($password)) {
            return new WP_Error('no_credentials', 'اطلاعات درگاه ملت تنظیم نشده است');
        }
        
        if (!extension_loaded('soap')) {
            return new WP_Error('soap_missing', 'افزونه SOAP در سرور فعال نیست');
        }
        
        try {
            $soap = new SoapClient('https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl', array(
                'encoding' => 'UTF-8',
                'cache_wsdl' => WSDL_CACHE_NONE
            ));
            
            $result = $soap->bpStartPayment(array(
                'terminalId' => intval($terminal_id),
                'userName' => $username,
                'userPassword' => $password,
                'callBackUrl' => add_query_arg(array(
                    'dima_callback' => '1',
                    'gateway' => 'mellat',
                    'order_id' => $order->id,
                    'token' => $token
                ), home_url('/')),
                'amount' => intval($order->final_amount),
                'localDate' => date('Ymd'),
                'localTime' => date('His'),
                'orderId' => intval($order->id),
                'additionalData' => 'سفارش #' . $order->id
            ));
            
            $response = explode(',', $result->return);
            $res_code = $response[0];
            
            if ($res_code == '0') {
                $ref_id = $response[1];
                global $wpdb;
                $wpdb->update(
                    $wpdb->prefix . 'dima_orders',
                    array('transaction_id' => $ref_id),
                    array('id' => $order->id)
                );
                return array(
                    'url' => 'https://bpm.shaparak.ir/pgwchannel/startpay.mellat',
                    'post_data' => array('RefId' => $ref_id)
                );
            }
            
            return new WP_Error('payment_error', 'خطا در اتصال به درگاه ملت - کد: ' . $res_code);
        } catch (Exception $e) {
            return new WP_Error('soap_error', 'خطا در اتصال SOAP: ' . $e->getMessage());
        }
    }
    
    /**
     * تایید پرداخت
     */
    public static function verify_payment($gateway, $order_id, $data) {
        global $wpdb;
        $table = $wpdb->prefix . 'dima_orders';
        
        $order = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id = %d", $order_id));
        if (!$order) return false;
        
        // بررسی توکن
        if (!isset($data['token']) || !Dima_Security::verify_transaction_token($order_id, $data['token'])) {
            Dima_Security::get_instance()->log_security_event('payment_token_invalid', array(
                'gateway' => $gateway,
                'order_id' => $order_id
            ), 'critical');
            return false;
        }
        
        switch ($gateway) {
            case 'zarinpal': return self::zarinpal_verify($order);
            case 'idpay': return self::idpay_verify($order);
            case 'mellat': return self::mellat_verify($order, $data);
            default: return false;
        }
    }
    
    private static function zarinpal_verify($order) {
        $merchant_id = get_option('dima_zarinpal_merchant');
        
        $verify_data = array(
            'MerchantID' => $merchant_id,
            'Authority' => $order->transaction_id,
            'Amount' => intval($order->final_amount)
        );
        
        $response = wp_remote_post('https://api.zarinpal.com/pg/v4/payment/verify.json', array(
            'body' => wp_json_encode($verify_data),
            'headers' => array('Content-Type' => 'application/json'),
            'timeout' => 30,
            'sslverify' => true
        ));
        
        if (is_wp_error($response)) return false;
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['data']['code']) && in_array($body['data']['code'], array(100, 101))) {
            $ref_id = isset($body['data']['ref_id']) ? $body['data']['ref_id'] : '';
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'dima_orders',
                array('status' => 'completed', 'ref_id' => $ref_id),
                array('id' => $order->id)
            );
            return true;
        }
        
        return false;
    }
    
    private static function idpay_verify($order) {
        $api_key = get_option('dima_idpay_api_key');
        
        $verify_data = array(
            'id' => $order->transaction_id,
            'order_id' => $order->id
        );
        
        $response = wp_remote_post('https://api.idpay.ir/v1.1/payment/verify', array(
            'body' => wp_json_encode($verify_data),
            'headers' => array(
                'Content-Type' => 'application/json',
                'X-API-KEY' => $api_key,
                'X-SANDBOX' => '0'
            ),
            'timeout' => 30,
            'sslverify' => true
        ));
        
        if (is_wp_error($response)) return false;
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['status']) && in_array($body['status'], array(100, 200))) {
            if (isset($body['payment']['amount'])) {
                if (!Dima_Security::verify_payment_amount($order->id, $body['payment']['amount'] / 10)) {
                    Dima_Security::get_instance()->log_security_event('payment_amount_mismatch', array(
                        'order_id' => $order->id,
                        'gateway' => 'idpay'
                    ), 'critical');
                    return false;
                }
            }
            
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'dima_orders',
                array(
                    'status' => 'completed',
                    'ref_id' => isset($body['payment']['track_id']) ? $body['payment']['track_id'] : ''
                ),
                array('id' => $order->id)
            );
            return true;
        }
        
        return false;
    }
    
    private static function mellat_verify($order, $data) {
        $terminal_id = get_option('dima_mellat_terminal_id');
        $username = get_option('dima_mellat_username');
        $password = get_option('dima_mellat_password');
        
        if (!isset($data['SaleOrderId']) || !isset($data['SaleReferenceId'])) {
            return false;
        }
        
        try {
            $soap = new SoapClient('https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl');
            
            $result = $soap->bpCheckRequest(array(
                'terminalId' => intval($terminal_id),
                'userName' => $username,
                'userPassword' => $password,
                'orderId' => intval($order->id),
                'saleOrderId' => intval($data['SaleOrderId']),
                'saleReferenceId' => intval($data['SaleReferenceId'])
            ));
            
            if ($result->return == '0') {
                $result = $soap->bpSettleRequest(array(
                    'terminalId' => intval($terminal_id),
                    'userName' => $username,
                    'userPassword' => $password,
                    'orderId' => intval($order->id),
                    'saleOrderId' => intval($data['SaleOrderId']),
                    'saleReferenceId' => intval($data['SaleReferenceId'])
                ));
                
                if (in_array($result->return, array('0', '45'))) {
                    global $wpdb;
                    $wpdb->update(
                        $wpdb->prefix . 'dima_orders',
                        array('status' => 'completed', 'ref_id' => $data['SaleReferenceId']),
                        array('id' => $order->id)
                    );
                    return true;
                }
            }
            return false;
        } catch (Exception $e) {
            return false;
        }
    }
}

/**
 * Callback handler برای درگاه‌ها
 */
add_action('init', function() {
    if (!isset($_GET['dima_callback'])) return;
    
    $gateway = isset($_GET['gateway']) ? sanitize_text_field($_GET['gateway']) : '';
    $order_id = isset($_GET['order_id']) ? absint($_GET['order_id']) : 0;
    $status = isset($_GET['Status']) ? sanitize_text_field($_GET['Status']) : '';
    
    if (!$order_id || !$gateway) {
        wp_die('درخواست نامعتبر است');
    }
    
    $payment_success = false;
    
    if ($gateway === 'zarinpal' && $status === 'OK') {
        $payment_success = Dima_Gateway::verify_payment($gateway, $order_id, $_GET);
    } elseif ($gateway === 'idpay') {
        $payment_success = Dima_Gateway::verify_payment($gateway, $order_id, $_GET);
    } elseif ($gateway === 'mellat' && isset($_GET['ResCode']) && $_GET['ResCode'] === '0') {
        $payment_success = Dima_Gateway::verify_payment($gateway, $order_id, $_GET);
    }
    
    $redirect_url = add_query_arg(array(
        'payment_status' => $payment_success ? 'success' : 'failed',
        'order_id' => $order_id
    ), home_url('/payment-result/'));
    
    if ($payment_success) {
        Dima_Cart::get_instance()->clear();
    }
    
    wp_redirect($redirect_url);
    exit;
});