<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Order;
use App\Models\Referral;
use App\Models\PaymentGateway;
use App\Models\EnrolledCourse;
use Auth;
use Session;



class CheckoutController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function checkout()
    {

        if (!Session::has('cart')) {
            return redirect()->route('front.cart')->with('error',"You don't have any product to checkout.");
        }

        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);

        $user = Auth::user();
        $courses = EnrolledCourse::whereUserId($user->id)->pluck('course_id');

        $courses = json_decode(json_encode($courses), true);

        foreach($cart->items as $course)
        {
            if (in_array($course['item']['id'], $courses)){
                $cart->removeItem($course['item']['id']);
            }
        }

        if (count($cart->items) > 0) {
            Session::put('cart', $cart);
        } else {
            Session::forget('cart');
            return redirect()->back()->with('success',__('You have already purchased these course.'));
        }


        $data['courses'] = $cart->items;

        $discount = 0;
        if($user->referral_id != 0){
            
            $refer = Referral::find($user->referral_id);
            $discnt = $refer->discount;
            $val = $cart->totalPrice;
            $val = $val / 100;
            $sub = $val * $discnt;
            $discount = $sub;

        }

        $data['discount'] = $discount;
        $data['totalPrice'] = $cart->totalPrice - $discount;

        $paypal = PaymentGateway::whereKeyword('paypal')->first();
        $data['paypalData'] = $paypal->convertAutoData();
        $data['paypal'] = $paypal;

        $stripe = PaymentGateway::whereKeyword('stripe')->first();
        $data['stripeData'] = $stripe->convertAutoData();
        $data['stripe'] = $stripe;

        return view('front.checkout',$data);


    }

    // Redirect To Checkout Page If Payment is Cancelled

    public function paycancle(){

        return redirect()->route('front.checkout')->with('error',__('Payment Cancelled.'));
     }


    // Redirect To Success Page If Payment is Comleted

     public function payreturn(){

        if(Session::has('tempcart')){
            $oldCart = Session::get('tempcart');
            $tempcart = new Cart($oldCart);
            $order_id = Session::get('temporder_id');
            $order = Order::find($order_id);
        }
        else{
            $tempcart = '';
            return redirect()->back();
        }

        return view('front.success',compact('tempcart','order'));
     }





}
