<?php
/**
 * SR_Zarinpal — درگاه پرداخت زرین‌پال برای گزارش خدمات
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class SR_Zarinpal {

    const SANDBOX_REQUEST = 'https://sandbox.zarinpal.com/pg/v4/payment/request.json';
    const SANDBOX_VERIFY  = 'https://sandbox.zarinpal.com/pg/v4/payment/verify.json';
    const SANDBOX_PAY     = 'https://sandbox.zarinpal.com/pg/StartPay/';
    const LIVE_REQUEST    = 'https://api.zarinpal.com/pg/v4/payment/request.json';
    const LIVE_VERIFY     = 'https://api.zarinpal.com/pg/v4/payment/verify.json';
    const LIVE_PAY        = 'https://www.zarinpal.com/pg/StartPay/';
    const DEFAULT_MERCHANT = '1344b5d4-0048-11e8-94db-005056a205be';

    public static function is_sandbox(): bool {
        return get_option( 'acc_zarinpal_sandbox', '1' ) === '1';
    }

    public static function merchant(): string {
        return (string) get_option( 'acc_zarinpal_merchant', self::DEFAULT_MERCHANT );
    }

    public static function request( int $amount_rial, string $callback_url, string $description, string $mobile = '', string $email = '' ): array {
        $endpoint = self::is_sandbox() ? self::SANDBOX_REQUEST : self::LIVE_REQUEST;
        $body = [
            'merchant_id'  => self::merchant(),
            'amount'       => $amount_rial,
            'callback_url' => $callback_url,
            'description'  => $description,
        ];
        if ( $mobile ) $body['mobile'] = $mobile;
        if ( $email )  $body['email']  = $email;

        $res = self::_post( $endpoint, $body );
        if ( empty( $res['data']['authority'] ) ) {
            $err = $res['errors']['message'] ?? ( $res['message'] ?? 'خطای درگاه' );
            return [ 'success' => false, 'message' => $err ];
        }
        $auth = sanitize_text_field( $res['data']['authority'] );
        $pay  = ( self::is_sandbox() ? self::SANDBOX_PAY : self::LIVE_PAY ) . $auth;
        return [ 'success' => true, 'authority' => $auth, 'payment_url' => $pay ];
    }

    public static function verify( string $authority, int $amount_rial ): array {
        $endpoint = self::is_sandbox() ? self::SANDBOX_VERIFY : self::LIVE_VERIFY;
        $res = self::_post( $endpoint, [
            'merchant_id' => self::merchant(),
            'authority'   => $authority,
            'amount'      => $amount_rial,
        ] );
        $code = (int) ( $res['data']['code'] ?? 0 );
        if ( $code === 100 || $code === 101 ) {
            return [
                'success' => true,
                'ref_id'  => (string) ( $res['data']['ref_id'] ?? '' ),
                'code'    => $code,
            ];
        }
        return [
            'success' => false,
            'message' => $res['errors']['message'] ?? 'پرداخت تأیید نشد',
            'code'    => $code,
        ];
    }

    public static function callback_url(): string {
        if ( function_exists( 'get_rest_url' ) ) {
            return get_rest_url( null, 'acc/v1/service/public/pay/verify' );
        }
        $base = defined( 'ACC_URL' ) ? rtrim( ACC_URL, '/' ) : '/acc-engine';
        return $base . '/api.php/acc/v1/service/public/pay/verify';
    }

    private static function _post( string $url, array $body ): array {
        $json = wp_json_encode( $body );
        if ( function_exists( 'wp_remote_post' ) ) {
            $resp = wp_remote_post( $url, [
                'headers' => [ 'Content-Type' => 'application/json', 'Accept' => 'application/json' ],
                'body'    => $json,
                'timeout' => 20,
            ] );
            if ( is_wp_error( $resp ) ) {
                return [ 'errors' => [ 'message' => $resp->get_error_message() ] ];
            }
            return json_decode( wp_remote_retrieve_body( $resp ), true ) ?: [];
        }
        $ch = curl_init( $url );
        curl_setopt_array( $ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $json,
            CURLOPT_HTTPHEADER     => [ 'Content-Type: application/json', 'Accept: application/json' ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 20,
        ] );
        $raw = curl_exec( $ch );
        curl_close( $ch );
        return json_decode( (string) $raw, true ) ?: [];
    }
}
