<?php

namespace TPS\Payment\Http\Controllers;

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

class SenagatController extends Controller
{
    public function __construct(protected OrderRepository $orderRepository, protected Senagat $senagat)
    {
    }
    /**
     * 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->senagat->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);
    }

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

        if($result['success']){

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

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

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