<?php

namespace Modules\Store\Repositories;

use Illuminate\Http\Request;
use Modules\Store\Interfaces\StoreRepositoryInterface;
use Modules\Store\Models\Store;
use Modules\Store\Models\StoreWork;
use Modules\Store\Models\Favorite;

class StoreRepository implements StoreRepositoryInterface
{

    public function get(Request $request)
    {
        $query = Store::with(['subCategory','category','branches']);

        if ($request->name)
        {
            $query->where('name','LIKE', '%'.$request->name.'%');
        }
        if($request->category_id)
        {
            $query->where('category_id',$request->category_id);
        }
        if($request->sub_category_id)
        {
            $query->where('sub_category_id',$request->sub_category_id);
        }
        
        if($request->city_id)
        {
            $query->whereHas('branches', function($q) use($request){
                $q->where('city_id', $request->city_id);
            });
        }
        
        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
        
        if($request->ids)
        {
            // $query->whereIn('id',$request->ids);
            $query->whereRaw("id IN (".implode(',', $request->ids).")");
        }
        
        if($request->status_available)
        {
            $query->where('status_available',$request->status_available);
        }
        
        
        if($request->rate)
        {
            $ids = $this->rateId($request->rate);
            $query->whereRaw("id IN (".implode(',', $ids).")");
        }
        
        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }
        
        if($request->orderBy)
        {
            if($request->orderBy == 'ASC')
            {
                $query->orderBy('id','ASC');
            }
            elseif($request->orderBy == 'DESC')
            {
                $query->orderBy('id','DESC');
            }
            elseif($request->orderBy == 'rate')
            {
                $orderedIds = $this->orderByIds($request);
                $query->orderByRaw("field(id,".$orderedIds.")");
            }
            elseif($request->orderBy == 'delivery_time')
            {
                $query->join('branches', 'stores.id', '=', 'branches.store_id')
                    ->where('branches.city_id', $request->city_id)
                    ->orderBy('branches.time_delivery', 'asc') 
                    ->select('stores.*');
            }
        }
        else
        {
            $query->orderBy('id','DESC');
        }
        
        if ($request->paginate ?? null) {
            $stores= $query->paginate(50);
        }else{
            $stores=$query->get();
        }
        
        return $stores;
    }
    
    public function orderByIds(Request $request)
    {
        $query = Store::query();
          
        if ($request->name)
        {
            $query->where('name','LIKE', '%'.$request->name.'%');
        }
        if($request->category_id)
        {
            $query->where('category_id',$request->category_id);
        }
        if($request->sub_category_id)
        {
            $query->where('sub_category_id',$request->sub_category_id);
        }
        
        if($request->city_id)
        {
            $query->whereHas('branches', function($q) use($request){
                $q->where('city_id', $request->city_id);
            });
        }
        
        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
        
        if($request->ids)
        {
            // $query->whereIn('id',$request->ids);
            $query->whereRaw("id IN (".implode(',', $request->ids).")");
        }
        
        if($request->status_available)
        {
            $query->where('status_available',$request->status_available);
        }

        if($request->rate)
        {
            $ids = $this->rateId($request->rate);
            $query->whereRaw("id IN (".implode(',', $ids).")");
        }
       

        
        $products=$query->get();
        
        $products = $products->sortByDESC('rate');
          
        $ids = $products->pluck('id')->toArray();
        if (count($ids) == 0)
        {
            $ids = ['0'];
        }
        $orderedIds = implode(',', $ids );
        return $orderedIds;
    }
    public function rateId($rate)
    {
        $ids = [];
        $stores = Store::cursor();
        foreach($stores as $row)
        {
            if($row->rate == $rate)
            {
                array_push($ids,$row->id);
            }
        }
        if(count($ids) == 0)
        {
            $ids = ['0'];
        }
        return $ids;
    }

    public function getItem(Store $store)
    {
        $store = Store::with(['subCategory','category','branches'])->find($store->id);
        return $store ;
    }

    //
    public function save(Request $request, ?Store $store): Store
    {
        $data= $request->all();
        unset($data['id']);// for security reasons
        if (!$store) {
            $store = Store::create($data);
        } else {
            if(isset($data['days']))
            {
                StoreWork::where('store_id',$store->id)->delete();
            }
            $store->update($data);
        }
        $this->saveData($request,$store->id);
        return $store;
    }

    private function saveData(Request $request, int $store_id ) :void
    {
        $requestData= $request->all();

        if (isset($requestData['days']))
        {
            foreach ($request->days as $key=>$row)
            {
                StoreWork::create([
                    'start_time' => $row['start_time'],
                    'end_time' => $row['end_time'],
                    'store_id' => $store_id,
                    'day' => $key,
                ]);
            }
        }
    }
    public function products(Store $store)
    {
        $products = StoreProduct::where('store_id',$store->id)->cursor();
        return $products;
    }

    /**
     * Remove the specified client from storage.
     * @param Request $request
     * @param int $id
     * @return array
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :array
    {
        $store= Store::withTrashed()->find($id);
        if ($store) {
            if ($store->deleted_at) {
                $store->forceDelete();
            } else {
                $store->delete();
            }
            return [ ['message'=> __('dashboard.deletedDone')]];
        } else{
            return [ ['message'=> __('dashboard.noResult')], 400];
        }
    }

    /**
     * Remove several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function destroyAll(Request $request) :array
    {
        $ids= $request->ids;
        $query= Store::whereIn('id', $ids);
        if ($request->force) {
            $deleted= $query->onlyTrashed()->forceDelete();
        } else {
            $deleted= $query->delete();
        }
        if($deleted){
            return [['message'=> __('dashboard.deletedDone')]];
        }
        return [ ['message'=> __('dashboard.noResult')], 400];
    }

    /**
     * Restore the specified client from storage.
     *
     * @param Request $request
     * @param int $id
     * @return array
     */
    public function restore(Request $request, int $id) :array
    {
        $store= Store::withTrashed()->find($id);
        if ($store) {
            $store->restore();
            return [['message'=> __('dashboard.saveDone')]];
        }
        return [['message'=> __('dashboard.noResult')], 400];

    }


    /**
     * Restore several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function restoreAll(Request $request) :array
    {
        $ids= $request->ids;
        Store::whereIn('id', $ids)->onlyTrashed()->restore();
        return [['message'=> __('dashboard.saveDone')]];
    }
    
    public function updateWorkTime(Request $request, int $id) 
    {
        $store= StoreWork::find($id);
        $store->update($request->all());
    }
    
    
    public function checkFavorite(Request $request) 
    {
        $fav = Favorite::where('user_id',$request->user_id)
                ->where('status',$request->status)
                ->where('store_id',$request->store_id)
                ->first();
        return $fav;
    }
    
    public function deleteFavorite($favorite) 
    {
        $favorite->delete();
    }

    public function saveFavorite(Request $request) 
    {
        Favorite::create([
                'user_id'=>$request->user_id,
                'status'=>$request->status,
                'store_id'=>$request->store_id,
            ]);
    }
    
    public function favoriteIds(Request $request) 
    {
        $ids = Favorite::where('user_id',$request->user_id)
                ->where('status',$request->status)
                ->where('user_id',$request->user_id)
                ->pluck('store_id')->toArray();
        if(count($ids) == 0)
        {
            $ids = ['0'];
        }
        return $ids;
    }


}
