<?php

namespace App\Http\Services\Payout\Bank;

use App\Http\Services\Payout\Bank\Util\ResponseBankUtilPayoutServices;
use App\Models\PaymentMethod;
use Illuminate\Support\Facades\URL;

/**
 * Laravel/Symfony Developer
 * Name: bukar mai 
 * Telegram: @Mamber001
 * Hire me via Telegram: @Mamber001
 */
class GcashPayBankPayoutServices
{

    /**
     * Transfer Payment
     * 
     * @param string reference
     * @param string currency
     * @param string amount
     * @param string method
     * @param string bank code
     * @param string bank name
     * @param string account number
     * @param string account name
     * @param string narration
     */
    public function transfer(
        string $reference,
        string $currency,
        string $amount,
        string $method,
        string $bank_code,
        string $bank_name = null,
        string $account_number,
        string $account_name,
        string $narration = 'Goods'
    )
    {
        try {
            // Get HeyPay settings
            $setting = PaymentMethod::where(['tag' => 'gcashpay', 'status' => 'active'])->first();
            if(!$setting) throw new \Exception("gcashPay service not enabled at the moment");
            $setting = json_decode($setting->settings);

            // Build request body (amount in cents)
            $requestBody = [
                'appid'     => $setting->appid->value,
                'amount'    => intval($amount * 100),
                'order_no'  => $reference,
                'timestamp' => time(),
                'notify_url'=> URL::route('ipn.heypay.payout'),
                'pay_code'  => $bank_code,
                'pay_name'  => $account_name,
                'pay_no'    => $account_number,
                'ext_no'    => $narration,
            ];

            // Sign the request
            $requestBody['sign'] = self::buildSignDigest($requestBody, $setting->app_key->value);

            // Send Curl Request
            $sendRequest = $this->curlRequest('POST', '/v1/payout/create', $requestBody);

            if($sendRequest instanceof \Exception) throw new \Exception($sendRequest->getMessage());

            // Format Response
            $response = ResponseBankUtilPayoutServices::response(
                200,
                2,
                true,
                $reference,
                $sendRequest['order_no'] ?? '',
                $currency,
                $amount,
                $method,
                $bank_code,
                $bank_name,
                $account_number,
                $account_name,
                $narration
            );

            return $response;

        } catch (\Exception $th) {
            return $th;
        }
    }

    /**
     * Curl Request
     */
    public function curlRequest(string $method, string $endpoint, array $body = [])
    {
        try {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => 'https://api.heypay.org' . $endpoint,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_POSTFIELDS => json_encode($body),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json'
                ],
            ]);

            $response = curl_exec($curl);
            $err = curl_error($curl);
            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);

            if ($err) throw new \Exception('Curl returned error: ' . $err);

            $response_array = json_decode($response, true);
            if(!in_array($httpcode, [200])) throw new \Exception($response_array['msg'] ?? 'Unknown error');
            if(($response_array['code'] ?? 1) !== 0) throw new \Exception($response_array['msg'] ?? 'Unknown error');

            return $response_array['data'] ?? [];

        } catch (\Exception $th) {
            return $th;
        }
    }

    /**
     * Build Signature Digest (HMAC-SHA1)
     */
    public static function buildSignDigest(array $data, string $key): string
    {
        unset($data['sign']);
        ksort($data);

        $str = '';
        foreach($data as $k => $v) {
            if($v !== '') $str .= $k . '=' . $v . '&';
        }
        $str = rtrim($str, '&');

        return base64_encode(hash_hmac("sha1", $str, $key, true));
    }
}
