<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\EnrolledCourse;
use Illuminate\Http\Request;
use App\Models\User;
use Datatables;
use Validator;

class StudentController extends Controller
{
  public function index()
  {
      return view('admin.student.index');
  }

  //*** JSON Request
  public function datatables()
  {
       $datas = User::where('register_id',0)->whereIsInstructor(0)->orderBy('id','desc')->get();
       //--- Integrating This Collection Into Datatables
       return Datatables::of($datas)

                          ->addColumn('name', function(User $data) {
                              $name = $data->first_name .' ' . $data->last_name;
                              return $name;
                          })
                          ->editColumn('photo', function(User $data) {
                              $img = '<img src="'.asset('assets/images/users/'.$data->photo).'" width="80" alt="student">';
                              return $img;
                          })

                          ->addColumn('status', function(User $data) {
                              $status      = $data->status == 1 ? __('Activated') : __('Deactivated');
                              $status_sign = $data->status == 1 ? 'success'   : 'danger';

                              return '<div class="btn-group mb-1">
                              <button type="button" class="btn btn-'.$status_sign.' btn-sm btn-rounded dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                '.$status .'
                              </button>
                              <div class="dropdown-menu" x-placement="bottom-start">
                                <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('admin-student-status',['id1' => $data->id, 'id2' => 1]).'">'.__("Activate").'</a>
                                <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('admin-student-status',['id1' => $data->id, 'id2' => 0]).'">'.__("Deactivate").'</a>
                              </div>
                            </div>';
                          })
                          ->addColumn('action', function(User $data) {
                              return '<div class="actions-btn">
                            <div class="dropdown">
                            <a class="btn btn-primary btn-sm btn-rounded dropdown-toggle" href="#" role="button" id="dropdownMenuLink"
                              data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> '.__("Options").' </a>
                            <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                              <a href="' . route('admin-student-assign-modal') . '" class="dropdown-item options assignCourse" data-id="'.$data->id.'" data-toggle="modal" data-target="#courseAssignModal">
                                <i class="fa fa-tasks"></i> '.__("Assign Course").'
                              </a>
                              <a href="' . route('admin-student-edit',$data->id) . '" class="dropdown-item options">
                              <i class="fas fa-edit"></i> '.__("Edit").'
                            </a>
                            <button type="button" data-toggle="modal" data-target="#deleteModal"  data-href="' . route('admin-student-delete',$data->id) . '" class="dropdown-item options">
                              <i class="fas fa-trash"></i> '.__("Delete").'
                            </button>

                            </div>
                          </div>
                              </div>';
                          })
                          ->rawColumns(['status','action','name','photo'])
                          ->toJson(); //--- Returning Json Data To Client Side
                    }



    public function create()
    {
        return view('admin.student.create');
    }


    public function store(Request $request)
    {
         //--- Validation Section

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


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

        $customs = [
            'photo.mimes' => __('Thumbnail Type is Invalid.'),
            ];
        $validator = Validator::make($request->all(), $rules, $customs);

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

        // logic section //
        $data = new User;
        $input = $request->all();
        $input['password'] = bcrypt($request['password']);
        if ($file = $request->file('photo'))
        {
           $name = time().str_replace(' ', '', $file->getClientOriginalName());
           $file->move('assets/images/users',$name);
           $input['photo'] = $name;
       }


       $input['affilate_code'] = md5($request->first_name.$request->last_name.$request->email);
       $data->create($input);
       $mgs = __('Data Added Successfully.').' '.'<a href="'.route('admin-student-index').'">'.__('View Lists.').'</a>';
       return response()->json($mgs);
    }

    public function edit($id)
    {
      $data = User::findOrFail($id);
      return view('admin.student.edit',compact('data'));
    }

    public function update(Request $request , $id)
    {
       //--- Validation Section

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


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

    $customs = [
        'photo.mimes' => __('Thumbnail Type is Invalid.'),
        ];
    $validator = Validator::make($request->all(), $rules, $customs);

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

    // logic section //

    $input = $request->all();
    $data = User::findOrFail($id);

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

   if(!empty($request->password)){
    $input['password'] = bcrypt($request['password']);
    }else {
        $input['password'] = $data->password;
    }

   $data->update($input);
   $mgs = __('Data Updated Successfully.').' '.'<a href="'.route('admin-student-index').'">'.__('View Lists.').'</a>';
   return response()->json($mgs);

  }

  //*** GET Request Status
  public function status($id1,$id2)
  {
    $data = User::findOrFail($id1);
    $data->status = $id2;
    $data->update();

    //--- Redirect Section
    $msg = __('Status Updated Successfully.');
    return response()->json($msg);
    //--- Redirect Section Ends

  }

  public function assignCourse(Request $request){

      //--- Validation Section
      $rules = [
        'course_id' => 'required',
        'user_id' => 'required'
        ];


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

    if ($validator->fails()) {
      return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
    }
    //--- Validation Section Ends
    $sameCourseAssign =  EnrolledCourse::where('course_id',$request->course_id)->where('user_id',$request->user_id)->count();

    if($sameCourseAssign>0){
      $msg = [];
      $msg[0] = 'Already Course Assign!';
      return response()->json(array('errors' => $msg));
    }

    $input = $request->all();
    $data = new EnrolledCourse();
    $data->fill($input)->save();

    //--- Redirect Section
    $msg = __('Course Assigned Successfully.');
    return response()->json($msg);
    //--- Redirect Section Ends

  }

  public function destroy($id)
  {
    $data = User::findOrFail($id);

    $courses = $data->courses;
    
    if($courses->count()>0){
      foreach($data->courses as $course){

        if($course->ratings->count()>0){
            foreach($course->ratings as $rating){
                $rating->delete();
            }
        }

        if($data->wishlist->count()>0){
          foreach($data->wishlist as $wishlist){
            $wishlist->delete();
          }
        }

        if($course->enrolled_courses->count()>0){
            foreach($course->enrolled_courses as $enroll){
                $enroll->delete();
            }
        }
        $course->delete();
      }
    }

    if($data->enrolled_courses->count()>0){
      foreach($data->enrolled_courses as $enroll){
        $enroll->delete();
      }
    }

    if($data->referral_history->count()>0){
      foreach($data->referral_history as $history){
        $history->delete();
      }
    }

    if($data->instructororders->count()>0){
      foreach($data->instructororders as $order){
        $order->delete();
      }
    }



    if(file_exists(base_path('../assets/images/users/'.$data->photo))){
      unlink(base_path('../assets/images/users/'.$data->photo));
    }
    $data->delete();
    $msg = __('Data Deleted Successfully.');
    return response()->json($msg);
  }

}
