<?php

namespace Modules\Expert\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Advertisement\Entities\Category;
use Modules\Blog\Entities\Comment;
use Modules\Core\Entities\User;
use Modules\Expert\Entities\Expert;
use Modules\Expert\Entities\UserExpert;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\Html\Builder;
use Nwidart\Modules\Facades\Module;
use Modules\Core\Http\Controllers\BaseController;

class ExpertController extends  BaseController
{
    protected $htmlBuilder;
    public function __construct(Builder $htmlBuilder)
{
    $this->htmlBuilder = $htmlBuilder;
    $this->htmlBuilder->parameters([
        'paging' => true,
        'searching' => true,
        'info' => false,
        'searchDelay' => 350,
        'language' => [
            'url' => Module::asset('core:datatable.json')
        ],
    ]);
    Parent::__construct();
}
    public function index(Request $request)
    {
    if ($request->ajax()) {
        return DataTables::of(Expert::select(['experts.id',DB::raw('concat(users.fname ," ",users.lname) as users_fullname '),'inbox','request', 'experts.created_at', 'experts.updated_at']
        ) ->join('users', 'experts.user_id', '=', 'users.id'))

            ->addColumn('operation', function($expert) {
                return parent::redirectAction('list/delete?id='.$expert->id,'حذف','danger mr-1')
                    .parent::redirectAction('list/edit?id='.$expert->id,'ویرایش','warning mr-1');
            })
            ->rawColumns(['operation'])
            ->make(true);
    }
    $object = 'کارشناسان';
    $html = $this->htmlBuilder
        ->addColumn(['data' =>'id', 'name' => 'id', 'title' => 'شناسه'])
        ->addColumn(['data' => 'users_fullname', 'name' => 'users.fname', 'title' => 'نام کاربر'])
        ->addColumn(['data' => 'users_fullname', 'name' => 'users.lname', 'title' => 'نام کاربر','class'=>'d-none'])
        ->addColumn(['data' => 'inbox', 'name' => 'inbox', 'title' => 'inbox'])
        ->addColumn(['data' => 'request', 'name' => 'request', 'title' => 'تعداد درخواست'])
        ->addColumn(['data' => 'created_at', 'name' => 'created_at', 'title' => 'ثبت'])
        ->addColumn(['data' => 'updated_at', 'name' => 'updated_at', 'title' => 'ویرایش'])
        ->addColumn(['data' => 'operation', 'name' => 'operation', 'title' => 'عملیات']);
    return view('core::shared.datatable', compact(['html','object']));
}
    /**
     * Remove the specified resource from storage.
     * @param Request $request
     * @return Response
     */
    public function destroy(Request $request)
{
    Expert::find($request->id)->delete();
    return redirect('admin/expert/list');
}
    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function add()
{
    $data['model'] = new Expert();
    $data['route_action'] = 'expert.list.store';
    return view('core::shared.add',$data);
}
    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
{
    $category = collect($request->category_id);
    $expert=Expert::create($request->all());
    Expert::find($expert->id)->category()->sync($category ,['created_at' => Carbon::now()]);
    return redirect()->route('admin.expert.list');
}
    /**
     * Show the form for editing the specified resource.
     * @param Request $request
     * @return Response
     */
    public function edit(Request $request)
{
    $data['route_action'] = 'expert.list.update';
    $data['data']=Expert::find($request->id);
    $param=Expert::find($request->id)->category()->select('categories.id', 'categories.title')->groupBy('id')->pluck('title', 'id');
    return view('core::shared.edit',$data, [ 'data'=>$data,'param'=>$param]);
}
    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(Request $request)
    {
    Expert::find(($request->id))->update($request->all());
    $expert=Expert::find($request->id);
        $category = collect($request->category_id);
        Expert::find($expert->id)->category()->sync($category ,['created_at' => Carbon::now()]);
    return redirect()->route('admin.expert.list');
    }
    /**
     * get expert list for advertisements
     * @param Request $request
     * @return Response
     */
    public function showAll(Request $request)
    {
        $data=Category::where('id',$request->id)->expert()->orderByRaw("RAND()")->get();
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * get expert list for advertisements
     * @return Response
     */
    public function show()
    {
        $data=Expert::where('user_id',Auth::user()->id)->with('users')->first();
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    public function single(Request $request)
    {
        $data=Expert::where('id',$request->id)->first();
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * get expert list for advertisements
     * @param Request $request
     * @return Response
     */
    public function listExperts(Request $request)
    {
        $data=Category::find($request->category_id)->expert()
            ->where('inbox','<',5)
//            ->where('request','>',0)
            ->where('city_id',$request->city_id)
            ->get();

        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    public function assign(Request $request){
        $expert_id=$request->expert_id;
        $adv_id=$request->adv_id;
        $check=UserExpert::where('user_id', Auth::user()->id)->where('adv_id',$adv_id)->where('expert_id',$expert_id)->first();
        if($check!=null){
            return response()->json([
                'data'  => false,
                'message'=>'conflict',
                'status' => 409
            ]);
        }else{
            $list=Expert::where('inbox','<',5)->where('request','>',0)->pluck('id')->toArray();

            if(in_array($expert_id,$list)){
                $data=UserExpert::create([
                    'user_id' => Auth::user()->id ,
                    'adv_id' => $adv_id ,
                    'expert_id' => $expert_id
                ]);
                return response()->json([
                    'data'  => $data,
                    'message'=>'ok',
                    'status' => 200
                ]);
            }else{
                return response()->json([
                    'data'  => false,
                    'message'=>'have no capacity',
                    'status' => 400
                ]);
            }
        }

    }
    /**
     * Show the specified resource.
     * @return Response
     */
    public function waitList()
{
    $expert_id=Expert::where('user_id',Auth::user()->id)->first()->id;
    $data=UserExpert::where('expert_id',$expert_id)->where('status',0)->get();
    return response()->json([
        'data'  => $data,
        'message'=>'ok',
        'status' => 200
    ]);
}

    public function acceptedList()
    {
        $expert_id=Expert::where('user_id',Auth::user()->id)->first()->id;
        $data=UserExpert::where('expert_id',$expert_id)->where('status',1)->get();
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    public function editList(Request $request)
    {
        $expert_id=Expert::where('user_id',Auth::user()->id)->first()->id;
        $check=UserExpert::where('expert_id',$expert_id)->where('id',$request->id)->first();
        if($check!=null){
            if (isset($request->remove)){
                UserExpert::where('expert_id',$expert_id)->where('id',$request->id)->first()->delete();
                $data=true;

            }else{
                UserExpert::where('expert_id',$expert_id)->where('id',$request->id)->first()->update($request->all());
                $data=UserExpert::where('expert_id',$expert_id)->where('id',$request->id)->first();
            }

            return response()->json([
                'data'  => $data,
                'message'=>'ok',
                'status' => 200
            ]);
        }else{
            return response()->json([
                'data'  => 'not match',
                'message'=>'ok',
                'status' => 403
            ]);
        }
    }

    public function point(Request $request)
    {
        $check=UserExpert::where('id',$request->id)->first();
        if($check!=null){
            UserExpert::where('id',$request->id)->first()->update(['point' => $request->point]);
            $data=UserExpert::where('id',$request->id)->first();
            return response()->json([
                'data'  => $data,
                'message'=>'ok',
                'status' => 200
            ]);
        }else{
            return response()->json([
                'data'  => 'not match',
                'message'=>'ok',
                'status' => 403
            ]);
        }
    }

    public function getPoint(Request $request)
    {
        $check=UserExpert::where('expert_id',$request->expert_id)->whereNotNull('Point')->first();
        if($check!=null){
            $data['point']=UserExpert::where('expert_id',$request->expert_id)->whereNotNull('Point')->avg('Point');
            $data['count']=UserExpert::where('expert_id',$request->expert_id)->whereNotNull('Point')->count();
            return response()->json([
                'data'  => $data,
                'message'=>'ok',
                'status' => 200
            ]);
        }else{
            $data['point']=0;
            $data['count']=0;
            return response()->json([
                'data'  => $data,
                'message'=>'has no point',
                'status' => 200
            ]);
        }
    }

    static public function addRequests($json){
        $request=json_decode($json);
        $data=$request->data;
        $user_id=$request->user_id;
        $expert=Expert::where('user_id',$user_id)->first();
        $expert_id=$expert->id;
        $expert_request=$expert->request;
        $request=$data->request;
        Expert::find($expert_id)->update(['request'=>$expert_request+$request]);
    }

    public function create(Request $request)
    {
        $category = collect($request->category_id);
        $request['user_id']=Auth::user()->id;
        $request['city_id']=Auth::user()->city_id;
        $expert=Expert::create($request->all());
        Expert::find($expert->id)->category()->sync($category ,['created_at' => Carbon::now()]);
        return response()->json([
            'data'  => $expert,
            'message'=>'ok',
            'status' => 200
        ]);
    }


    public function updateCat(Request $request)
    {
        $expert=Expert::where('user_id',Auth::user()->id)->first();
        Expert::find(($expert->id))->update($request->all());

        $category = collect($request->category_id);
        Expert::find($expert->id)->category()->sync($category ,['created_at' => Carbon::now()]);
        return response()->json([
            'data'  => $expert,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    static public function users()
    {
        $category = User::select('id', DB::raw('CONCAT(`fname`," " ,`lname`) as full_name'))->groupBy('id')->pluck('full_name', 'id');
        return $category;
    }

    static public function categories()
    {
        $category = Category::where('parent_id','!=',null)->pluck('title', 'id');
        return $category;
    }

}
