<?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\Entities\Auction;
use Modules\Auction\Entities\AuctionCategory;
use Modules\Auction\Http\Requests\CheckSpecialuser;
use Modules\Auction\Notifications\AuctionCreate;
use Modules\Blog\Entities\Comment;

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

class AuctionController 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(Auction::select(['auctions.id',
                DB::raw('concat(users.fname ," ",users.lname) as users_fullname ')
                ,DB::raw('auction_categories.title as auction_categories_title ')
                ,'auctions.title','display','time','auction_category_id', 'auctions.created_at', 'auctions.updated_at'])
                ->join('users', 'auctions.user_id', '=', 'users.id')
                ->join('auction_categories', 'auctions.auction_category_id', '=', 'auction_categories.id')
            )

                ->editColumn('display', function($auction) {
                    if($auction->display==1){
                        return "<span class='btn btn-success'> فعال</span>";
                    }elseif($auction->display==0){
                        return "<span class='btn btn-danger'>غیرفعال</span>";
                    }
                })
                ->addColumn('operation', function($auction) {
                    return parent::redirectAction('list/delete?id='.$auction->id,'حذف','danger mr-1')
                        .parent::redirectAction('list/edit?id='.$auction->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' => 'auction_categories_title', 'name' => 'auction_categories.title', 'title' => 'دسته بندی '])
            ->addColumn(['data' => 'title', 'name' => 'title', 'title' => 'عنوان'])
            ->addColumn(['data' => 'time', 'name' => 'time', 'title' => 'زمان پایان مزایده'])
            ->addColumn(['data' => 'display', 'name' => 'display', '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=Auction::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=AuctionCategory::find($request->id)->auction()->with('category')->orderBy('id','DESC')->get();
            }else{
                $list=Auction::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)
    {
        Auction::find($request->id)->delete();
        return redirect('admin/auction/list');
    }
    /**
     * This function use to create comment for auction
     * @param CheckSpecialuser $request
     * @return Response
     */
    function comment(CheckSpecialuser $request){
        $auction=Auction::find($request->id);

        $comment=$auction->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 auction comments
     * @param CheckSpecialuser $request
     * @return Response
     */
    function commentList(CheckSpecialuser $request){
        $data= Auction::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 Auction();
        $data['route_action'] = 'auction.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)
    {
        $auction=Auction::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,
            'auction_category_id' =>$request->auction_category_id,
            'display' =>$request->display
        ]);
        Parent::attachmentProcess($request,$auction);
        $category_id=$auction->auction_category_id;
        $ids=Like::where('likable_id',$category_id)->where('likable_type','Modules\Auction\Entities\AuctionCategory')->pluck('user_id');
        foreach ($ids as $itm) {
            User::find($itm)->notify(new AuctionCreate($auction->id, $category_id));
        }
        return redirect()->route('admin.auction.list');
    }
    /**
     * Show the form for editing a new resource.
     * @param  Request $request
     * @return Response
     */
    public function showEdit(Request $request)
    {
        $data=Auction::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'] = 'auction.list.update';
        $data['data']=Auction::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)
    {
        Auction::find(($request->id))->update($request->all());
        $data=Auction::find($request->id);
        Parent::attachmentProcess($request,$data);
        return redirect()->route('admin.auction.list');
    }
    /**
     * this function used to like a auction
     * @param CheckSpecialuser $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    function like(CheckSpecialuser $request){
        $auction = Auction::find($request->id);
        $like = $auction->like()->firstOrCreate([
            'user_id'=>Auth::user()->id
        ]);
//        if($like->wasRecentlyCreated){
//            $auction->increment('like');
//        }else{
//            $like->delete();
//            $auction->decrement('like');
//        }
        return response()->json([
            'data'  => true,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    function getLikedauction(){
        $special_user=SpecialUser::pluck('id');
        if(in_array(Auth::user()->id,$special_user)){
            $auctions=Auth::user()->likes()->with('likable')->get();
            return response()->json([
                'data'  => $auctions,
                'message'=>'ok',
                'status' => 200
            ]);
        }else{
            return response()->json([
                'data'  => 'Access Denied',
                'message'=>'ok',
                'status' => 200
            ]);
        }
    }
    /**
     * this function used to search auction
     * @param CheckSpecialuser
     * $request
     * @return array
     */
    function search(CheckSpecialuser $request){
        $input = $request->q;

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

        $data['category']=AuctionCategory::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= AuctionCategory::pluck('title','id');
        return $category;
    }

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