<?php

namespace Modules\Gift\Http\Controllers;

use App\Http\Controllers\PaymentController;
use App\Jobs\SendNotification;
use Exception;
use Illuminate\Http\Request;
use App\Jobs\SendGeneralEmail;
use Illuminate\Routing\Controller;
use Modules\Payment\Entities\Cart;
use Modules\Gift\Entities\GiftCart;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Auth;
use Modules\Gift\Entities\GiftRecord;
use Illuminate\Support\Facades\Artisan;
use Modules\Cashback\Entities\UserCashbackDetail;
use Modules\CourseSetting\Entities\CourseEnrolled;
use Throwable;

class AdminGiftController extends Controller
{
    public function index()
    {
        $gift_records = GiftRecord::all();
        return view('gift::index', compact('gift_records'));
    }

    public function settings()
    {
        return view('gift::settings');
    }

    public function sendInvitation($gift_record_id)
    {
        try {
            $gift_record = GiftRecord::where('id', $gift_record_id)->with('course')->first();

            $user = [];
            $user['email'] = $gift_record->gift_user_email;
            $user['name'] = $gift_record->gift_receiver_name;
            $course = $gift_record->course;
            $user = (object)$user;
            $gift_record_id_encrypt =$gift_record->id;

            $gift_record->gift_status = 3;
            $gift_record->save();

            SendNotification::dispatch('SEND_GIFT', $user,  [
                'sender' => $gift_record->sender->name,
                'course' => $course->title,
                'name' => $user->name,
                'message' => $gift_record->gift_message,
                'course_link' => route('gift.link', $gift_record_id_encrypt),
            ],[]);
            Toastr::success(_trans('common.Invitation Sent successful'), trans('common.Success'));
            return redirect()->back();
        } catch (Throwable $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function updateSettings(Request $request)
    {
        try {
            foreach ($request->except('_token') as $key => $setup) {
                UpdateGeneralSetting($key, $setup);
            }
            Toastr::success(_trans('gift.Gift Settings Updated successful'), trans('common.Success'));
            return redirect()->back();
        } catch (Throwable $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function acceptGift($gift_id)
    {
        try {
            $gift_record = GiftRecord::where('id', $gift_id)->with('course')->first();

            if ($gift_record->gift_user_email == Auth::user()->email && $gift_record->gift_status == 3) {
                if (!in_array($gift_record->gift_status, [4, 5])) {
                    $payment_controller = new PaymentController();
                    $checkout_data = $gift_record->checkout_data;
                    $checkout_info = (object)$checkout_data['payment_checkout_info'];
                    $checkout_info = GiftCart::where('tracking', $checkout_info->tracking)->with('course', 'user')->first();
                    $discount = $checkout_data['payment_discount'];
                    $cart = (object)$checkout_data['payment_cart'];
                    $carts = (object)$checkout_data['payment_carts'];
                    $courseType = (object)$checkout_data['payment_courseType'];
                    $gateWayName = $checkout_data['payment_gateWayName'];
                    $user = auth()->user();
                    $complete_enroll = $payment_controller->defaultPayment($checkout_info, $user, $discount, $cart, $carts, $courseType, $gateWayName);

                    $gift_record->gift_status = 4;
                    $gift_record->gift_receiver_id = Auth::user()->id;
                    $gift_record->save();


                    //cashback
                    if (isModuleActive('Cashback')) {
                        $user_cashback_details=UserCashbackDetail::where('is_gift',1)->where('gift_id',$gift_record->id)->first();
                        $last_enroll_this_user=CourseEnrolled::where('user_id',Auth::user()->id)->orderBy('id','desc')->first();
                        if($user_cashback_details){
                            $user_cashback_details->gift_enroll_id=$last_enroll_this_user->id;
                            $user_cashback_details->gifted_to=Auth::user()->id;
                            $user_cashback_details->save();
                        }

                    }

                    $checkout_info->delete();

                    Toastr::success(_trans('gift.Gifted Course Enrolled Successfully'), _trans('common.Success'));
                    return redirect()->route('myCourses');
                } else {
                    Toastr::error(_trans('gift.Invalid Gift'), _trans('common.Error'));
                    return redirect()->back();
                }
            } else {
                Toastr::warning(_trans('gift.This link is invalid'), _trans('common.Warning'));
                return redirect()->back();
            }
        } catch (Throwable $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function delete($gift_id)
    {
        try {
            $gift = GiftRecord::where('id', $gift_id)->first();
            $gift->delete();
            Toastr::success(_trans('gift.Gift Deleted Successfully'), _trans('common.Success'));
            return redirect()->route('gift.list');
        } catch (Throwable $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function myGifts()
    {
        try {
            $gift_records = GiftRecord::where(function ($q) {
                $q->where('user_id', Auth::user()->id)->orWhere('gift_receiver_id', Auth::user()->id);
            })
                ->with('course', 'sender', 'receiver')
                ->paginate(10);
            return view(theme('pages.my-gifts'), compact('gift_records'));
        } catch (Throwable $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function executeCommand()
    {
        try {
            Artisan::call('send:gift',[
                '--no-interaction' => true,
            ]);
        } catch (Exception $e) {

        }
        Toastr::success(trans('common.Operation successful'), trans('common.Success'));
        return redirect()->back();
    }
}
