<?php

namespace Modules\Shipping\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Shipping\Interfaces\ShippingRepositoryInterface;
use Modules\Shipping\Models\Shipping;
use Modules\Shipping\Models\ShippingCity;
use Modules\Shipping\Models\ShippingDescription;

class ShippingRepository implements ShippingRepositoryInterface
{
    public function get(Request $request)
    {
        $query = Shipping::orderBy('id', 'DESC')
            ->join('shipping_descriptions AS sd', 'shippings.id', 'sd.shipping_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'shippings.*']);

        if ($request->title) {
            $query->where('sd.title', 'LIKE', '%'.$request->title.'%');
        }
        if ($request->city_id)
        {
            $query->whereHas('cities',function ($q) use ($request){
                $q->where('city_id',$request->city_id);
            });
        }
        if ($request->date_from) {
            $query->whereDate('shippings.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('shippings.created_at', '<=', $request->date_to);
        }


        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        if ($request->paginate ?? null) {
            $shippings= $query->paginate(50);
        }else{
            $shippings=$query->cursor();
        }

        return $shippings;
    }

    public function getCity(ShippingCity $shippingCity)
    {
        return $shippingCity;
    }
    public function getItem(Shipping $shipping)
    {
        $query = ShippingDescription::where('shipping_id', $shipping->id)
            ->join('shippings', 'shippings.id', 'shipping_descriptions.shipping_id')
            ->join('languages', 'languages.id', 'shipping_descriptions.language_id')
            ->select(['shippings.*','shipping_descriptions.title', 'languages.local']);

        $shippingDescription= $query->get();
        foreach ($shippingDescription as $key=>$row) {
            if ($row->local == getCurrentLocale())
            {
                $shipping = $row;
            }
            $shipping[$row->local] = $row;
        }
        return $shipping ;
    }

    public function cities(Shipping $shipping)
    {
        return ShippingCity::where('shipping_id',$shipping->id)->cursor();
    }

    //
    public function save(Request $request, ?Shipping $shipping): Shipping
    {
        $data= $request->all();
        unset($data['id']);// for security reasons
        if (!$shipping) {
            $shipping = Shipping::create($data);
        } else {
            $shipping->update($data);
            ShippingDescription::where('shipping_id', $shipping->id)->delete();
//            ShippingCity::where('shipping_id', $shipping->id)->delete();
        }
        $this->saveData( $request, $shipping->id );
        return $shipping;
    }

    private function saveData(Request $request, int $shipping_id ) :void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'shipping_id'=> $shipping_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
            ];

            ShippingDescription::create($data);
        }

        if (isset($requestData['cities']))
        {
            foreach ($requestData['cities'] as $row)
            {
                ShippingCity::create([
                    'shipping_id'=>$shipping_id,
                    'city_id'=>$row['city_id'],
                    'cost'=>$row['cost']
                ]);
            }
        }
    }
    /**
     * Remove the specified client from storage.
     * @param Request $request
     * @param int $id
     * @return array
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :array
    {
        $shipping= Shipping::withTrashed()->find($id);
        if ($shipping) {
            if ($shipping->deleted_at) {
                $shipping->forceDelete();
            } else {
                $shipping->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= Shipping::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
    {
        $shipping= Shipping::withTrashed()->find($id);
        if ($shipping) {
            $shipping->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;
        Shipping::whereIn('id', $ids)->onlyTrashed()->restore();
        return [['message'=> __('dashboard.saveDone')]];
    }
}

