<?php


namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ParameterGlobalController;
use App\Models\MasterConfig;
use App\Models\OauthClient;
use Illuminate\Support\Facades\Log;
use App\Models\ApiLogError;
use Illuminate\Http\Response;

class RajaGadaiOutController extends Controller
{

    public $logKey; //agar bisa diakses lewat CLI (ini saat test prelive)
    public function __construct()
    {
        $route = request()->route();
        if ($route) {
            $action = $route->getActionName(); // misalnya "App\Http\Controllers\HomeController@index"
            $this->logKey = [
                'log_key' => (int) $this->keyLogs(),
                'caller'  => $action
            ];
        } else {
            // default logKey kalau dipanggil dari CLI (job/command)
            $this->logKey = [
                'log_key' => (int) $this->keyLogs(),
                'caller'  => 'CLI'
            ];
        }
    }


    public function sendAPI($data, $url, $name_module)
    {
        try {
            $api = MasterConfig::where('key', 'BASE_URL_RGAPP')->first();
            $baseUrl = $api->value;
            $urlFinal = $baseUrl . $url;
            $auth = OauthClient::where('client_secret', ParameterGlobalController::client_secret_rg())->first();
            $headers = [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $auth->token,
            ];
            Log::channel('rgapps')->info('url: ' . $urlFinal, $this->logKey);
            Log::channel('rgapps')->info('Header: ' . json_encode($headers), $this->logKey);
            Log::channel('rgapps')->info('Request: ' . json_encode($data), $this->logKey);
             
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $urlFinal);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $response = curl_exec($ch);

            if ($response === FALSE) {
                die('Curl failed: ' . curl_error($ch));
            }

            $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $request = json_encode($data);
            if ($http_status != 200) {
                ApiLogError::create([
                    'name_module' => $name_module,
                    'url' => $urlFinal,
                    'status_code' => $http_status,
                    'request' => $request,
                    'response' => $response,
                    'created_who' => 'api-mobile',
                ]);
            }
            curl_close($ch);
            Log::channel('rgapps')->info('Response: ' . $response, $this->logKey);
            return $response;
        } catch (\Exception $e) {
            $errorMessage = $this->responseError($e, 'rgapps', $this->logKey);
            return response()->json($errorMessage, ($e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function extend($member,  $noTrans)
    {
        $url = '/transaction/data-extend';
        $data = [
            'memberNumber' => $member,
            'transactionNumber' => $noTrans,
        ];
        $name_module = 'Extend';
        $response = $this->sendAPI($data, $url, $name_module);
        return $response;
    }

    public function payment($noTrans, $nominal, $voucher, $point, $extDocnum)
    {
        $url = '/transaction/payment';
        $data = [
            'transactionNumber' => $noTrans,
            'extendDocNumber' => $extDocnum,
            'amount' => $nominal,
            'codeVoucher' => $voucher,
            'usedPoint' => $point
        ];
        $name_module = 'Payment';
        $response = $this->sendAPI($data, $url, $name_module);
        return $response;
    }

    public function dataGadai($member)
    {
        try {
            $api = MasterConfig::where('key', 'BASE_URL_RGAPP')->first();
            $baseUrl = $api->value;
            $urlFinal = $baseUrl . '/transaction/data-gadai?memberNumber=' . $member;
            $data = [];
            $auth = OauthClient::where('client_secret', ParameterGlobalController::client_secret_rg())->first();
            $headers = [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $auth->token,
            ];

            Log::channel('rgapps')->info('url: ' . $urlFinal, $this->logKey);
            Log::channel('rgapps')->info('Header: ' . json_encode($headers), $this->logKey);
            Log::channel('rgapps')->info('Request: ' . json_encode($data), $this->logKey);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $urlFinal);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $response = curl_exec($ch);

            if ($response === FALSE) {
                die('Curl failed: ' . curl_error($ch));
            }

            $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $responseBody = substr($response, $headerSize);

            curl_close($ch);
            Log::channel('rgapps')->info('Response:' . $response, $this->logKey);
            return $response;
        } catch (\Exception $e) {
            $errorMessage = $this->responseError($e, 'rgapps', $this->logKey);
            return response()->json($errorMessage, ($e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function register($memberNumber, $phoneNum)
    {
        $url = '/customer/register';
        $data = [
            'phoneNumber' => $phoneNum,
            'memberNumber' => $memberNumber,
        ];
        $name_module = 'Register';
        $response = $this->sendAPI($data, $url, $name_module);
        return $response;
    }

    public function redeem($phoneNumber, $member, $exCode, $amount, $duration)
    {
        $data = [
            'phoneNumber' => $phoneNumber,
            'memberNumber' => $member,
            'externalCode' => $exCode,
            'voucherAmount' => $amount,
            'duration' => (int)$duration
        ];

        $url = '/transaction/request-voucher';
        $name_module = 'Redeem';
        $response = $this->sendAPI($data, $url, $name_module);
        return $response;
    }

    public function redeemGB($phoneNumber, $member, $exCode, $pickupLocation, $pickupAddress, $pickupOutletCode, $itemRedeem)
    {
        $data = [
            'phoneNumber' => $phoneNumber,
            'memberNumber' => $member,
            'externalCode' => $exCode,
            'itemRedeem' => $itemRedeem,
            'pickupOutletCode' => $pickupOutletCode,
            'pickupLocation' => $pickupLocation,
            'pickupAddress' => $pickupAddress
        ];
        $url = '/transaction/request-voucher-gadai-baru';
        $name_module = 'Redeem GB';
        $response = $this->sendAPI($data, $url, $name_module);
        // Dipakai untuk throw error jika format tidak valid
        $voucher = json_decode($response, true);
        return $response;
    }
}
