<?php

namespace Modules\Subscription\Http\Controllers;

use App\BillingDetails;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Coupons\Entities\Coupon;
use Modules\Subscription\Entities\CourseSubscription;
use Modules\Subscription\Entities\SubscriptionCart;
use Modules\Subscription\Entities\SubscriptionCheckout;

class CourseSubscriptionController extends Controller
{

    public function planAddToCart()
    {
        try {

            $cart = SubscriptionCart::where('user_id', Auth::id())->first();
            $plan = CourseSubscription::find(\request('id'));
            $bill = BillingDetails::where('user_id', \auth()->id())->orderBy('updated_at')->first();
            if (empty($plan)) {
                return false;

            }
            if (!$cart) {
                $cart = new SubscriptionCart();
                $cart->tracking = getTrx(20);
            }
            $cart->user_id = Auth::id();
            $cart->plan_id = $plan->id;
            $cart->price = $plan->price;
            $cart->days = $plan->days;
            $cart->billing_detail_id = $bill->id ?? 0;
            $cart->save();

            $data = [
                'code' => \request('code'),
                'total' => $plan->price
            ];
            $result = $this->applyCoupon($data, $cart);

            $data = [
                'price' => getPriceFormat($result['total'] ?? $cart->price),
                'raw_price' => $result['total'] ?? $cart->price,
                'days' => $cart->days,
                'message' => $result['success'] ?? '',
            ];
            return json_encode($data);
        } catch (\Exception $e) {

        }
    }

    public function addToCart($user_id, $plan_id)
    {
        if (demoCheck()) {
            return false;
        }

        if (!Auth::check()) {
            Toastr::error(trans('subscription.You must login'), trans('common.Failed'));
            return false;
        }
        if (Auth::user()->role_id == 1) {
            Toastr::error(trans('subscription.You are not allowed'), trans('common.Failed'));
            return false;


        }
        $cart = SubscriptionCart::where('user_id', $user_id)->first();
        $plan = CourseSubscription::find($plan_id);
        if (empty($plan)) {
            Toastr::error(trans('subscription.Invalid Plan'), trans('common.Failed'));
            return false;

        }
        if (!$cart) {
            $cart = new SubscriptionCart();
            $cart->tracking = getTrx(20);
        }
        $cart->user_id = $user_id;
        $cart->plan_id = $plan_id;
        $cart->price = $plan->price;
        $cart->days = $plan->days;
        $cart->billing_detail_id = 0;
        $cart->save();
        return true;
    }


