<?php

namespace TPS\Payment\Http\Controllers;

use GuzzleHttp\Exception\ConnectException;
use Illuminate\Support\Facades\Log;
use Webkul\Checkout\Facades\Cart;
use TPS\Payment\Methods\AltynAsyr;
use Webkul\Checkout\Repositories\CartRepository;
use Webkul\Sales\Repositories\OrderRepository;

class AltynAsyrController extends Controller
{

    public function __construct(protected OrderRepository $orderRepository, protected AltynAsyr $altynAsyr)
    {
    }

    /**
     * Redirects to payment gateway
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function redirect()
    {
        $result =  $this->altynAsyr->registerOrder();

        if($result['success']){
            return redirect($result['url']);
        }

        session()->flash('error', $result['message']);

        return redirect()->route('shop.checkout.onepage.index');
    }

    /**
     * Success payment
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function success(CartRepository $cartRepository, $cart_id){

        if(!auth()->guard()->check() && !session()->has('cart')){
            Cart::setCart($cartRepository->find($cart_id));
        }

        $result = $this->altynAsyr->getOrderStatus();

        if ($result['success'] ) {
            $order = $this->orderRepository->create(Cart::prepareDataForOrder());

            Cart::deActivateCart();

            session()->flash('order', $order);

//            return view('shop::checkout.retry',$result);

            return redirect()->route('shop.checkout.success');
        }

        return view('shop::checkout.retry',$result);
    }

}
