<?php

namespace App\Http\Controllers\Admin;

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

class CategoryController extends Controller
{

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


    //*** JSON Request
    public function datatables()
    {
         $datas = Category::where('register_id',0)->orderBy('id','desc')->get();
         //--- Integrating This Collection Into Datatables
         return Datatables::of($datas)
                            ->addColumn('status', function(Category $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-cat-status',['id1' => $data->id, 'id2' => 1]).'">'.__("Activate").'</a>
                                  <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('admin-cat-status',['id1' => $data->id, 'id2' => 0]).'">'.__("Deactivate").'</a>
                                </div>
                              </div>';

                            })

                            ->addColumn('action', function(Category $data) {
                                return '<div class="actions-btn"><a href="' . route('admin-cat-edit',$data->id) . '" class="btn btn-primary btn-sm btn-rounded">
                                <i class="fas fa-edit"></i> '.__("Edit").'
                              </a><button type="button" data-toggle="modal" data-target="#deleteModal"  data-href="' . route('admin-cat-delete',$data->id) . '" class="btn btn-danger btn-sm btn-rounded">
                                <i class="fas fa-trash"></i>
                              </button></div>';
                            })
                            ->rawColumns(['status','action'])
                            ->toJson(); //--- Returning Json Data To Client Side
    }

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

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

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

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

        $rules = [
            'photo' => 'mimes:jpeg,jpg,png,svg|max:2000',
                 ];
        $customs = [
            'photo.mimes' => __('Icon Type is Invalid.'),
            'photo.max' => __('Maximum Size is 2 MB.'),
                   ];
        $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 Category();
        $input = $request->all();
        if ($file = $request->file('photo'))
         {
            $name = time().str_replace(' ', '', $file->getClientOriginalName());
            $file->move('assets/images/categories',$name);
            $input['photo'] = $name;
        }
        if ($request->is_top == ""){
            $input['is_top'] = 0;
        }
        else {
            $input['is_top'] = 1;
        }
        $data->fill($input)->save();
        //--- Logic Section Ends

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

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

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

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

        $rules = [
            'photo' => 'mimes:jpeg,jpg,png,svg|max:2000',
                 ];
        $customs = [
            'photo.mimes' => __('Icon Type is Invalid.'),
            'photo.max' => __('Maximum Size is 2 MB.'),
                   ];
        $validator = Validator::make($request->all(), $rules, $customs);

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

        //--- Logic Section
        $data = Category::findOrFail($id);
        $input = $request->all();
            if ($file = $request->file('photo'))
            {
                $name = time().str_replace(' ', '', $file->getClientOriginalName());
                $file->move('assets/images/categories',$name);
                if($data->photo != null)
                {
                    if(file_exists(base_path('../assets/images/categories/'.$data->photo))){
                        unlink(base_path('../assets/images/categories/'.$data->photo));
                    }
                }
            $input['photo'] = $name;
            }

            if ($request->is_top == ""){
                $input['is_top'] = 0;
            }
            else {
                $input['is_top'] = 1;
            }
        $data->update($input);
        //--- Logic Section Ends

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

      //*** GET Request Status
      public function status($id1,$id2)
      {
        $data = Category::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 = Category::findOrFail($id);

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

      //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/categories/'.$data->photo))){
          unlink(base_path('../assets/images/categories/'.$data->photo));
      }


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