<?php

namespace App\Http\Controllers\Front;


use App\Models\Cart;
use App\Models\Order;
use App\Models\InstructorOrder;
use App\Models\User;

use App\Classes\GeniusMailer;
use App\Models\Notification;
use App\Models\UserNotification;

use App\Models\Course;
use App\Models\Currency;
use App\Models\Referral;
use App\Models\Generalsetting;
use App\Models\PaymentGateway;
use App\Models\EnrolledCourse;
use App\Models\ReferralHistory;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Cartalyst\Stripe\Laravel\Facades\Stripe;

use DB;
use Auth;
use Session;
use Validator;

class StripeController extends Controller
{

    public $curr;


    public function __construct()
    {
        $this->curr = \DB::table('currencies')->where('register_id',0)->where('is_default','=',1)->first();

        //Set Stripe Keys
        $data = PaymentGateway::where('register_id',0)->whereKeyword('stripe')->first();
        $paydata = $data->convertAutoData();
        \Config::set('services.stripe.key', $paydata['key']);
        \Config::set('services.stripe.secret', $paydata['secret']);
    }

    public function store(Request $request){

        $user = Auth::user();
        $input = $request->all();

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

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


        $pay_amount = $request->pay_amount;
        $discount = $request->discount;

        $new_cart = [];
        $new_cart['totalQty'] = $cart->totalQty;
        $new_cart['totalPrice'] = $pay_amount;
        $new_cart['items'] = $cart->items;
        $new_cart = json_encode($new_cart);

        $settings = Generalsetting::findOrFail(1);

        $comission = $settings->percentage_commission;

        $success_url = route('front.payment.return');
        $item_name = $settings->title." Order";
        $item_number = Str::random(4).time();
        $item_amount = $pay_amount;


        $validator = Validator::make($request->all(),[
                        'cardNumber' => 'required',
                        'cardCVC' => 'required',
                        'month' => 'required',
                        'year' => 'required',
                    ]);

        if ($validator->passes()) {

            $stripe = Stripe::make(\Config::get('services.stripe.secret'));
            try{
                $token = $stripe->tokens()->create([
                    'card' =>[
                            'number' => $request->cardNumber,
                            'exp_month' => $request->month,
                            'exp_year' => $request->year,
                            'cvc' => $request->cardCVC,
                        ],
                    ]);
                if (!isset($token['id'])) {
                    return back()->with('error',__('Token Problem With Your Token.'));
                }

                $charge = $stripe->charges()->create([
                    'card' => $token['id'],
                    'currency' => $this->curr->name,
                    'amount' => $item_amount,
                    'description' => $item_name,
                    ]);

                if ($charge['status'] == 'succeeded') {

                    $order = new Order;
                    $order['user_id'] = $user->id;
                    $order['txnid'] = $charge['balance_transaction'];
                    $order['charge_id'] = $charge['id'];
                    $order['cart'] = $new_cart;
                    $order['order_number'] = $item_number;
                    $order['discount'] = $discount;
                    $order['pay_amount'] = $item_amount / $this->curr->value;

                    $order['currency_sign'] = $this->curr->sign;
                    $order['currency_value'] = $this->curr->value;

                    $order['method'] = $input['method'];
                    $order['status'] = 'Completed';
                    $order['payment_status'] = 'Completed';
                    $order->save();

                    foreach($cart->items as  $course)
                    {
                        EnrolledCourse::create(['user_id' => $user->id, 'course_id' => $course['item']['id']]);

                        if($course['affilate_user'] != 0){
                            if(Auth::user()->id != $course['affilate_user']){
                                ReferralHistory::create([
                                    'referrer_id' => $course['affilate_user'],
                                    'affilate_id' => Auth::user()->id,
                                    'course_id' => $course['item']['id'],
                                    'type' => $course['type']
                                ]);

                                $total_refer = ReferralHistory::where('register_id',0)->where('referrer_id',$course['affilate_user'])->count();

                                foreach(Referral::where('register_id',0)->whereType($course['type'])->get() as $refer){
                                    if($refer->times == $total_refer){
                                        User::find($course['affilate_user'])->update(['referral_id' => $refer->id]);
                                    }
                                }
                            }

                        }

                        if($course['item']['user_id'] != 0){


                            $instructor = User::find($course['item']['user_id']);

                            if($instructor->referral_id != 0){
                                $comission -= $instructor->referral->discount;
                            }

                            InstructorOrder::create([
                                'user_id' => $course['item']['user_id'],
                                'order_id' => $order->id,
                                'course_id' => $course['item']['id'],
                                'price' => $course['price'],
                                'order_number' => $order->order_number,
                                'status' => 'Completed',
                                'charge' => $comission
                            ]);

                            $discnt = $comission;
                            $val = $course['price'];
                            $val = $val / 100;
                            $sub = $val * $discnt;
                            $discount = $sub;
                            $instructor_price = $course['price'] - $discount;
        
                            $instructor->balance += $instructor_price;
                            $instructor->update();

                            //User Notification.......
                            $user_notification = new UserNotification();
                            $user_notification->user_id = $course['item']['user_id'];
                            $user_notification->order_number = $order->order_number;
                            $user_notification->save();


                        }

                    }

                    //Sending Email To Buyer

                    $data = [
                        'to' => $user->email,
                        'type' => "new_order",
                        'cname' => $user->first_name.' '.$user->last_name,
                        'oamount' => "",
                        'aname' => "",
                        'aemail' => "",
                        'wtitle' => "",
                        'onumber' => $order->order_number,
                    ];

                    $mailer = new GeniusMailer();
                    $mailer->sendAutoMail($data,$order->id);            

                    //Sending Email To Admin
                    $data = [
                        'to' => DB::table('pagesettings')->where('register_id',0)->first()->contact_email,
                        'subject' => "New Order Recieved!!",
                        'body' => "Hello Admin!<br>Your store has received a new order.<br>Order Number is ".$order->order_number.".Please login to your panel to check. <br>Thank you.",
                    ];
                    $mailer = new GeniusMailer();
                    $mailer->sendCustomMail($data);  

                    $notification = new Notification();
                    $notification->order_id = $order->id;
                    $notification->save();


                    Session::put('temporder_id',$order->id);
                    Session::put('tempcart',$cart);
                    Session::forget('cart');
                    return redirect($success_url);
                }

            }catch (Exception $e){
                return back()->with('error', $e->getMessage());
            }catch (\Cartalyst\Stripe\Exception\CardErrorException $e){
                return back()->with('error', $e->getMessage());
            }catch (\Cartalyst\Stripe\Exception\MissingParameterException $e){
                return back()->with('error', $e->getMessage());
            }
        }
        return back()->with('error', __('Please Enter Valid Credit Card Informations.'));
    }

}
