<?php

namespace Modules\Shop\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\Http\Requests\DeleteBlog;
use Modules\Core\Entities\Attachment;
use Modules\Core\Entities\City;
use Modules\Core\Entities\User;
use Modules\Shop\Entities\CategoryShop;
use Modules\Shop\Entities\Shop;
use Modules\Shop\Notifications\test;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\Html\Builder;
use Nwidart\Modules\Facades\Module;
use Modules\Core\Http\Controllers\BaseController;
class ShopController  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(Shop::
        select(['shops.id',DB::raw('concat(users.fname ," ",users.lname) as users_fullname ')
            ,'shops.title','type','price','shops.mobile','business_licence','owner','status','shops.created_at', 'shops.updated_at'])
            ->join('users', 'shops.user_id', '=', 'users.id')
        )

            ->editColumn('type', function($shop) {
                if($shop->type=='silver'){
                    return "<span class='btn btn-default'>نقره ای</span>";
                }
                elseif($shop->type=='gold'){
                    return "<span class='btn btn-warning'>طلایی</span>";
                }
                else{
                    return "<span class='btn btn-primary'>عادی</span>";
                }
            })
            ->editColumn('status', function($shop) {
                if($shop->status==1){
                    return "<span class='btn btn-success'> فعال</span>";
                }elseif($shop->status==0){
                    return "<span class='btn btn-danger'>غیرفعال</span>";
                }
            })
            ->editColumn('owner', function($shop) {
                if($shop->owner==1){
                    return "<span class='btn btn-success'>شخصی</span>";
                }elseif($shop->owner==0){
                    return "<span class='btn btn-danger'>استیجاری</span>";
                }elseif($shop->owner==2){
                    return "<span class='btn btn-danger'>مجازی</span>";
                }
            })
            ->addColumn('operation', function($shop){
                return parent::redirectAction('list/delete?id='.$shop->id,'حذف','danger mr-1')
                    .parent::redirectAction('list/edit/'.$shop->id,'ویرایش','warning mr-1')
                    .parent::redirectAction('list/attachments/'.$shop->id,'پیوست ها','success mr-1');
            })
            ->rawColumns(['operation','status','type','owner'])
            ->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' => 'title', 'name' => 'title', 'title' => 'عنوان'])
        ->addColumn(['data' => 'type', 'name' => 'type', 'title' => 'نوع'])
        ->addColumn(['data' => 'mobile', 'name' => 'mobile', 'title' => 'تلفن همراه'])
        ->addColumn(['data' => 'status', 'name' => 'status', '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 DeleteBlog $request
     * @return Response
     */
    public function destroy(DeleteBlog $request)
{
    Shop::find($request->id)->delete();
    return redirect('admin/shop/list');
}
    public function add()
    {
        $data['model'] = new Shop();
        $data['route_action'] = 'shop.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)
    {
        $shop=Shop::create($request->all());
        $category = collect($request->category_id);
        Shop::find($shop->id)->category()->sync($category ,['created_at' => Carbon::now()]);

        Parent::multi_attachments_process($request,$shop);

        return redirect()->route('admin.shop.list');
    }
    /**
     * Show the form for editing the specified resource.
     * @param Request $request
     * @return Response
     */
    public function edit(Request $request)
    {
        $data['route_action'] = 'shop.list.update';
        $data['data']=Shop::find($request->id);

        $param=Shop::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)
    {
        $shop=Shop::find(($request->id))->update($request->all());
        $category = collect($request->category_id);

        Shop::find($request->id)->category()->sync($category ,['created_at' => Carbon::now()]);

        return redirect()->route('admin.shop.list');
    }

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

    static public function owner(){
    return ['1'=>'شخصی','0' => 'استیجاری','2' => 'مجازی'];
    }

    static public function type(){
    return ['silver'=>'نقره ای','gold' => 'طلایی','normal' => 'عادی'];
    }

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

    public function create(Request $request)
    {
        $request['user_id']=Auth::user()->id;
        $check=Shop::where('user_id',Auth::user()->id)->first();
        if($check==null){
            $data=Shop::create($request->all());
            $category = collect($request->category_id);
            Shop::find($data->id)->category()->sync($category ,['created_at' => Carbon::now()]);
            Parent::multi_attachments_process($request,$data);

            return response()->json([
                'data'  => Shop::with('attachments','user','city')->where('id',$data->id)->get(),
                'message'=>'ok',
                'status' => 200
            ]);
        }else{
            return response()->json([
                'data'  => false,
                'message'=>'rejected',
                'status' => 409
            ]);
        }

    }

//    public function showAll()
//    {
//        $data=Shop::with('attachments','user','city')->paginate(9);
//        return response()->json([
//            'data'  => $data,
//            'message'=>'ok',
//            'status' => 200
//        ]);
//    }

    public function show(Request $request)
    {
        $data=Shop::with('attachments','user','city','advertisement')->where('id',$request->id)->first();
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    public function showAdv(Request $request)
    {

        $data=Shop::find($request->id)->advertisement()->paginate(9);
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    public function updateShop(Request $request)
    {
        $shop=Shop::where('id',$request->id)->first();
        Shop::find(($shop->id))->update($request->all());
        $category = collect($request->category_id);
        Shop::find($shop->id)->category()->sync($category ,['created_at' => Carbon::now()]);
        $data=Shop::where('id',$request->id)->with('attachments','User','city')->first();
        Parent::multi_attachments_process($request,$data);
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    public function delete(Request $request)
    {
        Shop::find($request->id)->delete();
        return response()->json([
            'data'  => true,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    function like(Request $request){
        $like =  Shop::find($request->id)->like()->firstOrCreate([
            'user_id'=>Auth::user()->id
        ]);
        return response()->json([
            'data'  => true,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    static public function assignGold($json){
        $request=json_decode($json);
        $data=$request->data;
        $shop_id=$data->shop_id;
        $invoice_id=$request->invoice_id;

        Shop::where('id',$shop_id)->first()->update(['type'=>'gold']);



        Attachment::where('attachmentable_id',$invoice_id)->where('attachmentable_type','Modules\Financial\Entities\Invoice')->update([
            'attachmentable_type' => 'Modules\Shop\Entities\Shop',
            'attachmentable_id' => $shop_id
        ]);
    }

    static public function assignSilver($json){
    $request=json_decode($json);
    $data=$request->data;
    $shop_id=$data->shop_id;
        $invoice_id=$request->invoice_id;

        Shop::where('id',$shop_id)->first()->update(['type'=>'silver']);

        Attachment::where('attachmentable_id',$invoice_id)->where('attachmentable_type','Modules\Financial\Entities\Invoice')->update([
            'attachmentable_type' => 'Modules\Shop\Entities\Shop',
            'attachmentable_id' => $shop_id
        ]);
}

    public function shopDeleteAttachment(Request $request)
    {
        $Attachment=Attachment::where('uid',$request->uid)->first();
        if($Attachment->attachmentable_type=='Modules\Advertisement\Entities\Shop'){
            $Attachment->attachmentable_id;
            $user_id=Shop::where('id',$Attachment->attachmentable_id)->first()->user_id;
            if($user_id==Auth::user()->id){
                $Attachment->delete();
                return response()->json([
                    'data'  => true,
                    'message'=>'ok',
                    'status' => 200
                ]);
            }else{
                return response()->json([
                    'data'  => false,
                    'message'=>'unAuthorize',
                    'status' => 200
                ]);
            }
        }
    }

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

    public function showAll(Request $request)
    {
        $input = $request->q;
        $c=new Shop();
        $c=$c->where('title','like',"%$input%");
        if(isset($request->filter)){
            $filter=json_decode($request->filter);
            foreach ($filter as $key=>$value){
                $c=$c->where('data->'.$key,$value);
            }
        }

        if(isset($request->type)){
            $c=$c->where('type',$request->type);
        }
        if(isset($request->city_id)){
            $c=$c->where('city_id',$request->city_id);
        }
        if(isset($request->state_id)){
            $cities=City::where('state_id',$request->state_id)->pluck('id');
            $c=$c->whereIn('city_id',$cities);
        }
        if(isset($request->orderby)){
            if($request->orderby=='priceDesc'){
                $c=$c->orderBy('price','DESC');

            }elseif ($request->orderby=='priceAsc'){
                $c=$c->orderBy('price','ASC');

            }elseif ($request->orderby=='idAsc'){
                $c=$c->orderBy('id','ASC');

            }
            elseif ($request->orderby=='idDesc'){
                $c=$c->orderBy('id','DESC');
            }
        }


        if(isset($request->category_id)){
            $shop_ids=CategoryShop::where('category_id',$request->category_id)->pluck('shop_id');
            $c=$c->whereIn('id',$shop_ids);

        }
        if(isset($request->cat_parent)){
            $cats=Category::where('parent_id',$request->cat_parent)->pluck('id');
            $shop_ids=CategoryShop::whereIn('category_id',$cats)->pluck('shop_id');
            $c=$c->whereIn('id',$shop_ids);

        }
        $data=$c->with('category','attachments','user','city')->where('status',1)->paginate(9);
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);







    }

}