<?php

namespace App\Http\Controllers\Student;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Models\Rating;
use Illuminate\Support\Facades\Hash;
use App\Models\Admin;
use App\Models\Generalsetting;
use App\Models\User;
use App\Models\Course;
use App\Models\EnrolledCourse;
use App\Models\Referral;
use App\Models\ReferralHistory;
use Validator;



class StudentController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

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

        $certify = EnrolledCourse::whereUserId($user->id)->whereCertificate(1)->pluck('course_id');
        $courses = EnrolledCourse::whereUserId($user->id)->pluck('course_id');
        $enrolled_courses = Course::where('register_id',0)->where('status','=',1)->whereIn('id',$courses)->latest('id')->paginate(8);
        if($request->ajax())
        {
            return view('front.ajax.enrolled_courses',compact('user','enrolled_courses','certify'));
        }

        return view('student.dashboard',compact('user','enrolled_courses','certify'));
    }

    public function profile()
    {
        $student = Auth::user();
        return view('student.profile',compact('student'));
    }

    public function account()
    {
        $student = Auth::user();
        return view('student.account',compact('student'));
    }


 public function accountUpdate(Request $request)
    {
        $user = Auth::user();

        if ($request->cpass){
            if (Hash::check($request->cpass, $user->password)){
                if ($request->newpass == $request->renewpass){
                    $input['password'] = Hash::make($request->newpass);
                }else{
		return back()->with('error',__('Confirm password does not match.'));
                }
            }else{
		return back()->with('error',__('Current password Does not match.'));
            }
        }
        $user->update($input);
        $msg = __('Successfully change your password');
        return back()->with('success',$msg);
    }



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

    public function reviewsubmit(Request $request)
    {

            $user = Auth::user();
            $course = Course::find($request->course_id);

            $sameCourseAssign =  EnrolledCourse::where('course_id',$request->course_id)->where('user_id',$user->id)->count();
  
            if($sameCourseAssign == 0){
              $data['error'] = __('You are not enrolled to this course!');
              return redirect()->route('student-dashboard')->with('error',$data['error']);

              if($request->ajax())
              {
                  return response()->json($data);
              }
              else{
                  return redirect()->route('front.course',$course->slug)->with('success',$data);
              }

            }


            $prev_reviewer = Rating::where('course_id','=',$request->course_id)->where('user_id','=',$user->id)->first();
            if(isset($prev_reviewer))
            {

                $input = $request->all();
                $input['review_date'] = date('Y-m-d H:i:s');
                $prev_reviewer->update($input);
                $data = __('Your Rating Submitted Successfully.');
                if($request->ajax())
                {
                    return response()->json($data);
                }
                else{
                    return redirect()->route('front.course',$course->slug)->with('success',$data);
                }

            }

            $Rating = new Rating;
            $Rating->fill($request->all());
            $Rating['review_date'] = date('Y-m-d H:i:s');
            $Rating['user_id'] = $user->id;
            $Rating->save();
            $data = __('Your Rating Submitted Successfully.');

            if($request->ajax())
            {
                return response()->json($data);
            }
            else{
                return redirect()->route('front.course',$course->slug)->with('success',$data);
            }

            return response()->json($data);

    }

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


    public function profileupdate(Request $request)
    {
        $data = Auth::user();

        if(User::where('email',$request->email)->where('id','!=',$data->id)->where('register_id',0)->exists()){
            return response()->json(array('errors' => [0 =>'This email has already been taken.']));
        }
        //--- Validation Section

        $rules =
        [
            'photo' => 'mimes:jpeg,jpg,png,svg',
        ];


        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
          return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
        }
        //--- Validation Section Ends
        $input = $request->all();

        

            if ($file = $request->file('photo'))
            {
                $name = time().str_replace(' ', '', $file->getClientOriginalName());
                $file->move('assets/images/users/',$name);
                if($data->photo != null)
                {
                    if (file_exists(public_path().'/assets/images/users/'.$data->photo)) {
                        unlink(public_path().'/assets/images/users/'.$data->photo);
                    }
                }
            $input['photo'] = $name;
            }
        $data->update($input);

        return response()->json(__('Successfully updated your profile.'));


    }

 public function resetform()
    {
        return view('student.reset');
    }


    public function profileImage()
    {
        $student = Auth::user();
        return view('student.photo',compact('student'));
    }


    public function application()
    {
        $user = Auth::user();
        if($user->is_instructor == 2){
            return redirect()->route('instructor-dashboard');
        }
        return view('instructor.application',compact('user'));
    }

    public function applicationSubmit(Request $request)
    {
        $user = Auth::user();


        $rules = [
            'instructor_name'      => 'required|unique:users',
            'address'      => 'required',
            'phone'      => 'required',
            'document'       => 'mimes:doc,docs,pdf,txt,png,jpg,jpeg',
             ];

             $validator = Validator::make($request->all(), $rules);
             if ($validator->fails()) {
               return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
             }

             $input = $request->all();
             $input['email'] = $user->email;
             if($request->file('document')){
                $file = $request->document;
                $name = time().str_replace(' ', '', $file->getClientOriginalName());
                $file->move('assets/application/',$name);
                $input['document'] = $name;
             }

             $input['is_instructor'] = 1;
             $input['instructor_slug'] = str_replace(" ","-",$input['instructor_name']);

             $data = Auth::user();
             $data->update($input);



             $mgs = __('Application submit successfully');
             return response()->json($mgs);

    }

    //*** GET Request Status
    public function certificate_show($id)
    {
      $user = Auth::user();
      $gs = Generalsetting::find(1);
      $data = EnrolledCourse::whereUserId($user->id)->whereCourseId($id)->first();
      $admin = Admin::first()->name;

      $student = $data->user->showName();
      $course = $data->course->title;
      $body = preg_replace("/{student_name}/", $student  ,$gs->cert_text);
      $body = preg_replace("/{admin_name}/", $admin ,$body);
      $body = preg_replace("/{course_title}/", $course  ,$body);
      $body = preg_replace("/{website_title}/", $gs->title ,$body);

      //--- Redirect Section

      return view('instructor.enrollment.certificate',compact('body','student','course','data'));
      //--- Redirect Section Ends

    }


    public function affilate()
    {
        $student = Auth::user();
        $refer = null;
        if($student->referral_id != 0){
            $refer = Referral::find($student->referral_id);
        }

        $refers = Referral::whereRegisterId(0)->whereType('Student')->orderBy('id')->get();
        return view('student.affilate.index',compact('refers','refer','student'));
    }

    public function affilate_history()
    {
        $student = Auth::user();
        $refers = ReferralHistory::whereRegisterId(0)->where('referrer_id',$student->id)->orderBy('id')->get();
        return view('student.affilate.history',compact('student','refers'));
    }


    public function assignCourse(Request $request){

      $student = Auth::user();
      $sameCourseAssign =  EnrolledCourse::where('course_id',$request->course_id)->where('user_id',$student->id)->count();
  
      if($sameCourseAssign > 0){
        $data['error'] = __('Course Enrolled Already!');
        return redirect()->route('student-dashboard')->with('error',$data['error']);
      }

      $input = $request->all();
      $data = new EnrolledCourse();
      $input['user_id'] = $student->id;
      $data->fill($input)->save();
  
      //--- Redirect Section

      $msg = __('Course Enrolled Successfully.');
      return redirect()->route('student-dashboard')->with('success',$msg);

      //--- Redirect Section Ends
  
    }


}
