<?php

namespace App\PaymentChannels\Drivers\Paytr;

use App\Models\Order;
use App\Models\PaymentChannel;
use App\PaymentChannels\BasePaymentChannel;
use App\PaymentChannels\IChannel;
use Illuminate\Http\Request;

class Channel extends BasePaymentChannel implements IChannel
{
    protected $currency;
    protected $test_mode;

    protected $merchant_id;
    protected $merchant_salt;
    protected $merchant_key;


    protected array $credentialItems = [
        'merchant_id',
        'merchant_salt',
        'merchant_key',
    ];

    /**
     * Channel constructor.
     * @param PaymentChannel $paymentChannel
     */
    public function __construct(PaymentChannel $paymentChannel)
    {
        $this->currency = "TRY";//currency();

        $this->setCredentialItems($paymentChannel);
    }

    // Documentation => https://github.com/GizemSever/laravel-paytr

    private function handleConfigs()
    {
        // Credentials
        \Config::set('paytr.credentials.merchant_id', $this->merchant_id);
        \Config::set('paytr.credentials.merchant_key', $this->merchant_key);
        \Config::set('paytr.credentials.merchant_salt', $this->merchant_salt);

        // Options
        \Config::set('paytr.options.base_uri', 'https://www.paytr.com');
        \Config::set('paytr.options.timeout', 60);
        \Config::set('paytr.options.success_url', $this->makeCallbackUrl("success"));
        \Config::set('paytr.options.fail_url', $this->makeCallbackUrl("fail"));
        \Config::set('paytr.options.test_mode', !!$this->test_mode);
    }

    public function paymentRequest(Order $order)
    {
        $this->handleConfigs();
        $user = $order->user;
        $price = $this->makeAmountByCurrency($order->total_amount, $this->currency);


        $products = [];
        foreach ($order->orderItems as $orderItem) {
            $products[] = [
                'Cart Item ' . $orderItem->id, // name
                $this->makeAmountByCurrency($orderItem->amount, $this->currency), // price
                1, // Quantity
            ];
        }

        $generalSettings = getGeneralSettings();

        $mobile = !empty($user->mobile) ? $user->mobile : (!empty($generalSettings['site_phone']) ? $generalSettings['site_phone'] : '0123456789');
        $email = !empty($user->email) ? $user->email : (!empty($generalSettings['site_email']) ? $generalSettings['site_email'] : 'site_email@gmail.com');
        $siteAddress = getContactPageSettings("address");
        $address = !empty($user->address) ? $user->address : (!empty($siteAddress) ? $siteAddress : 'Platform address');

        $basket = \Paytr::basket()->addProducts($products);

        $payment = \Paytr::payment()
            ->setCurrency($this->currency)
            ->setUserPhone($mobile)
            ->setUserAddress($address)
            ->setNoInstallment(1)
            ->setMaxInstallment(1)
            ->setEmail($email)
            ->setMerchantOid($order->id)
            ->setUserIp("1.1.1.1")
            ->setPaymentAmount($price)  // Total payment amount
            ->setUserName($user->full_name)
            ->setSuccessUrl($this->makeCallbackUrl("success"))
            ->setFailUrl($this->makeCallbackUrl("fail"))
            ->setLang("en")
            ->setBasket($basket);


        $paymentRequest = \Paytr::createPayment($payment);

        if ($paymentRequest->isSuccess()) {
            $token = $paymentRequest->getToken();
            // If the payment request has been successfully created,
            // you can view the iframe using the token.
            // Iframe URL: 'https://www.paytr.com/odeme/guvenli/'. $token

            return 'https://www.paytr.com/odeme/guvenli/' . $token;

            /*$data = [
                'iframUrl' => 'https://www.paytr.com/odeme/guvenli/' . $token
            ];
            return view('design_1.web.cart.payment.channels.paytr', $data);*/
        }

        $toastData = [
            'title' => trans('cart.fail_purchase'),
            'msg' => '',
            'status' => 'error'
        ];
        return redirect()->back()->with(['toast' => $toastData])->withInput();
    }

    private function makeCallbackUrl($status)
    {
        return url("/payments/verify/Paytr?status={$status}");
    }

    public function verify(Request $request)
    {
        $this->handleConfigs();
        $user = auth()->user();

        $verification = \Paytr::paymentVerification($request);
dd($verification);
        if (!$verification->verifyRequest()) {
            // Throw unauthorized
        }

        $orderId = $verification->getMerchantOid(); // Payment id generated by you
        $isSuccess = $verification->isSuccess(); // Is the payment status successful

        $order = Order::where('id', $orderId)
            ->where('user_id', $user->id)
            ->first();

        if (!empty($order)) {
            $orderStatus = Order::$fail;

            if ($isSuccess) {
                $orderStatus = Order::$paying;
            }

            $order->update([
                'status' => $orderStatus
            ]);
        }

        return $order;
    }
}
