<?php

namespace Modules\Advertisement\Http\Controllers;

use App\Notifications\HelloNotification;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Advertisement\Entities\Advertisement;
use Modules\Advertisement\Entities\Category;
use Modules\Advertisement\Entities\CityTest;
use Modules\Advertisement\Entities\StateTest;
use Modules\Advertisement\Notifications\NewAdvertisement;
use Modules\Blog\Entities\Like;
use Modules\Core\Entities\Attachment;
use Modules\Core\Entities\City;
use Modules\Core\Entities\CityTranslation;
use Modules\Core\Entities\State;
use Modules\Core\Entities\StateTranslation;
use Modules\Core\Entities\User;

use Yajra\DataTables\DataTables;
use Yajra\DataTables\Html\Builder;
use Nwidart\Modules\Facades\Module;
use Modules\Core\Http\Controllers\BaseController;

class AdvertisementController 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(Advertisement::select(['advertisements.id','advertisements.title','priority','status', 'category_id','expiration_time','type','accept','offer','advertisements.created_at', 'advertisements.updated_at'
                ,DB::raw('concat(users.fname ," ",users.lname) as users_fullname ')
                ,DB::raw('categories.title as categories_title ')
            ])->orderBy('id','Desc')->join('users', 'advertisements.user_id', '=', 'users.id')
                ->join('categories', 'advertisements.category_id', '=', 'categories.id')
            )
                ->editColumn('accept', function($adv){
                    if($adv->accept==1){
                        return "<span class='btn btn-success'>فعال</span>";
                    }elseif($adv->accept==0){
                        return "<span class='btn btn-warning'>غیر فعال</span>";
                    }
                })
                ->editColumn('priority', function($adv) {
                    if($adv->priority=='immediate'){
                        return "<span class='btn btn-warning'>فوری</span>";
                    }elseif($adv->priority=='immediate-special'){
                        return "<span class='btn btn-danger'>ویژه و فوری</span>";
                    }
                    elseif($adv->priority=='special'){
                        return "<span class='btn btn-info'>ویژه</span>";
                    }else{
                        return "<span class='btn btn-primary'>عادی</span>";
                    }
                })
                ->editColumn('type', function($adv){
                    if($adv->type=='rent'){
                        return "اجاره";
                    }elseif($adv->type=='sale'){
                        return "فروش";
                    }
                    elseif($adv->type=='buy'){
                        return "خرید";
                    }
                })
                ->editColumn('offer', function($adv) {

                    if($adv->offer==1){
                        return "<span class='btn btn-success'>فعال</span>";
                    }elseif($adv->offer==0){
                        return "<span class='btn btn-danger'>غیرفعال</span>";
                    }
                })
                ->editColumn('status', function($adv) {
                    if($adv->status==1){
                        return "پرداخت شده";
                    }elseif($adv->status==0){
                        return "منقضی شده";
                    }elseif($adv->status==2){
                        return "در انتظار پرداخت";
                    }
                })
                ->addColumn('operation', function($adv){
                    return parent::redirectAction('list/comment/'.$adv->id,'نظرات','success')
                    . parent::redirectAction('list/experience/'.$adv->id,'گزارشات','primary')
                    . parent::redirectAction('list/offer/'.$adv->id,'پیشنهادات','info')
                    . parent::redirectAction('list/edit/'.$adv->id,'ویرایش','warning');
//                    . parent::redirectAction('list/delete?id='.$adv->id,'حذف','danger');
                })
                ->rawColumns(['operation','status','offer','priority','accept'])
                ->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' => 'accept', 'name' => 'accept', 'title' => 'نمایش'])
            ->addColumn(['data' => 'status', 'name' => 'status', 'title' => 'وضغیت'])
            ->addColumn(['data' => 'priority', 'name' => 'priority', 'title' => 'اولویت'])
            ->addColumn(['data' => 'categories_title', 'name' => 'categories.title', 'title' => 'دسته بندی'])
            ->addColumn(['data' => 'expiration_time', 'name' => 'expiration_time', 'title' => 'انقضا'])
            ->addColumn(['data' => 'created_at', 'name' => 'created_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)
    {
        Advertisement::find($request->id)->delete();
        return redirect('admin/advertisement/list');
    }
    public function getCities($id){
        $ids=City::where('state_id',$id)->pluck('id');
        $data=CityTranslation::whereIn('city_id',$ids)->get();
        return $data;
    }

    public function getCity(Request $request){
        $city=City::where('id',$request->id)->first();
        $ids=$city->id;
        $state_id=$city->state_id;
        $data=CityTranslation::where('city_id',$ids)->first();
        $data['state']=StateTranslation::where('state_id',$state_id)->first();
        return $data;
    }
    public function getStates(){
        $data=StateTranslation::all();
        return $data;
    }
    public function getSubCategory($id){
        $data=Category::where('parent_id',$id)->get();
        return $data;
    }

    public function getDataCategory($id){
        $data=Category::where('id',$id)->with('items')->first();
        $data['expiration_time']=\Carbon\Carbon::now()->addDays($data->time)->toDateString();
        return $data;
    }
    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function add()
    {
        $data['route_action'] = 'advertisement.list.store';
        $data['categories'] = Category::where('parent_id' , null)->get();
        $data['state'] = StateTranslation::all();
        return view('advertisement::advertisement.add',$data);
    }
    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        $request['user_id'] = Auth::user()->id;
        if($request->priority=='immediate'){
            $request['sort'] = 102;

        }elseif($request->priority=='special'){
            $request['sort'] = 103;

        }elseif($request->priority=='normal'){
            $request['sort'] = 101;

        }elseif($request->priority=='immediate-special'){
            $request['sort'] = 104;
        }

        if(isset ($request->datas)){
            $request['data'] = json_encode($request->datas);
            $adv=Advertisement::create($request->all());
        }else{
            $adv=Advertisement::create($request->all());
        }
        Parent::multi_attachments_process($request,$adv);

        if(isset($request->shop_id)){
            $adv_id=$adv->id;
            $shop_id=$request->shop_id;

            $ids=Like::where('likable_id',$shop_id)->where('likable_type','Modules\Shop\Entities\Shop')->pluck('user_id');
            foreach ($ids as $itm){
                User::find($itm)->notify(new NewAdvertisement($adv_id,$shop_id));
            }
        }

        return redirect()->route('admin.advertisement.list');
    }
    public function create(Request $request)
{
    $request['user_id'] = Auth::user()->id;
    $request['user_id'] = Auth::user()->id;
    if($request->priority=='immediate'){
        $request['sort'] = 102;

    }elseif($request->priority=='special'){
        $request['sort'] = 103;

    }elseif($request->priority=='normal'){
        $request['sort'] = 101;

    }elseif($request->priority=='immediate-special'){
        $request['sort'] = 104;
    }
    if(isset ($request->datas)){
        $request['data'] = json_encode($request->datas);
        $adv=Advertisement::create($request->all());
    }else{
        $adv=Advertisement::create($request->all());
    }
    Parent::multi_attachments_process($request,$adv);

    if(isset($request->shop_id)){
        $adv_id=$adv->id;
        $shop_id=$request->shop_id;

        $ids=Like::where('likable_id',$shop_id)->where('likable_type','Modules\Shop\Entities\Shop')->pluck('user_id');
        foreach ($ids as $itm){
            User::find($itm)->notify(new NewAdvertisement($adv_id,$shop_id));
        }
    }
    return response()->json([
        'data'  => $adv,
        'message'=>'ok',
        'status' => 200
    ]);
}
    /**
     * Show the form for editing the specified resource.
     * @param $id
     * @return Response
     */
    public function edit($id)
    {
        $data['route_action'] = 'advertisement.list.update';
        $data['data']=Advertisement::where('id',$id)->with('city','category','attachments')->first();
        $state_id=$data['data']['city']['state_id'];
        $data['data']['state'] = StateTranslation::where('id',$state_id)->first();
        $ids=City::where('state_id',$state_id)->pluck('id');
        $data['data']['state']['cites'] = CityTranslation::whereIn('city_id',$ids)->get();
        $data['state']= StateTranslation::all();
        $data['params'] = ['id'=>$id];
        $data['id']=$id;
        return view('advertisement::advertisement.edit',$data);
    }
    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(Request $request)
    {
        if(isset ($request->datas)){
            $request['data'] = json_encode($request->datas);
        }
        $adv=Advertisement::find(($request->id))->update($request->all());
        Parent::multi_attachments_process($request,$adv);
        return redirect()->route('admin.advertisement.list');
    }
    /**
     * Show the specified resource.
     * @param Request $request
     * @return Response
     */
    public function show(Request $request)
    {
        $c=new Advertisement();
        if(isset($request->q)){
            $input = $request->q;
            $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->category_id)){
            $c=$c->where('category_id',$request->category_id);
        }
        if(isset($request->type)){
            $c=$c->where('type',$request->type);
        }
//        if(isset($request->cat_parent)){
//            $cats=Category::where('parent_id',$request->cat_parent)->pluck('id');
//            $c=$c->whereIn('category_id',$cats);
//        }
        if(isset($request->priority)){
            $c=$c->where('priority',$request->priority);
        }
        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->pricemin)){
            $c=$c->where('price','>',$request->pricemin);
        }
        if(isset($request->pricemax)){
            $c=$c->where('price','<',$request->pricemax);
        }
        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');
            }
        }
        $data=$c->with('user','offers','attachments','experience','comments')->orderBy('id','desc')->where('accept',1)->paginate(9);
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * Show the specified resource.
     * @param Request $request
     * @return Response
     */
    public function single(Request $request)
    {
       $data=Advertisement::with('user','offers','attachments','experience','comments')->where('id',$request->id)->first();
        $data->increment('hit');
       return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * Show the list of advertisements
     * @param Request $request
     * @return Response
     */
    public function CategoryAdv(Request $request)
    {
        if($request->id){
            $list=Category::find($request->id)->advertisement()->with('user')->where('accept',1)->orderBy('id','DESC')->paginate(9);
        }else{
            $list=Advertisement::with('user')->where('accept',1)->orderBy('id','DESC')->paginate(9);
        }
        return response()->json([
            'data'  => $list,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * this function used to like a advertisement
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    function like(Request $request){
        $adv = Advertisement::find($request->id);
        $like =  Advertisement::find($request->id)->like()->firstOrCreate([
            'user_id'=>Auth::user()->id
        ]);

        if($like->wasRecentlyCreated){
            $adv->increment('like');
        }else{
            $like->delete();
            $adv->decrement('like');
        }
        return response()->json([
            'data'  => true,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    function likedList(){
        $data = Like::where('likable_type','Modules\Advertisement\Entities\Advertisement')->where('user_id',Auth::user()->id)->with('likable')->paginate(9);
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * this function used to search
     * @param Request $request
     * @return array
     */
    function search(Request $request){
        $input = $request->q;
            $c=new Advertisement();
            $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->category_id)){
            $c=$c->where('category_id',$request->category_id);
        }
        if(isset($request->cat_parent)){
            $cats=Category::where('parent_id',$request->cat_parent)->pluck('id');
            $c=$c->whereIn('category_id',$cats);
        }
        if(isset($request->priority)){
            $c=$c->where('priority',$request->priority);
        }
        if(isset($request->city_id)){
            $c=$c->where('city_id',$request->city_id);
        }
        if(isset($request->type)){
            $c=$c->where('type',$request->type);
        }
        if(isset($request->state_id)){
            $cities=City::where('state_id',$request->state_id)->pluck('id');
            $c=$c->whereIn('city_id',$cities);
        }
        if(isset($request->pricemin)){
            $c=$c->where('price','>',$request->pricemin);
        }
        if(isset($request->pricemax)){
            $c=$c->where('price','<',$request->pricemax);
        }
        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');
            }
        }

        $data=$c->with('user','offers','attachments','experience','comments')->where('accept',1)->get();
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    static public function paid($json){
        $data=json_decode($json);
        $advertisement_id=$data->adv_id;

        if($data->type=='immediate'){
            $request['sort'] = 102;

        }elseif($data->type=='special'){
            $request['sort'] = 103;

        }elseif($data->type=='normal'){
            $request['sort'] = 101;

        }elseif($data->type=='immediate-special'){
            $request['sort'] = 104;
        }

        Advertisement::where('id',$advertisement_id)->first()->update(['status'=>1,'priority'=>$data->type ,'sort' =>  $request['sort']]);
    }

    public function list()
    {
            $types=Advertisement::groupBy('category_id')->get()->pluck('category_id');
            $array=array();
            foreach ($types as $type){
                $array[$type]=Advertisement::where('category_id',$type)->where('accept',1)->with('user','offers','attachments','experience','comments')->orderBy('id','desc')->take(5)->get();
            }
            $data['advertisement']= $array;

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

    public function related(Request $request)
    {
        $adv_id=$request->adv_id;
        $category_id=Advertisement::where('id',$adv_id)->first()->category_id;
        $data=Advertisement::where('category_id',$category_id)->where('id','!=',$adv_id)->where('accept',1)->with('user','offers','attachments','experience','comments')->orderBy('id','desc')->take(5)->get();
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    public function userAdvertisement()
    {
        $data= Advertisement::where('user_id',Auth::user()->id)->with('user','offers','attachments','experience','comments')->orderBy('id','desc')->paginate(9);
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    public function maxPrice()
    {
        $data= Advertisement::max('price');
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }

    public function delete(Request $request)
    {
        $adv=Advertisement::where('id',$request->id)->first();

        if($adv->user_id==Auth::user()->id){
            $adv->delete();
            return response()->json([
                'data'  => true,
                'message'=>'ok',
                'status' => 200
            ]);
        }else{
            return response()->json([
                'data'  => false,
                'message'=>'unauthenticated',
                'status' => 200
            ]);
        }
    }
    public function updateAdv(Request $request)
    {
        $adv=Advertisement::where('id',$request->id)->first();

        if($adv->user_id==Auth::user()->id){
            $request['user_id'] = Auth::user()->id;
            $request['accept'] = 0;

            if(isset ($request->datas)){
                $request['data'] = json_encode($request->datas);
                $data=Advertisement::where('id',$request->id)->first()->update($request->all());
            }else{
                $data=Advertisement::where('id',$request->id)->first()->update($request->all());
            }
            Parent::multi_attachments_process($request,$adv);
            return response()->json([
                'data'  => $data,
                'message'=>'ok',
                'status' => 200
            ]);
        }else{
            return response()->json([
                'data'  => false,
                'message'=>'unauthenticated',
                'status' => 200
            ]);
        }
    }

    public function advDeleteAttachment(Request $request)
    {
        $Attachment=Attachment::where('uid',$request->uid)->first();
        if($Attachment->attachmentable_type=='Modules\Advertisement\Entities\Advertisement'){
            $Attachment->attachmentable_id;
            $user_id=Advertisement::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
                ]);
            }
        }
    }
}
