<?php

namespace App\Services;

// use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;

use Duitku\Config;

use Exception;

class Duitku
{
    public function __construct($config_duitku)
    {
        $merchantKey = $config_duitku['merchant_key'];
        $merchantCode = $config_duitku['merchant_code'];

        $this->duitkuConfig = new Config($merchantKey, $merchantCode);
        $this->duitkuConfig->setSandboxMode(env('DUITKU_SANDBOX', true));


        // $duitkuConfig = new \Duitku\Config("3b4264fb0118bab008448a67e83f6cbe", "DS12798");

        // // false for production mode
        // // true for sandbox mode
        // $duitkuConfig->setSandboxMode(true);
    }


    public function applyInvoice($patient, $invoices, $paymentCreate, $total_price, $paymentMethods)
    {

        $paymentMethod      = $paymentMethods->code;
        $paymentAmount      = $total_price; // Amount

        $email              = $patient->email ?? ''; //"customer@gmail.com"; // your customer email
        $phoneNumber        = $patient->phone ?? ''; //"081234567890"; // your customer phone number (optional)
        $productDetails     = $invoices->invoice_number;

        $merchantOrderId    = $paymentCreate->transaction_id; // from merchant, unique
        // dd($merchantOrderId);
        $additionalParam    = ''; // optional
        $merchantUserInfo   = ''; // optional
        $customerVaName     = $patient->name ?? ''; // display name on bank confirmation display
        $callbackUrl        = env('DUITKU_PAYMENT_CALLBACK_URL'); // url for callback
        $returnUrl          = 'https://dev-superapp.primaya.id';
        $expiryPeriod       = $paymentMethods->timeout; // set the expired time in minutes

        // Customer Detail
        $firstName          = $patient->name ?? '';
        // dd($firstName);
        $lastName           = $patient->last_name ?? '';

        // Address
        $alamat             = $patient->address->first()->line ?? '';
        // dd($alamat);
        $city               = $patient->address->first()->city->name ?? '';
        // dd($city);
        $postalCode         = $patient->postal_code ?? '';
        $countryCode        = "ID";

        $address = array(
            'firstName'     => $firstName,
            'lastName'      => $lastName,
            'address'       => $alamat,
            'city'          => $city,
            'postalCode'    => $postalCode,
            'phone'         => $phoneNumber,
            'countryCode'   => $countryCode
        );

        $customerDetail = array(
            'firstName'         => $firstName,
            'lastName'          => $lastName,
            'email'             => $email,
            'phoneNumber'       => $phoneNumber,
            'billingAddress'    => $address,
            // 'shippingAddress'   => $address
        );

        // $itemDetails = [];
        // foreach ($invoices->items as $item) {
        //     $itemDetails[] = [
        //         'name'  => $invoices->invoice_number,
        //         'price'  => (int) $item->price_net,
        //         'quantity'  => 1,
        //     ];
        // }

        $itemDetails            = array(
            array(
                'name'  => $invoices->invoice_number,
                'price'  => (int) $total_price,
                'quantity'  => 1,
            )
        );

        $params = array(
            'paymentMethod'     => $paymentMethod,
            'paymentAmount'     => (int) $paymentAmount,
            'merchantOrderId'   => $merchantOrderId,
            'productDetails'    => $productDetails,
            'additionalParam'   => $additionalParam,
            'merchantUserInfo'  => $merchantUserInfo,
            'customerVaName'    => $customerVaName,
            'email'             => $email,
            'phoneNumber'       => $phoneNumber,
            'itemDetails'       => $itemDetails,
            'customerDetail'    => $customerDetail,
            'callbackUrl'       => $callbackUrl,
            'returnUrl'         => $returnUrl,
            'expiryPeriod'      => $expiryPeriod
        );

        $this->transaction_details = $params;
        return $this;
    }

    public function createPayment()
    {
        try {
            // createInvoice Request
            $responseDuitku = \Duitku\Api::createInvoice($this->transaction_details, $this->duitkuConfig);

            return json_decode($responseDuitku);
        } catch (\Exception $e) {
            throw $e;
        }
    }


    public function checkTransaction($paymentCreate)
    {
        try {
            // $merchantOrderId = "96ce0853-35e2-4809-97bf-47463d236773";
            $merchantOrderId = $paymentCreate->first()->transaction_id;
            // dd($merchantOrderId);

            $transactionList = \Duitku\Api::transactionStatus($merchantOrderId, $this->duitkuConfig);

            header('Content-Type: application/json');
            $transaction = json_decode($transactionList);

            // var_dump($transactionList);

            if ($transaction->statusCode == "00") {
                return response()->json([
                    'data' => $transaction
                ]);
            } else if ($transaction->statusCode == "01") {
                return response()->json([
                    'data' => $transaction
                ]);
            } else {
                return response()->json([
                    'data' => $transaction
                ]);
                // Action Failed Or Expired
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }


    public static function getSignature($merchantCode, $amount, $merchantOrderId, $apiKey)
    {
        $params = $merchantCode . $amount . $merchantOrderId . $apiKey;

        // DS12798 
        // 110.000,00
        // 96ce58d2-0aec-4a1a-b0b1-c96c0e2ff2d8
        // 3b4264fb0118bab008448a67e83f6cbe
        return md5($params);
    }

    public function validateCallback($config_duitku, $merchantCode, $amount, $merchantOrderId, $signature)
    {

        $apiKey = $config_duitku['merchant_key'];

        if (!empty($merchantCode) && !empty($amount) && !empty($merchantOrderId) && !empty($signature)) {
            $this->params = $merchantCode . $amount . $merchantOrderId . $apiKey;
            $calcSignature = $this->getSignature($merchantCode, $amount, $merchantOrderId, $apiKey);

            if ($signature == $calcSignature) {
                return true;
            } else {
                throw new \Exception('Bad Signature');
            }
        } else {
            throw new \Exception('Bad Parameter');
        }
    }



    public function translatePaymentStatus($paymentStatusCode)
    {
        switch ($paymentStatusCode) {
            case '00':
                $status = 'success';
                break;

            default:
                $status = 'failed';
                break;
        }
        return $status;
    }

    public function paymentMethod()
    {
        try {
            $paymentAmount = "10000"; //"YOUR_AMOUNT";
            $paymentMethodList = \Duitku\Api::getPaymentMethod($paymentAmount, $this->duitkuConfig);

            header('Content-Type: application/json');
            // return 
            $paymentMethod = json_decode($paymentMethodList);
            return response()->json($paymentMethod->paymentFee);
            // echo $paymentMethodList->paymentFee;
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}
