<?php

namespace App\Services\Repositories;

use App\Models\Banner;
use App\Models\BannerDescription;
use App\Services\Interfaces\BannerRepositoryInterface;
use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class BannerRepository implements BannerRepositoryInterface
{
    public function get(Request $request)
    {
        $query = Banner::orderBy('id', 'ASC')
            ->join('banner_descriptions AS pd', 'banners.id', 'pd.banner_id')
            ->join('languages', 'languages.id', 'pd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['pd.name', 'banners.*']);

        if ($request->name) {
            $query->where('pd.name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->date_from) {
            $query->whereDate('banners.created_at', '>=', $request->date_from);
        }

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

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

        if ($request->id) {
            $result= $query->findOrFail($request->id);
        }elseif ($request->paginate ?? null) {
            $result=  $query->paginate(50);
        }else{
            $result= $query->get();
        }

        return $result;
    }

    public function getItemById(int $bannerId):Banner
    {
        $banner = Banner::findOrFail($bannerId);
        $query = BannerDescription::where('banner_id', $banner->id)
            ->join('languages', 'languages.id', 'banner_descriptions.language_id')
            ->select(['banner_descriptions.*', 'languages.local']);

        $bannerDescription= $query->get();
        // dd($bannerDescription->toArray());
        foreach ($bannerDescription as $row) {
            $banner[$row->local]= $row;
        }
        return $banner ;
    }

    public function getItem(Banner $banner):Banner
    {
        $query = BannerDescription::where('banner_id', $banner->id)
            ->join('languages', 'languages.id', 'banner_descriptions.language_id')
            ->select(['banner_descriptions.*', 'languages.local']);

        $bannerDescription= $query->get();
        // dd($bannerDescription->toArray());
        foreach ($bannerDescription as $row) {
            $banner[$row->local]= $row;
        }
        return $banner ;
    }

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

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

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

    /**
     * Remove several banners by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function destroyAll(Request $request) :array
    {
        // return [ ['message'=> __('dashboard.noResult')], 400];
        $ids= $request->ids;
        $query= Banner::whereIn('id', $ids) ->where('id', '!=', 1);
        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 banner from storage.
     *
     * @param Request $request
     * @param int $id
     * @return array
     */
    public function restore(Request $request, int $id) :array
    {
        $banner= Banner::withTrashed()->find($id);
        if ($banner) {
            $banner->restore();
            return [['message'=> __('dashboard.saveDone')]];
        }
        return [['message'=> __('dashboard.noResult')], 400];

    }

    /**
     * Restore several banners by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function restoreAll(Request $request) :array
    {
        $ids= $request->ids;
        Banner::whereIn('id', $ids)->onlyTrashed()->restore();
        return [['message'=> __('dashboard.saveDone')]];
    }

}