    public function applyCoupon($data, $cart)
    {


        try {

            $code = $data['code'];
            $total = $data['total'];

            $tracking = $cart->tracking;
            SubscriptionCheckout::where('tracking', $tracking)->delete();

            if (hasTax()) {
                $tax = taxAmount($total);
                $errorTotal = applyTax($total);
            } else {
                $tax = 0;
                $errorTotal = $total;
            }
            $coupon = Coupon::where('code', $code)->whereDate('start_date', '<=', Carbon::now())
                ->whereDate('end_date', '>=', Carbon::now())->where('status', 1)->first();
            if (!$coupon) {
                return false;
            }


            $couponApply = false;


            $checkout = new SubscriptionCheckout();
            $checkout->billing_detail_id = (int)$cart->billing_detail_id;
            if (isset($coupon)) {
                if ($coupon->limit != 0) {
                    if ($coupon->limit <= $coupon->loginUserTotalUsed()) {
                        return [
                            'error' =>trans('subscription.Already used this coupon'),
                            'total' => number_format(getPriceAsNumber($errorTotal), 2),
                            'tax' => number_format(getPriceAsNumber($tax), 2),
                        ];
                    }
                }


                $max_dis = $coupon->max_discount;
                $min_purchase = $coupon->min_purchase;
                $type = $coupon->type;
                $value = $coupon->value;

                $checkTrackingId = SubscriptionCheckout::where('tracking', $tracking)->where('coupon_id', $coupon)->first();

                if ($checkTrackingId) {
                    return [
                        'error' =>trans('subscription.Already used this coupon'),
                        'total' => number_format(getPriceAsNumber($errorTotal), 2),
                        'tax' => number_format(getPriceAsNumber($tax), 2),
                    ];
                }

                if ($total >= $min_purchase) {


                    if ($coupon->category == 1) {
                        $couponApply = true;
                    } elseif ($coupon->category == 2) {

                        return [
                            'error' => trans('subscription.This coupon apply for single course'),
                            'total' => number_format(getPriceAsNumber($errorTotal), 2),
                            'tax' => number_format(getPriceAsNumber($tax), 2),
                        ];
                    } elseif ($coupon->category == 3) {
                        if ($coupon->coupon_user_id != $checkout->user_id) {
                            return [
                                'error' => trans('subscription.This coupon not for you'),
                                'total' => number_format(getPriceAsNumber($errorTotal), 2),
                                'tax' => number_format(getPriceAsNumber($tax), 2),
                            ];
                        } else {
                            $couponApply = true;
                        }
                    }

                    $final = $total;
                    if ($couponApply) {
                        if ($type == 0) {
                            $discount = (($total * $value) / 100);
                            if ($discount >= $max_dis) {

                                $final = ($total - $max_dis);
                                $checkout->discount = $max_dis;
                                $checkout->purchase_price = $final;
                            } else {

                                $final = ($total - $discount);
                                $checkout->discount = $discount;
                                $checkout->purchase_price = $final;

                            }
                        } else {
                            $discount = $value;
                            if ($discount >= $max_dis) {
                                $final = ($total - $max_dis);

                                $checkout->discount = $max_dis;
                                $checkout->purchase_price = $final;
                            } else {
                                $final = ($total - $discount);
                                $checkout->discount = $discount;
                                $checkout->purchase_price = $final;
                            }
                        }
                    }
                    if ($discount > $total) {
                        return [
                            'error' => trans('frontend.Invalid Request'),
                            'total' => number_format(getPriceAsNumber($errorTotal), 2),
                            'tax' => number_format(getPriceAsNumber($tax), 2),
                        ];
                    }
                    if (hasTax()) {
                        $tax = taxAmount($final);
                        $final = applyTax($final);
                        $checkout->tax = $tax;
                        $checkout->purchase_price = $final;

                    } else {
                        $tax = 0;
                    }
                    $checkout->tracking = $tracking;
                    $checkout->purchase_price = getPriceAsNumber($final);
                    $checkout->user_id = Auth::id();
                    $checkout->coupon_id = $coupon->id;
                    $checkout->price = $total;
                    $checkout->status = 0;
                    $checkout->save();

                    return [
                        'success' => trans('coupons.You have received') . ' ' . ($coupon->type == 1 ? getPriceFormat($coupon->value) : $coupon->value . '%') . ' ' . trans('coupons.discount'),
                        'total' => number_format(getPriceAsNumber($final), 2),
                        'tax' => number_format(getPriceAsNumber($tax), 2),
                        'discount' => number_format(getPriceAsNumber($checkout->discount), 2)
                    ];
                } else {
                    return [
                        'error' => trans('frontend.Coupon Minimum Purchase Does Not Match'),
                        'total' => number_format(getPriceAsNumber($errorTotal), 2),
                        'tax' => number_format(getPriceAsNumber($tax), 2),
                    ];
                }

            } else {
                $checkout->discount = 0;
                $checkout->coupon_id = null;
                $checkout->purchase_price = $total;
                $checkout->save();
                return [
                    'error' => trans('frontend.Invalid Coupon'),
                    'total' => number_format(getPriceAsNumber($errorTotal), 2),
                    'tax' => number_format(getPriceAsNumber($tax), 2),
                ];
            }

        } catch (\Exception $e) {
            return ['error' => trans('common.Operation Failed')];
        }
    }
}
