<?php

namespace Modules\UpcomingCourse\Http\Controllers;

use App\User;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\CourseSetting\Entities\Category;
use Modules\CourseSetting\Entities\Course;
use Modules\CourseSetting\Entities\CourseLevel;
use Modules\FrontendManage\Entities\FrontPage;
use Modules\Localization\Entities\Language;
use Modules\Newsletter\Http\Controllers\AcelleController;
use Modules\Newsletter\Http\Controllers\GetResponseController;
use Modules\Newsletter\Http\Controllers\MailchimpController;
use Modules\Quiz\Entities\OnlineQuiz;
use Exception;
use Modules\UpcomingCourse\Entities\UpcomingCourseBooking;
use Modules\UpcomingCourse\Entities\UpcomingCourseFollower;
use Modules\UpcomingCourse\Jobs\PublishCourseJob;
use Yajra\DataTables\DataTables;

class UpcomingCourseController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['homeIndex']);
        $this->middleware('RoutePermissionCheck:admin.upcoming_courses.index', ['only' => ['index', 'datatable']]);
        $this->middleware('RoutePermissionCheck:admin.upcoming_courses.index', ['only' => ['index', 'datatable']]);
        $this->middleware('RoutePermissionCheck:admin.upcoming_courses.followers', ['only' => ['followers', 'followersDatatable']]);
        $this->middleware('RoutePermissionCheck:admin.upcoming_courses.pre_booking', ['only' => ['prebooking', 'prebookingDatatable']]);
        $this->middleware('RoutePermissionCheck:admin.upcoming_courses.publish', ['only' => ['publish']]);
    }

    public function publish($id)
    {
        try {
            Course::where('id', $id)->update(['publish_status' => 'published']);
            PublishCourseJob::dispatch($id);
            Toastr::success('Course Publish Successfully', 'Success');
            return redirect()->back();

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function followers($id)
    {
        try {
            $data['course'] = Course::find($id);
            $data['id'] = $id;
            return view('upcomingcourse::upcoming_courses.followers', $data);

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function followersDatatable($id, Request $request)
    {
        try {

            $data = UpcomingCourseFollower::query()
                ->with(['user'])
                ->where('course_id', $id);

            if ($request->f_date) {
                $data->whereBetween(DB::raw('DATE(created_at)'), formatDateRangeData($request->f_date));
            }

            return DataTables::of($data)
                ->addIndexColumn()
                ->editColumn('created_at', function ($row) {
                    return showDate($row->created_at);
                })
                ->addColumn('name', function ($row) {
                    return $row->user->name;
                })
                ->addColumn('email', function ($row) {
                    return $row->user->email;
                })
                ->toJson();
        } catch (\Exception $e) {
            return response()->json([
                'error' => $e->getMessage()
            ], 503);
        }
    }


    public function prebooking($id)
    {
        try {
            $data['course'] = Course::find($id);
            $data['id'] = $id;
            return view('upcomingcourse::upcoming_courses.prebookings', $data);

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function prebookingDatatable($id, Request $request)
    {
        try {

            $data = UpcomingCourseBooking::query()
                ->with(['user', 'payments'])
                ->where('course_id', $id);

            if ($request->f_date) {
                $data->whereBetween(DB::raw('DATE(created_at)'), formatDateRangeData($request->f_date));
            }

            return DataTables::of($data)
                ->addIndexColumn()
                ->editColumn('created_at', function ($row) {
                    return showDate($row->created_at);
                })
                ->addColumn('name', function ($row) {
                    return $row->user->name;
                })
                ->addColumn('email', function ($row) {
                    return $row->user->email;
                })
                ->addColumn('payments', function ($row) {
                    return showPrice($row->payments->sum('amount'));
                })
                ->toJson();
        } catch (\Exception $e) {
            return response()->json([
                'error' => $e->getMessage()
            ], 503);
        }
    }


    public function following($id)
    {
        try {
            UpcomingCourseFollower::create([
                'user_id' => \auth()->user()->id,
                'course_id' => $id,
            ]);
            Toastr::success('Course Following Successfully', 'Success');
            return redirect()->back();

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }


    public function unfollow($id)
    {
        try {
            $following = UpcomingCourseFollower::where('course_id', $id)->where('user_id', auth()->user()->id)->first();
            if ($following) {
                $following->delete();
            }
            Toastr::success('Course Unfollow Successfully', 'Success');
            return redirect()->back();

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function homeIndex(Request $request)
    {
        try {
            $row = FrontPage::where('slug', '/upcoming-courses')->first();
            $details = dynamicContentAppend($row->details);
            return view('aorapagebuilder::pages.show', compact('row', 'details'));

        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function index()
    {
        try {
            $user = Auth::user();

            $video_list = [];
            $vdocipher_list = [];

            $courses = [];
            $query = Category::where('status', 1)->orderBy('position_order', 'ASC');
            if (isModuleActive('OrgInstructorPolicy') && \auth()->user()->role_id != 1) {
                $assign = OrgPolicyCategory::where('policy_id', \auth()->user()->policy_id)->pluck('category_id')->toArray();
                $query->whereIn('id', $assign);
            }
            $categories = $query->with('parent')->get();
            if ($user->role_id == 2) {
                $quizzes = OnlineQuiz::where('created_by', $user->id)->latest()->get();
            } else {
                $quizzes = OnlineQuiz::latest()->get();
            }

            $instructor_query = User::select('name', 'id');
            if (isModuleActive('UserType')) {
                $instructor_query->whereHas('userRoles', function ($q) {
                    $q->whereIn('role_id', [1, 2]);
                });
            } else {
                $instructor_query->whereIn('role_id', [1, 2]);
            }
            $instructors = $instructor_query->get();
            $languages = Language::select('id', 'native', 'code')
                ->where('status', '=', 1)
                ->get();
            $levels = CourseLevel::where('status', 1)->get();
            $title = trans('courses.All');

            $sub_lists = $this->getSubscriptionList();

            return view('upcomingcourse::upcoming_courses.index', compact('sub_lists', 'levels', 'video_list', 'vdocipher_list', 'title', 'quizzes', 'courses', 'categories', 'languages', 'instructors'));
        } catch (Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());

        }
    }

    public function getSubscriptionList()
    {
        $list = [];

        try {
            $user = Auth::user();
            if ($user->subscription_method == "Mailchimp" && $user->subscription_api_status == 1) {
                $mailchimp = new MailchimpController();
                $mailchimp->mailchimp($user->subscription_api_key);
                $getlists = $mailchimp->mailchimpLists();
                foreach ($getlists as $key => $l) {
                    $list[$key]['name'] = $l['name'];
                    $list[$key]['id'] = $l['id'];
                }

            } elseif ($user->subscription_method == "GetResponse" && $user->subscription_api_status == 1) {
                $getResponse = new GetResponseController();
                $getResponse->getResponseApi($user->subscription_api_key);
                $getlists = $getResponse->getResponseLists();
                foreach ($getlists as $key => $l) {
                    $list[$key]['name'] = $l->name;
                    $list[$key]['id'] = $l->campaignId;
                }
            } elseif ($user->subscription_method == "Acelle" && $user->subscription_api_status == 1) {
                $acelleController = new AcelleController();

                $acelleController->getAcelleApiResponse();
                $getlists = $acelleController->getAcelleList();
                foreach ($getlists as $key => $l) {
                    $list[$key]['name'] = $l['name'];
                    $list[$key]['id'] = $l['uid'];


                }
            }
        } catch (\Exception $exception) {

        }
        return $list;

    }

    public function datatable(Request $request)
    {

        $query = Course::where('is_upcoming_course', 1)->whereIn('type', [1, 2])->with('category', 'quiz', 'user');
        if ($request->course_status != "") {
            if ($request->course_status == 1) {
                $query->where('courses.status', 1);
            } elseif ($request->course_status == 0) {
                $query->where('courses.status', 0);
            }
        }
        if ($request->publish_status) {
            $query->where('publish_status', $request->publish_status);
        }

        if ($request->f_date) {
            $query->whereBetween(DB::raw('DATE(publish_date)'), formatDateRangeData($request->f_date));
        }

        if ($request->category != "") {
            $query->where('category_id', $request->category);
        }
        if ($request->type != "") {
            $query->where('type', $request->type);
        }
        if ($request->instructor != "") {
            $query->where('user_id', $request->instructor);
        }
        if ($request->search_status != "") {
            $query->where('courses.status', $request->search_status);
        }
        if ($request->required_type != "") {
            $query->where('required_type', $request->required_type);
        }
        if ($request->mode_of_delivery != "") {
            $query->where('mode_of_delivery', $request->mode_of_delivery);
        }

        if (isInstructor()) {
            $query->where('user_id', '=', Auth::id());
            $query->orWhere('assistant_instructors', 'like', '%"{' . Auth::id() . '}"%');
        }
        if (isModuleActive('OrgInstructorPolicy') && \auth()->user()->role_id != 1) {
            $assigns = Auth::user()->policy->course_assigns;
            $ids = [];
            foreach ($assigns as $assign) {
                $ids[] = $assign->course_id;
            }
            $query->orWhereIn('id', $ids);
        }

        if (isModuleActive('Organization') && Auth::user()->isOrganization()) {
            $query->whereHas('user', function ($q) {
                $q->where('organization_id', Auth::id());
                $q->orWhere('id', Auth::id());
            });
        }

        if (isModuleActive('AdvanceQuiz')) {
            $query->where('advance_test', 0);
        }

        $query->select('courses.*');

        return Datatables::of($query)
            ->addIndexColumn()
            ->editColumn('title', function ($query) {
                return $query->title;
            })
            ->editColumn('publish_date', function ($query) {
                return showDate($query->publish_date);
            })
            ->editColumn('is_allow_prebooking', function ($query) {
                return $query->is_allow_prebooking ? 'Yes' : "No";
            })
            ->editColumn('booking_amount', function ($query) {
                if ($query->is_allow_prebooking) {
                    return showPrice($query->booking_amount);
                }
                return '';
            })
            ->editColumn('required_type', function ($query) {
                return $query->required_type == 1 ? trans('courses.Compulsory') : trans('courses.Open');
            })->editColumn('mode_of_delivery', function ($query) {
                if ($query->mode_of_delivery == 1) {
                    $title = trans('courses.Online');

                } elseif ($query->mode_of_delivery == 2) {
                    $title = trans('courses.Distance Learning');
                } else {
                    if (isModuleActive('Org')) {
                        $title = trans('courses.Offline');
                    } else {
                        $title = trans('courses.Face-to-Face');
                    }
                }
                return $title;
            })
            ->addColumn('type', function ($query) {
                return $query->type == 1 ? trans('courses.Course') : trans('quiz.Quiz');

            })->addColumn('status', function ($query) {
                return view('coursesetting::components._course_status_td', ['query' => $query]);
            })->addColumn('lessons', function ($query) {
                return $query->lessons->count();
            })
            ->editColumn('category', function ($query) {
                if ($query->category) {
                    return $query->category->name;
                } else {
                    return '';
                }

            })
            ->editColumn('quiz', function ($query) {
                if ($query->quiz) {
                    return $query->quiz->title;
                } else {
                    return '';
                }

            })->editColumn('user', function ($query) {
                if ($query->user) {
                    return $query->user->name;
                } else {
                    return '';
                }

            })->addColumn('enrolled_users', function ($query) {
                return $query->enrollUsers->where('teach_via', 1)->count() . "/" . $query->enrollUsers->where('teach_via', 2)->count();
            })
            ->editColumn('scope', function ($query) {
                if ($query->scope == 1) {
                    $scope = trans('courses.Public');
                } else {
                    $scope = trans('courses.Private');
                }
                return $scope;

            })->addColumn('price', function ($query) {
                return view('coursesetting::components._course_price_td', ['query' => $query]);
            })->addColumn('action', function ($query) {
                return view('coursesetting::components._course_action_td', ['query' => $query]);
            })->rawColumns(['status', 'price', 'action', 'enrolled_users'])
            ->make(true);
    }


}
