<?php

namespace App\Http\Controllers\Instructor;

use Validator;
use Datatables;
use App\Models\Course;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use DB;

class CourseController extends Controller
{


  public $curr;

  public function __construct()
  {
      $this->middleware('auth:web');

      $this->curr = \DB::table('currencies')->where('register_id',0)->where('is_default','=',1)->first();

  }

    //*** JSON Request
    public function datatables()
    {
      $user = Auth::guard('web')->user();

         $datas = Course::where('register_id',0)->where('user_id',$user->id)->orderBy('id','desc')->get();
         //--- Integrating This Collection Into Datatables
         return Datatables::of($datas)

                            ->editColumn('price', function(Course $data) {
                                $price = $data->price * $this->curr->value;
                                $show_price = $price == 0 ? __('Free') : $this->curr->sign.$price;
                                return $show_price;
                            })

                            ->addColumn('status', function(Course $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('instructor-course-status',['id1' => $data->id, 'id2' => 1]).'">'.__("Activate").'</a>
                                  <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('instructor-course-status',['id1' => $data->id, 'id2' => 0]).'">'.__("Deactivate").'</a>
                                </div>
                              </div>';
                            })
                            ->addColumn('action', function(Course $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('instructor-course-curriculam',$data->id) . '" class="dropdown-item options">
                              <i class="fas fa-cog"></i> '.__("Curriculam").'
                            </a>
                                <a href="' . route('instructor-course-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('instructor-course-delete',$data->id) . '" class="dropdown-item options">
                                <i class="fas fa-trash"></i> '.__("Delete").'
                              </button>

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

    //*** GET Request
    public function index()
    {
        return view('instructor.course.index');
    }

    //*** GET Request
    public function create()
    {
        return view('instructor.course.create');
    }

    //*** GET Request
    public function load($id)
    {
        $cat = Category::find($id);
        return view('admin.subcategory.load.subcategory',compact('cat'));
    }


    //*** POST Request
    public function store(Request $request)
    {
      if(Course::where('title',$request->title)->where('register_id',0)->exists()){
        return response()->json(array('errors' => [0 =>'This title has already been taken.']));
      }
        $rules = [
            'photo' => 'mimes:jpeg,jpg,png,svg',
            ];
        $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 Course();

        $input = $request->all();
        if ($file = $request->file('photo'))
         {
            $name = time().str_replace(' ', '', $file->getClientOriginalName());
            $file->move('assets/images/courses',$name);
            $input['photo'] = $name;
        }
       
        if ($request->is_free){
            $input['is_free'] = 1;
            $input['price'] = 0;
            $input['discount_price'] = 0;
        }else{
            $input['is_free'] = 0;
            $input['price'] = ($input['price'] / $this->curr->value);
            $input['discount_price'] = ($input['discount_price'] / $this->curr->value);
        }

        $input['requirements'] = implode(',,,', $request->requirements);
        $input['outcomes'] = implode(',,,', $request->outcomes);
        $input['include_icon'] = implode(',,,', $request->include_icon);
        $input['include_text'] = implode(',,,', $request->include_text);
        $input['status'] = 1;
        if(!empty($request->meta_keywords)){
            $input['meta_keywords'] = str_replace(["value", "{", "}", "[","]",":","\""], '', $request->meta_keywords);
        }

        $input['slug'] = str_replace(" ","-",$input['title']);
        $input['user_id'] = Auth::user()->id;

        $data->fill($input)->save();

        //--- Logic Section Ends

        //--- Redirect Section
        $msg = __('New Data Added Successfully.').' '.'<a href="'.route('instructor-course-index').'"> '.__('View Lists.').'</a>';
        return response()->json($msg);
        //--- Redirect Section Ends
    }

    //*** GET Request
    public function edit($id)
    {
        $data = Course::findOrFail($id);
        return view('instructor.course.edit',compact('data'));
    }

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

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

        $rules = [
        	'photo' => 'mimes:jpeg,jpg,png,svg',
        		];
        $customs = [
        	'photo.mimes' => __('Icon 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 = Course::findOrFail($id);

        $input = $request->all();
        if ($file = $request->file('photo'))
         {
            if(file_exists(base_path('../assets/images/courses/'.$data->photo))){
                unlink(base_path('../assets/images/courses/'.$data->photo));
            }

            $name = time().str_replace(' ', '', $file->getClientOriginalName());
            $file->move('assets/images/courses',$name);
            $input['photo'] = $name;
        }
   
        if ($request->is_free){
            $input['is_free'] = 1;
            $input['price'] = 0;
            $input['discount_price'] = 0;
        }else{
            $input['is_free'] = 0;
            $input['price'] = ($input['price'] / $this->curr->value);
            $input['discount_price'] = ($input['discount_price'] / $this->curr->value);
        }

        $input['requirements'] = implode(',,,', $request->requirements);
        $input['outcomes'] = implode(',,,', $request->outcomes);
        $input['include_icon'] = implode(',,,', $request->include_icon);
        $input['include_text'] = implode(',,,', $request->include_text);
        if(!empty($request->meta_keywords)){
            $input['meta_keywords'] = str_replace(["value", "{", "}", "[","]",":","\""], '', $request->meta_keywords);
        }

        $input['slug'] = str_replace(" ","-",$input['title']);
        $input['user_id'] = Auth::user()->id;

        $data->update($input);
        //--- Logic Section Ends

        //--- Redirect Section
        $msg = __('Data Updated Successfully.').' '.'<a href="'.route('instructor-course-index').'">'.__('View Lists.').'</a>';
        return response()->json($msg);
        //--- Redirect Section Ends
    }

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

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

      }


    //*** GET Request Delete
    public function destroy($id)
    {
        $data = Course::findOrFail($id);

        //If Photo Doesn't Exist
        if($data->photo == null){
            $data->delete();
            //--- Redirect Section
            $msg = __('Data Deleted Successfully.');
            return response()->json($msg);
            //--- Redirect Section Ends
        }
        //If Photo Exist
        if(file_exists(base_path('../assets/images/courses/'.$data->photo))){
            unlink(base_path('../assets/images/courses/'.$data->photo));
          }

        $data->delete();
        //--- Redirect Section
        $msg = __('Data Deleted Successfully.');
        return response()->json($msg);
        //--- Redirect Section Ends
    }
}
