<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Course;
use App\Models\Destination;
use App\Models\Level;
use App\Models\Institute;

use App\Traits\CourseSearch;

use Auth;
use Mail;
use Session;
use DB;
use Response;

class CourseController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('admin');
        $this->api_base_url = apiUrl();
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $loggedin = Auth::guard('admin')->user();
        $institutes = Institute::orderBy('name', 'ASC')->get();
        return view('admin.courses.list',compact('institutes'));
    }

    public function load(Request $request)
    {   
        $loggedin = Auth::guard('admin')->user();
        $search_text = $request->search;

        $qry = model('Course')::whereNotNull('destination_id');

        if($request->institute != 0){
            $qry = (clone $qry)->where('institute_id', $request->institute)->orderBy('name');
        }

        if($search_text){
            $qry = (clone $qry)->where('name', 'like', '%' . $search_text . '%');
        }

        $courses = $qry->orderBy('name', 'ASC')->paginate(40);
        return view('admin.courses.load',compact('courses'));
    }

    public function create()
    {
        $loggedin = Auth::guard('admin')->user();
        $destinations = $this->get_destinations();
        return view('admin.courses.add',compact('destinations'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $loggedin = Auth::guard('admin')->user();
        $this->validate($request,[
            'courseName' => 'required',
            'destination_id' => 'required',
            'institute_id' => 'required',
            'level_id' => 'required',
            'department' => 'required',
            'tutionFee' => 'required'
        ]);

        //dd($request);

        DB::beginTransaction();
        try {
            $course = new \App\Models\Course;
            $course->destination_id = $this->getModelId('Destination', $request->destination_id);
            $course->institute_id = $this->getInstituteId($request->institute_id, $course->destination_id);
            $course->level_id = $this->getModelId('Level', $request->level_id);
            $course->department = $request->department;
            $course->name = $request->courseName;
            $course->length = $request->courseLength;
            $course->tution_fee = $request->tutionFee;
            $course->ielts = $request->ielts;
            $course->toefl = $request->toefl;
            $course->pte = $request->pte;
            $course->duolingo = $request->duolingo;
            $course->scholarship = $request->scholarship;
            $course->deposit_required = $request->depositRequired;
            //$course->ucas_fee = $request->ucasFee;
            //$course->min_gpa = $request->minGpa;
            $course->sop = $request->sop;
            $course->cv = $request->cv;
            $course->reference = $request->reference;
            $course->entry_requirement = $request->entry_requirement;
            $course->save();

            if($request->campuses){
                foreach($request->campuses as $campus){
                    $courseCampus = new \App\Models\CourseCampus;
                    $courseCampus->campus_id = $this->getCampusId($course->institute_id, $campus);
                    $courseCampus->course_id = $course->id;
                    $courseCampus->save();
                }
            }

            if($request->intakes){
                foreach($request->intakes as $intake){
                    $courseCampus = new \App\Models\CourseIntake;
                    $courseCampus->intake = $intake;
                    $courseCampus->course_id = $course->id;
                    $courseCampus->save();
                }
            }

            if($request->tags){
                $tags = explode(',', $request->tags);
                foreach($tags as $tag){
                    $tagRow = new \App\Models\CourseTag;
                    $tagRow->keyword = $tag;
                    $tagRow->course_id = $course->id;
                    $tagRow->save();
                }
            }

            DB::commit();
            
            return redirect()->action('Admin\CourseController@index')->with('success','Successfully Created!');
        } catch (\Exception $e) { 
            dd($e);
            DB::rollBack();
            return redirect()->action('Admin\CourseController@index')->with('error', "Something Wrong!");
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $loggedin = Auth::guard('admin')->user();

        $course = Course::find($id);
        $selected = model('CourseCampus')::where('course_id', $course->id)->pluck('campus_id')->toArray();
        $selected_campuses = model('Campus')::whereIn('id', $selected)->get();
        return view('admin.courses.view',compact('course','selected_campuses'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $loggedin = Auth::guard('admin')->user();

        $course = Course::find($id);
        $destinations = $this->get_destinations();
        $institutes = $this->get_institutes($course->destination->sams_id);
        $campuses = $this->get_campuses($course->institute->sams_id);
        $levels = $this->get_levels($course->institute->sams_id,0);
        $intakes = $this->get_intakes($course->institute->sams_id,$course->level->sams_id);

        //dd($intakes);
        $selected = model('CourseCampus')::where('course_id', $course->id)->pluck('campus_id')->toArray();
        $selected_campuses = model('Campus')::whereIn('id', $selected)->pluck('sams_id')->toArray();
        $selected_intakes = model('CourseIntake')::where('course_id', $course->id)->pluck('intake')->toArray();
        $selected_tags = model('CourseTag')::where('course_id', $course->id)->pluck('keyword')->toArray();
        return view('admin.courses.edit',compact('course','destinations','institutes','campuses','levels','intakes','selected_campuses','selected_intakes','selected_tags'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $loggedin = Auth::guard('admin')->user();
        $this->validate($request,[
            'courseName' => 'required',
            'destination_id' => 'required',
            'institute_id' => 'required',
            'level_id' => 'required',
            'department' => 'required',
            'tutionFee' => 'required'
        ]);

        //dd($request);

        DB::beginTransaction();
        try {
            $course = model('Course')::find($request->id);
            $course->destination_id = $this->getModelId('Destination', $request->destination_id);
            $course->institute_id = $this->getInstituteId($request->institute_id, $course->destination_id);
            $course->level_id = $this->getModelId('Level', $request->level_id);
            $course->department = $request->department;
            $course->name = $request->courseName;
            $course->length = $request->courseLength;
            $course->tution_fee = $request->tutionFee;
            $course->ielts = $request->ielts;
            $course->toefl = $request->toefl;
            $course->pte = $request->pte;
            $course->duolingo = $request->duolingo;
            $course->scholarship = $request->scholarship;
            $course->deposit_required = $request->depositRequired;
            //$course->ucas_fee = $request->ucasFee;
            //$course->min_gpa = $request->minGpa;
            $course->sop = $request->sop;
            $course->cv = $request->cv;
            $course->reference = $request->reference;
            $course->entry_requirement = $request->entry_requirement;
            $course->update();

            if($request->campuses){
                model('CourseCampus')::where('course_id', $course->id)->delete();
                foreach($request->campuses as $campus){
                    $courseCampus = new \App\Models\CourseCampus;
                    $courseCampus->campus_id = $this->getCampusId($course->institute_id, $campus);
                    $courseCampus->course_id = $course->id;
                    $courseCampus->save();
                }
            }

            if($request->intakes){
                model('CourseIntake')::where('course_id', $course->id)->delete();
                foreach($request->intakes as $intake){
                    $courseCampus = new \App\Models\CourseIntake;
                    $courseCampus->intake = $intake;
                    $courseCampus->course_id = $course->id;
                    $courseCampus->save();
                }
            }

            if($request->tags){
                model('CourseTag')::where('course_id', $course->id)->delete();
                $tags = explode(',', $request->tags);
                foreach($tags as $tag){
                    $tagRow = new \App\Models\CourseTag;
                    $tagRow->keyword = $tag;
                    $tagRow->course_id = $course->id;
                    $tagRow->save();
                }
            }

            DB::commit();
            return redirect()->action('Admin\CourseController@index')->with('success','Successfully Updated!');
        }catch (\Exception $e) {
            dd($e);
            DB::rollBack();
            return redirect()->action('Admin\CourseController@index')->with('error', "Something Wrong!");
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $loggedin = Auth::guard('admin')->user();
        $course = Course::find($id);

        DB::beginTransaction();
        try {
            model('CourseCampus')::where('course_id', $course->id)->delete();
            model('CourseIntake')::where('course_id', $course->id)->delete();
            model('CourseTag')::where('course_id', $course->id)->delete();
            Course::whereId($id)->delete();

            DB::commit();
            return redirect()->action('Admin\CourseController@index')->with('success','Successfully Deleted!');
        }catch (\Exception $e) { 
            DB::rollBack();
            return redirect()->action('Admin\CourseController@index')->with('error', "Something Wrong!");
        }
    }

    public function bulkEntry()
    {
        $loggedin = Auth::guard('admin')->user();
        return view('admin.courses.bulk');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storeExcel(Request $request)
    {
        $loggedin = Auth::guard('admin')->user();
        $this->validate($request,[
            'file' => 'required'
        ]);

        DB::beginTransaction();
        try {
            $importedList = [];
            if($request->hasFile('file')){
                $course_import = new \App\Imports\CourseImport();
                $file = $request->file('file');
                $course_import->import($file);
                $importedList = $course_import->getImportedRows();
            }
            if(count($importedList)){
                foreach ($importedList as $key => $value) {
                    if(!empty($value['name'])){
                        $instituteInfo = $this->get_institute_and_destination(trim($value['institute']));
                        $levelInfo = $this->get_level_by_name(trim($value['level']));
                        $arr[] = $value;
                        $course = new \App\Models\Course;
                        $course->destination_id = $instituteInfo['destination_id'];
                        $course->institute_id = $instituteInfo['institute_id'];
                        $course->level_id = $levelInfo;
                        $course->department = trim($value['department']);
                        $course->name = trim($value['name']);
                        $course->length = trim($value['length']);
                        $course->tution_fee = trim($value['tuitionfee']);
                        $course->ielts = $value['ielts']?trim($value['ielts']):null;
                        $course->toefl = $value['toefl']?trim($value['toefl']):null;
                        $course->pte = $value['pte']?trim($value['pte']):null;
                        $course->duolingo = $value['duolingo']?trim($value['duolingo']):null;
                        $course->scholarship = trim($value['scholarship']);
                        $course->deposit_required = $value['depositrequired'];
                        $course->sop = trim($value['sop'])=='Yes'?'1':'0';
                        $course->cv = trim($value['cv'])=='Yes'?'1':'0';
                        $course->reference = trim($value['reference']);
                        $course->entry_requirement = $value['entryrequirement'];
                        $course->save();

                        if($value['campuses']){
                            $campuses = explode(',', $value['campuses']);
                            foreach($campuses as $campus){
                                $courseCampus = new \App\Models\CourseCampus;
                                $courseCampus->campus_id = $this->get_campus_by_name(trim($campus), $course->institute_id);
                                $courseCampus->course_id = $course->id;
                                $courseCampus->save();
                            }
                        }
            
                        if($value['intakes']){
                            $intakes = explode(',', $value['intakes']);
                            $monthList = [
                                'Jan' => 1,
                                'Feb' => 2,
                                'Mar' => 3,
                                'Apr' => 4,
                                'May' => 5,
                                'Jun' => 6,
                                'Jul' => 7,
                                'Aug' => 8,
                                'Sept' => 9,
                                'Sep' => 9,
                                'Oct' => 10,
                                'Nov' => 11,
                                'Dec' => 12,
                            ];

                            foreach($intakes as $intake){
                                $dt = new \App\Models\CourseIntake;
                                $dt->intake = $monthList[trim($intake)];
                                $dt->course_id = $course->id;
                                $dt->save();
                            }
                        }
            
                        if($value['tags']){
                            $tags = explode(',', $value['tags']);
                            foreach($tags as $tag){
                                $tagRow = new \App\Models\CourseTag;
                                $tagRow->keyword = trim($tag);
                                $tagRow->course_id = $course->id;
                                $tagRow->save();
                            }
                        }
                    }
                }
            }
            
            DB::commit();
            
            return redirect()->action('Admin\CourseController@index')->with('success','Successfully Uploaded!');
        } catch (\Exception $e) { 
            dd($e);
            DB::rollBack();
            return redirect()->action('Admin\CourseController@index')->with('error', "Something Wrong!");
        }
    }

    public function downloadBulkTemplate()
    {
        $file = public_path(). "/templates/courses_bulk_upload_template.xlsx";
        if (file_exists($file)) {
            return Response::download($file);
        } else {
            echo('File not found.');
        }
    }

    public function get_institute_and_destination($instituteName){
        $data = [];
        $check = findRowByColumn('Institute','name', $instituteName);
        if($check){
            $data = ['institute_id' => $check->id, 'destination_id' => $check->destination_id];
        }else{
            $getData = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-institute-by-name?name='.$instituteName);
            if($getData){
                $destination_id = $this->getModelId('Destination', $getData['destination'].'::'.$getData['destinationName']);
                $data = ['institute_id' => $this->getInstituteId($getData['id'].'::'.$getData['name'], $destination_id), 'destination_id' => $destination_id];
            }
        }  
        return $data; 
    }

    public function get_level_by_name($name){
        $data = [];
        $check = findRowByColumn('Level','name', $name);
        if($check){
            return $check->id;
        }else{
            $getData = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-level-by-name?name='.$name);
            if($getData){
                return $this->getModelId('Level', $getData['id'].'::'.$getData['name']);
            }
        }  

        return $data; 
    }

    public function get_campus_by_name($name, $institute){
        $data = [];
        $check = model('Campus')::where('name', $name)->where('institute_id', $institute)->first();
        if($check){
            return $check->id;
        }else{
            $sams_id = model('Institute')::find($institute)->sams_id;
            $getData = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-campus-by-name?name='.$name.'&institute='.$sams_id);
            if($getData){
                return $this->getCampusId($institute, $getData['id'].'::'.$getData['campus_name']);
            }
        }  

        return $data; 
    }

    public function get_destinations(){
        $data = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-destinations');
        return $data;
    }

    public function get_institutes($destination){
        $data = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-institutes?destination='.$destination.'&type=all');
        return $data;
    }

    public function get_campuses($institute){
        $data = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-campuses?institute='.$institute);
        return $data;
    }

    public function get_levels($institute, $group){
        $data = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-levels?institute='.$institute.'&group='.$group);
        return $data;
    }

    public function get_intakes($institute, $level){
        $data = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-intakes?institute='.$institute.'&level='.$level);
        return $data;
    }

    public function getCountry($id){
        $data = getApiRequest($this->api_base_url.'api/sams-institutes/v1/get-country?id='.$id);
        return $data;
    }

    public function getInstituteId($input, $destination) //create or find row by sams Id
    {
        $arr = explode('::', $input);
        $id = $arr[0];
        $name = $arr[1];

        $check = findRowByColumn('Institute','sams_id', $id);
        if($check){
            return $check->id;
        }else{
            
            $row = new \App\Models\Institute;   
            $row->sams_id = $id;
            $row->destination_id = $destination;
            $row->name = $name;
            $row->save();

            return $row->id;
        }
    }

    public function getModelId($model, $input) //create or find row by sams Id
    {
        $arr = explode('::', $input);
        $id = $arr[0];
        $name = $arr[1];

        $check = findRowByColumn($model,'sams_id', $id);

        if($check){
            return $check->id;
        }else{
            if($model == 'Destination'){
                $row = new \App\Models\Destination;
                $country = $this->getCountry($id);
                if($country){
                    $row->short_code = $country['short_code'];
                    $row->currency = $country['currency_symbol'];
                }
            }elseif($model == 'Level'){
                $row = new \App\Models\Level;
            }    
            $row->sams_id = $id;
            $row->name = $name;
            $row->save();

            return $row->id;
        }
    }

    public function getCampusId($institute, $input) //create or find row by sams Id
    {
        $arr = explode('::', $input);
        $id = $arr[0];
        $name = $arr[1];

        $check = findRowByColumn('Campus','sams_id', $id);

        if($check){
            return $check->id;
        }else{
            
            $row = new \App\Models\Campus;   
            $row->sams_id = $id;
            $row->institute_id = $institute;
            $row->name = $name;
            $row->save();

            return $row->id;
        }
    }

    public function edit_entry_req($institute_id, $course_id)
    {
        $loggedin = Auth::guard('admin')->user();
        $serial = 1;
        if($course_id != 0){
            $course = Course::find($course_id);
            $serial = Course::where('institute_id',$institute_id)->where('id', '<=', $course_id)->count();
        }else{
            $course = Course::where('institute_id',$institute_id)->first();
        }
        $total_courses = Course::where('institute_id',$institute_id)->count();
        $selected_tags = model('CourseTag')::where('course_id', $course->id)->pluck('keyword')->toArray();
        return view('admin.courses.edit_entry_req',compact('course','selected_tags','serial','total_courses'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update_entry_req(Request $request, $id)
    {
        $loggedin = Auth::guard('admin')->user();

        DB::beginTransaction();
        try {
            $course = model('Course')::find($request->id);
            $course->entry_requirement = $request->entry_requirement;
            $course->update();

            if($request->tags){
                model('CourseTag')::where('course_id', $course->id)->delete();
                $tags = explode(',', $request->tags);
                foreach($tags as $tag){
                    $tagRow = new \App\Models\CourseTag;
                    $tagRow->keyword = $tag;
                    $tagRow->course_id = $course->id;
                    $tagRow->save();
                }
            }

            DB::commit();
            $next_course = model('Course')::where('id','>',$request->id)->first();
            if($next_course){
                return redirect()->action('Admin\CourseController@edit_entry_req',['institute'=>$course->institute_id,'course'=>$next_course->id])->with('success','Successfully Updated! Redirected to Next Course.');
            }else{
                return redirect()->action('Admin\ListController@institutes')->with('success','All Done!');
            }
        }catch (\Exception $e) {
            DB::rollBack();
            return redirect()->action('Admin\CourseController@index')->with('error', "Something Wrong!");
        }
    }
}
