<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Withdraw;
use Validator;
use Auth;
use App\Models\Order;
use Datatables;

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

    //*** JSON Request
    public function datatables()
    {
         $datas = User::where('register_id',0)->whereIsInstructor(2)->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 = $data->photo ? '<img src="'.asset('assets/images/users/'.$data->photo).'" width="80" alt="Users">' : '<img src="'.asset('assets/images/placeholder.jpg').'" width="80" alt="Users">';
                                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-instructor-status',['id1' => $data->id, 'id2' => 1]).'">'.__("Activate").'</a>
                                  <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('admin-instructor-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-instructor-secret',$data->id) . '" class="dropdown-item options">
                                <i class="fas fa-user-secret"></i> '.__("Secret Login").'
                              </a>
				<a href="javascript:;" data-href="' . route('admin-instructor-details',$data->id) . '" class="dropdown-item options" id="instructordetails" data-toggle="modal" data-target="#details">
                                <i class="fas fa-eye"></i> '.__("Details").'
                              </a>
                                <a href="' . route('admin-instructor-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-instructor-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 secretlogin($id)
{
  $instructor = User::findOrFail($id);
  Auth::guard('web')->login($instructor);
  return redirect(route('instructor-dashboard'));
}




      public function create()
      {
          return view('admin.instructor.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.']));
          }

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


           $rules = [
              'photo' => 'mimes:jpeg,jpg,png,svg',
              'first_name' => 'required',
              'last_name' => 'required',
              'phone' => 'required',
              'address' => '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['instructor_slug'] = str_replace(" ","-",$input['instructor_name']);
         $input['affilate_code'] = md5($request->first_name.$request->last_name.$request->email);

         $input['is_instructor'] = 2;
         $data->create($input);
         $mgs = __('Data Added Successfully.').' '.'<a href="'.route('admin-instructor-index').'">'.__('View Lists.').'</a>';
         return response()->json($mgs);
      }


      public function edit($id)
      {
        $data = User::findOrFail($id);
        return view('admin.instructor.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.']));
        }
         if(User::where('instructor_name',$request->instructor_name)->where('id','!=',$id)->where('register_id',0)->exists()){
          return response()->json(array('errors' => [0 =>'This Instructor name has already been taken.']));
        }


         $rules = [
          'photo' => 'mimes:jpeg,jpg,png,svg',
          'first_name' => 'required',
          'last_name' => 'required',
          'phone' => 'required',
          'address' => '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);

      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;
    }
    $input['is_instructor'] = 2;
    $input['instructor_slug'] = str_replace(" ","-",$input['instructor_name']);

     $data->update($input);
     $mgs = __('Data Updated Successfully.').' '.'<a href="'.route('admin-instructor-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 details($id)
    {
      $instructor = User::findOrFail($id);
      return view('admin.instructor.details',compact('instructor'));
    }



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();
              }
          }
          $course->delete();
        }
      }

	

      if($data->wishlist){
            foreach($data->wishlist as $wishlist){
              $wishlist->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($data->withdraws->count() > 0)
        {
            foreach ($data->withdraws as $gal) {
                $gal->delete();
            }
        }

      
        if($data->senders->count() > 0)
        {
            foreach ($data->senders as $gal) {
            if($gal->messages->count() > 0)
            {
                foreach ($gal->messages as $key) {
                    $key->delete();
                }
            }
                $gal->delete();
            }
        }

        if($data->recievers->count() > 0)
        {
            foreach ($data->recievers as $gal) {
            if($gal->messages->count() > 0)
            {
                foreach ($gal->messages as $key) {
                    $key->delete();
                }
            }
                $gal->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);
    }



    // Apllication Instructor
    public function applications()
    {
      return view('admin.instructor.application.index');
    }


     //*** JSON Request
     public function applicationdatatables()
     {
          $datas = User::where('register_id',0)->where('is_instructor',1)->get();
          //--- Integrating This Collection Into Datatables
          return Datatables::of($datas)


                             ->addColumn('details', function(User $data) {
                                 $details = '<button class="btn btn-primary" id="applicationDetails" data-toggle="modal" data-href="'.route('admin.application.details',$data->id).'" data-target="#details">'.__('Details').'</button>';
                                 return $details;
                             })

                             ->editColumn('document', function(User $data) {
                                 $document = $data->document == __('Not Sent') ? '' : '<a class="btn btn-primary" id="applicationDowoload" href="'.route('admin.application.download',$data->id).'">'.__('Download').'</a>';
                                 return $document;
                             })

                             ->addColumn('name', function(User $data) {
                                 $name = $data->first_name . $data->last_name;
                                 return $name;
                             })

                             ->addColumn('status', function(User $data) {
                              $status      = $data->status == 2 ? __('Approve') : __('Pending');
                              $status_sign = $data->status == 2 ? 'success'   : 'danger';

                              return '<div class="btn-group mb-1">
                              <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.application.status',['id1' => $data->id, 'id2' => 2]).'">'.__("Approve").'</a>
                                <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('admin.application.status',['id1' => $data->id, 'id2' => 0]).'">'.__("Pending").'</a>
                              </div>
                            </div>';

                          })

                             ->addColumn('action', function(User $data) {
                                 return '<button type="button" data-toggle="modal" data-target="#deleteModal"  data-href="' . route('admin.application.delete',$data->id) . '" class="btn btn-danger btn-sm">
                                 <i class="fas fa-trash"></i>
                               </button>';
                             })
                             ->rawColumns(['details','name','status','action','document'])
                             ->toJson(); //--- Returning Json Data To Client Side
                       }



public function applicationsdetails($id)
{
    $data['data'] = User::findOrFail($id);
    return view('admin.instructor.application.details',$data);
}


   //*** GET Request Status
   public function applicationstatus($id1,$id2)
   {
     $user = User::findOrFail($id1);

     if($id2 == 2)
     $user->update([
       'is_instructor' =>2,

     ]);
     else{
      $user->update([
        'is_instructor' => 1,
      ]);
     }

     $user->update();

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

   }



   public function applicationdelete($id)
   {
       $user = User::findOrFail($id);

       if(file_exists(base_path('../assets/application/'.$user->document))){
        unlink(base_path('../assets/application/'.$user->document));
      }

      $user->update([
        'is_instructor' => 0,
        'address' => '',
        'message' => '',
        'phone' => '',
        'document' => '',
        'instructor_name' => '',
        'instructor_slug' => '',
      ]);
      $msg = __('Application delete Successfully.');
      return response()->json($msg);

   }


public function applicationdownload($id)
{
  $data = User::findOrFail($id);
  return response()->download(public_path('assets/application/'.$data->document));
}


public function withdraws(){
  return view('admin.instructor.withdraws');
}

 //*** JSON Request
 public function withdrawdatatables()
 {
      $datas = Withdraw::where('register_id',0)->get();
      //--- Integrating This Collection Into Datatables
      return Datatables::of($datas)
                         ->addColumn('email', function(Withdraw $data) {
                             $email = $data->user->email;
                             return $email;
                         }) 
                         ->addColumn('phone', function(Withdraw $data) {
                             $phone = $data->user->phone;
                             return $phone;
                         }) 
                         ->editColumn('status', function(Withdraw $data) {
                             $status = ucfirst($data->status);
                             return $status;
                         }) 
                         ->editColumn('amount', function(Withdraw $data) {
                             $amount = $data->amount;
                             return '$' . $amount;
                         }) 
                         ->editColumn('created_at', function(Withdraw $data) {
                          $date = $data->created_at->diffForHumans();
                          return $date;
                      }) 
                     
                      ->addColumn('action', function(Withdraw $data) {
                      $action = '<div class="actions-btn"><a href="javascript:;" data-href="' . route('admin-withdraw-show',$data->id) . '" class="btn btn-primary btn-sm btn-rounded" id="applicationDetails" data-toggle="modal" data-target="#details">
                        <i class="fas fa-eye"></i> '.__("Details").'
                      </a>';

                      if($data->status == "pending") {
                        $action .= '<button data-href="' . route('admin-withdraw-accept',$data->id) . '" class="btn btn-success btn-sm btn-rounded" data-toggle="modal" class="btn btn-success" data-target="#status-modal">
                        <i class="fas fa-edit"></i> '.__("Accept").'
                      </button>
                      
                      <button data-href="' . route('admin-withdraw-reject',$data->id) . '" class="btn btn-danger btn-sm btn-rounded" data-toggle="modal" class="btn btn-success" data-target="#confirm-delete">
                      <i class="fas fa-edit"></i> '.__("Reject").'
                    </button>
                    ';
                    }
                      
                      $action .= '</div>';
                      return $action;
                    })
                         
                    
                         
                         ->rawColumns(['name','action'])
                         ->toJson(); //--- Returning Json Data To Client Side
 }


 //*** GET Request       
 public function withdrawdetails($id)
 {
    
     $withdraw = Withdraw::findOrFail($id);
     return view('admin.instructor.withdraw-details',compact('withdraw'));
 }

 //*** GET Request   
 public function accept($id)
 {
     $withdraw = Withdraw::findOrFail($id);
     $data['status'] = "completed";
     $withdraw->update($data);
     //--- Redirect Section     
     $msg = __('Withdraw Accepted Successfully.');
     return response()->json($msg);      
     //--- Redirect Section Ends   
 }

 //*** GET Request   
 public function reject($id)
 {
     $withdraw = Withdraw::findOrFail($id);
     $account = User::findOrFail($withdraw->user->id);
     $account->balance = $account->balance + $withdraw->amount + $withdraw->fee;
     $account->update();
     $data['status'] = "rejected";
     $withdraw->update($data);
     //--- Redirect Section     
     $msg = __('Withdraw Rejected Successfully.');
     return response()->json($msg);      
     //--- Redirect Section Ends   
 }


}
