<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Subcategory;
use App\Models\User;
use App\Models\Course;

use Auth;
use Illuminate\Http\Request;



class CatalogController extends Controller
{

    // -------------------------------- CATALOG SECTION ----------------------------------------

    public function catalog(Request $request, $slug=null, $slug1=null)
    {

        $cat = null;
        $subcat = null;
        $sort = $request->sort;
        $type = $request->type;
        $level = $request->level;
        $rating = $request->rating;
        $rating = $rating * 20;
        $duration = $request->durations;

        $search = $request->search;

        if (!empty($slug)) {
            $cat = Category::where('slug', $slug)->first();
            $data['cat'] = $cat;
        }
        if (!empty($slug1)) {
            $subcat = Subcategory::where('slug', $slug1)->firstOrFail();
            $data['subcat'] = $subcat;
        }

        $courses = Course::when($cat, function ($query, $cat) {
                                    return $query->where('category_id', $cat->id);
                                })
                                ->when($subcat, function ($query, $subcat) {
                                    return $query->where('subcategory_id', $subcat->id);
                                })
                                ->when($search, function ($query, $search) {
                                    return $query->whereRaw('MATCH (title) AGAINST (? IN BOOLEAN MODE)' , array($search));
                                })
                                ->when($type, function ($query, $type) {
                                    if ($type == 'free') {
                                      return $query->where('price','=',0);
                                    }
                                    elseif($type == 'paid') {
                                      return $query->where('price','!=',0);
                                    }
                                })
                                ->when($level, function ($query, $level) {
                                    if ($level== 'beginner') {
                                      return $query->where('level','=','Beginner');
                                    }
                                    elseif($level == 'intermediate') {
                                      return $query->where('level','=','Intermediate');
                                    }
                                    elseif($level == 'advanced') {
                                        return $query->where('level','=','Advanced');
                                    }
                                })
                                ->when($duration, function ($query, $duration) {
                                    if ($duration == '0-2') {

                                        return $query->join('sections','sections.course_id','=','courses.id')
                                        ->join('lessons','lessons.section_id','=','sections.id')
                                        ->select('courses.id','courses.title','courses.price','courses.user_id','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo')
                                        ->havingRaw('sum(time_to_sec(lessons.duration)) >= ?', [0])
                                        ->havingRaw('sum(time_to_sec(lessons.duration)) <= ?', [7200])
                                        ->groupBy('courses.id','courses.title','courses.price','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.user_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo');

                                    }
                                    elseif($duration == '2-6') {

                                        return $query->join('sections','sections.course_id','=','courses.id')
                                        ->join('lessons','lessons.section_id','=','sections.id')
                                        ->select('courses.id','courses.title','courses.price','courses.user_id','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo')
                                        ->havingRaw('sum(time_to_sec(lessons.duration)) >= ?', [7201])
                                        ->havingRaw('sum(time_to_sec(lessons.duration)) <= ?', [21600])
                                        ->groupBy('courses.id','courses.title','courses.price','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.user_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo');

                                    }
                                    elseif($duration == '6-12') {


                                        return $query->join('sections','sections.course_id','=','courses.id')
                                        ->join('lessons','lessons.section_id','=','sections.id')
                                        ->select('courses.id','courses.title','courses.price','courses.user_id','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo')
                                        ->havingRaw('sum(time_to_sec(lessons.duration)) >= ?', [21601])
                                        ->havingRaw('sum(time_to_sec(lessons.duration)) <= ?', [43200])
                                        ->groupBy('courses.id','courses.title','courses.price','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.user_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo');


                                    }
                                    elseif($duration == '12-18') {
                                        return $query->join('sections','sections.course_id','=','courses.id')
                                        ->join('lessons','lessons.section_id','=','sections.id')
                                        ->select('courses.id','courses.title','courses.price','courses.user_id','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo')
                                        ->havingRaw('sum(time_to_sec(lessons.duration)) >= ?', [43201])
                                        ->havingRaw('sum(time_to_sec(lessons.duration)) <= ?', [64800])
                                        ->groupBy('courses.id','courses.title','courses.price','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.user_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo');
                                    }
                                })

                                ->when($rating, function ($query, $rating) {


                                      return $query->join('ratings','ratings.course_id','=','courses.id')
                                      ->select('courses.id','courses.title','courses.price','courses.user_id','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo')
                                      ->havingRaw('SUM(ratings.rating) >= ?', [$rating])
                                      ->groupBy('courses.id','courses.title','courses.price','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.user_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo');


                                })

                                ->when($sort, function ($query, $sort) {
                                    if ($sort == 'new') {
                                      return $query->latest('id');
                                    }
                                    elseif($sort == 'old') {
                                      return $query->oldest('id');
                                    }
                                    elseif($sort=='high_price') {
                                      return $query->latest('price');
                                    }
                                    elseif($sort=='low_price') {
                                      return $query->oldest('price');
                                    }

                                    elseif($sort=='popular') {
                                        return $query->join('enrolled_courses','enrolled_courses.course_id','=','courses.id')
                                                     ->select('courses.id','courses.title','courses.price','courses.user_id','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo',\DB::raw('count(enrolled_courses.course_id) as popular'))
                                                     ->orderBy('popular','desc')
                                                     ->groupBy('courses.id','courses.title','courses.price','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.user_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo');
                                      }
                                      elseif($sort=='high_rated') {
                                        return $query->join('ratings','ratings.course_id','=','courses.id')
                                                     ->select('courses.id','courses.title','courses.price','courses.user_id','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo',\DB::raw('sum(ratings.rating) as top'))
                                                     ->orderBy('top','desc')
                                                     ->groupBy('courses.id','courses.title','courses.price','courses.status','courses.language_id','courses.category_id','courses.subcategory_id','courses.user_id','courses.is_top','courses.is_free','courses.slug','courses.discount_price','courses.short_description','courses.description','courses.level','courses.requirements','courses.outcomes','courses.course_overview_type','courses.course_overview_url','courses.photo');
                                      }

                                })
                                ->when(empty($sort), function ($query, $sort) {
                                    return $query->latest('id');
                                });


                                $courses = $courses->where('register_id',0)->where('status', 1)->paginate(9);

                                $data['courses'] = $courses;

                                if($request->ajax()) {
                                    return view('front.ajax.catalog', $data);

                                }

        return view('front.catalog', $data);
    }

