<?php

namespace Modules\Auction\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;
use Modules\Auction\Http\Requests\CheckSpecialuser;
use Modules\Auction\Notifications\TenderCreate;
use Modules\Blog\Entities\Comment;
use Modules\Auction\Entities\Tender;
use Modules\Auction\Entities\TenderCategory;

use Modules\Blog\Entities\Like;
use Modules\Core\Entities\User;
use Modules\Slider\Entities\Slider;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\Html\Builder;
use Nwidart\Modules\Facades\Module;
use Modules\Core\Http\Controllers\BaseController;

class TenderController 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(Tender::select(['tenders.id',
                DB::raw('concat(users.fname ," ",users.lname) as users_fullname ')
                ,DB::raw('tender_categories.title as tender_categories_title ')
                ,'tenders.title','display','time','tender_category_id', 'tenders.created_at', 'tenders.updated_at'])
                ->join('users', 'tenders.user_id', '=', 'users.id')
                ->join('tender_categories', 'tenders.tender_category_id', '=', 'tender_categories.id')
            )
                ->editColumn('display', function($tender) {

                    if($tender->display==1){
                        return "<span class='btn btn-success'> فعال</span>";
                    }elseif($tender->display==0){
                        return "<span class='btn btn-danger'>غیرفعال</span>";
                    }
                })
                ->addColumn('operation', function($tender) {
                    return parent::redirectAction('list/delete?id='.$tender->id,'حذف','danger mr-1')
                        .parent::redirectAction('list/edit?id='.$tender->id,'ویرایش','warning mr-1');
                })
                ->rawColumns(['operation','display'])
                ->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' => 'tender_categories_title', 'name' => 'tender_categories.title', 'title' => 'دسته بندی '])
            ->addColumn(['data' => 'title', 'name' => 'title', 'title' => 'عنوان'])
            ->addColumn(['data' => 'time', 'name' => 'time', 'title' => 'زمان پایان مناقصه'])
            ->addColumn(['data' => 'display', 'name' => 'display', 'title' => 'نمایش'])
            ->addColumn(['data' => 'tender_category_id', 'name' => 'tender_category_id', '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']));
    }

    public function show(CheckSpecialuser $request)
    {
        $data=Tender::find($request->id)->with('category','user','comments')->where('id',$request->id)->first();
        $data->increment('hit');
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * Show the specified resource.
     * @param CheckSpecialuser $request
     * @return Response
     */
    public function list(CheckSpecialuser $request)
    {
        if($request->id){
            $list=TenderCategory::find($request->id)->tender()->with('category')->orderBy('id','DESC')->get();
        }else{
            $list=Tender::with('category')->orderBy('id','DESC')->get();
        }
        if($request->sort == 'hit'){
            $list=$list->sortByDesc('hit')->values()->all();
        }
        if($request->sort == 'like'){
            $list=$list->sortByDesc('likes')->values()->all();
        }
        $list=BaseController::paginateCollection($list,9,$request->page);
        return response()->json([
            'data'  => $list,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * Remove the specified resource from storage.
     * @param Request $request
     * @return Response
     */
    public function destroy(Request $request)
    {
        Tender::find($request->id)->delete();
        return redirect('admin/tender/list');
    }
    /**
     * This function use to create comment for tender
     * @param CheckSpecialuser $request
     * @return Response
     */
    function comment(CheckSpecialuser $request){
        $tender=Tender::find($request->id);

        $comment=$tender->comments()->create([
            'comment'=>$request->comment,
            'user_id'=>Auth::user()->id,
        ]);

        $results=Comment::where('id',$comment->id)->with('commentable')->first();
        return response()->json([
            'data'  => $results,
            'message'=>__('ok'),
            'status' => 200
        ]);
    }
    /**
     * This function use to get list og tender comments
     * @param CheckSpecialuser $request
     * @return Response
     */
    function commentList(CheckSpecialuser $request){
        $data= Tender::where('id',$request->id)->with('comments')->first();
        return response()->json([
            'data'  => $data,
            'message'=>__('ok'),
            'status' => 200
        ]);
    }
    /**
     * Remove the specified comment
     * @param CheckSpecialuser $request
     * @return Response
     */
    public function deleteComment(CheckSpecialuser $request)
    {
        Comment::find($request->id)->delete();
        return response()->json([
            'data' =>true,
            'message'=>'deleted',
            'status' => 200
        ]);
    }
    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function add()
    {
        $data['model'] = new Tender();
        $data['route_action'] = 'tender.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)
    {
        $tender=Tender::create([
            'user_id' => Auth::user()->id,
            'title' => $request->title,
            'seo_title' => $request->seo_title,
            'seo_description' => $request->seo_description,
            'content' => $request->get('content'),
            'description' =>$request->description,
            'tender_category_id' =>$request->tender_category_id,
            'display' =>$request->display
        ]);
        Parent::attachmentProcess($request,$tender);
            $category_id=$tender->tender_category_id;
            $ids=Like::where('likable_id',$category_id)->where('likable_type','Modules\Auction\Entities\TenderCategory')->pluck('user_id');
            foreach ($ids as $itm){
                User::find($itm)->notify(new TenderCreate($tender->id,$category_id));
        }
        return redirect()->route('admin.tender.list');
    }
    /**
     * Show the form for editing a new resource.
     * @param  Request $request
     * @return Response
     */
    public function showEdit(Request $request)
    {
        $data=Tender::find($request->id);
        return view('core::shared.edit', ['data' => $data]);
    }
    /**
     * Show the form for editing the specified resource.
     * @param Request $request
     * @return Response
     */
    public function edit(Request $request)
    {
        $data['route_action'] = 'tender.list.update';
        $data['data']=Tender::find($request->id);
        return view('core::shared.edit', $data);
    }
    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(Request $request)
    {
        Tender::find(($request->id))->update($request->all());
        $data=Tender::find($request->id);
        Parent::attachmentProcess($request,$data);
        return redirect()->route('admin.tender.list');
    }
    /**
     * this function used to like a tender
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    function like(Request $request){
        $tender = Tender::find($request->id);
        $like = $tender->like()->firstOrCreate([
            'user_id'=>Auth::user()->id
        ]);
//        if($like->wasRecentlyCreated){
//            $tender->increment('like');
//        }else{
//            $like->delete();
//            $tender->decrement('like');
//        }
        return response()->json([
            'data'  => true,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    function getLikedtender(){
        $tenders=Auth::user()->likes()->with('likable')->get();
        return response()->json([
            'data'  => $tenders,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * this function used to search tender
     * @param Request $request
     * @return array
     */
    function search(Request $request){
        $input = $request->q;

        $data['tender']=tender::where('title','like',"%$input%")
            ->orWhere('description','like',"%$input%")
            ->orWhere('content','like',"%$input%")
            ->get();

        $data['category']=tenderCategory::where('title','like',"%$input%")
            ->orWhere('description','like',"%$input%")
            ->get();

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

    static public function display(){
        return ['1'=>'فعال','0' => 'غیر فعال'];
    }

    static public function category(){
        $category= tenderCategory::pluck('title','id');
        return $category;
    }

    public function showAll()
    {
        $data['tender']=Tender::orderBy('id','desc')->with('category')->paginate(9);
        $data['category']=TenderCategory::orderBy('id','desc')->get();
        $data['slider']=Slider::where('slug','main')->with('subs')->get();
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }


    /**
     * Show tender by category id.
     * @param Request $request
     * @return Response
     */
    public function lists(Request $request)
    {
        if($request->q!=null){
            $input=$request->q;
            $data=Tender::where('title','like',"%$input%")
                ->orWhere('description','like',"%$input%")
                ->orWhere('content','like',"%$input%")
                ->paginate(9);

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

        }
        else{
            if($request->id!=null){
                if(TenderCategory::find($request->id)==null){
                    $list=TenderCategory::find($request->id);
                }else{
                    $list=TenderCategory::find($request->id)->tender()->with('category')->orderBy('id','asc')->paginate(9);
                }
            }else{
                $list=Tender::with('category')->paginate(9);
            }
            if($request->sort == 'hit'){
                $list=$list->sortBy('hit');
            }
            if($request->sort == 'like'){
                $list=$list->sortBy('likes');
            }
            return response()->json([
                'data' =>$list,
                'message'=>'ok',
                'status' => 200
            ]);
        }



    }
}