    // -------------------------------- CATALOG SECTION END ----------------------------------------



    // -------------------------------- AUTOSEARCH SECTION ----------------------------------------

    public function autosearch($slug)
    {
        if(mb_strlen($slug,'UTF-8') > 1){
            $search = ' '.$slug;
            $courses = Course::where('title', 'like', '%' . $search . '%')->where('register_id',0)->whereStatus(1)->take(10)->get();
            return view('load.suggest',compact('courses','slug'));
        }
        return "";
    }


    public function youtubesearch($slug)
    {

        $gs = \App\Models\Generalsetting::find(1);
        $apikey = $gs->youtube_api_key; 
        $googleApiUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=' . $slug . '&maxResults=' . 8 . '&key=' . $apikey;
    
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $googleApiUrl);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
    
        curl_close($ch);
        $data = json_decode($response);
        $value = json_decode(json_encode($data), true);
        if(isset($value['error'])){
            return '';
        }else{
            $items = $value['items'];
            return view('load.suggest-youtube',compact('items'));
        }

    }

    // -------------------------------- AUTOSEARCH SECTION ENDS ----------------------------------------


    // -------------------------------- COURSE DETAILS SECTION ----------------------------------------

    public function course(Request $request,$slug)
    {
        $type = '';
        $affilate_user = 0;
        if(Auth::check()){
            if($request->has('ref')){
                if(!empty($request->ref)){
                    $ref = $request->ref;
                    $user = User::where('affilate_code',$ref)->first();
                    if($user){
                        if(Auth::user()->id != $user->id){
                            $affilate_user = $user->id;
                            $type = $user->is_instructor == 2 ? 'Instructor' : 'Student';
                        }
                    }
                }
            }
        }

      $course = Course::where('slug','=',$slug)->firstOrFail();
      $data['course'] = $course;
      $data['instructor'] = !empty($course->instructor) ? $course->instructor : 'admin';
      $data['admin'] = \DB::table('admins')->first();
      $data['affilate_user'] = $affilate_user;
      $data['type'] = $type;
      return view('front.course',$data);

    }

    // -------------------------------- COURSE DETAILS SECTION ENDS ----------------------------------------

    // -------------------------------- INSTRUCTOR DETAILS SECTION ----------------------------------------

    public function instructorDetails(Request $request,$slug)
    {
        $instructor = User::where('instructor_slug',$slug)->first();
        $type = 'instructor';

        if(empty($instructor)){
            $type = 'admin';
            $instructor = \DB::table('admins')->first();
            $courses = Course::where('register_id',0)->where('user_id',0)->whereStatus(1)->paginate(8);
        }else{
            $courses = $instructor->courses()->where('register_id',0)->whereStatus(1)->paginate(8);
        }

        if($request->ajax()) {
            return view('front.ajax.instructor', compact('instructor','type','courses'));

        }

        return view('front.instructor',compact('instructor','type','courses'));
    }

    // -------------------------------- INSTRUCTOR DETAILS SECTION ENDS ----------------------------------------

    // ------------------ RATING SECTION --------------------

    public function reviews($id){
        $course = Course::find($id);
        return view('load.reviews',compact('course'));
    }

    public function sideReviews($id){
        $course = Course::find($id);
        return view('load.side-load',compact('course'));
    }

    // ------------------ RATING SECTION ENDS --------------------
}
