<?php

namespace Modules\Coupon\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Coupon\Interfaces\CouponRepositoryInterface;
use Modules\Coupon\Models\Coupon;
use Modules\Coupon\Models\CouponDescription;

class CouponRepository implements CouponRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Coupon::query()
            ->join('coupon_descriptions AS sd', 'coupons.id', 'sd.coupon_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'coupons.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return CouponDescription::where('coupon_id', $id)
            ->join('languages', 'languages.id', 'coupon_descriptions.language_id')
            ->join('coupons', 'coupons.id', 'coupon_descriptions.coupon_id')
            ->select(['coupon_descriptions.*', 'languages.local','coupons.*'])->get();
    }

    public function checkItem(int $id)
    {
        return Coupon::find($id);
    }

    public function getItemByCode(string $code)
    {
        return Coupon::where('code',$code)->first();
    }

    public function getItemTrashed(int $id)
    {
        $coupon = Coupon::onlyTrashed()->find($id);
        return $coupon ;
    }

    public function create(array $request): Coupon
    {
        $coupon = Coupon::create($request);
        return $coupon;
    }

    public function update(array $request, ?Coupon $coupon): Coupon
    {
        $coupon->update($request);

        return $coupon;
    }

    public function saveData(array $request, int $coupon_id ) :void
    {
        CouponDescription::where('coupon_id', $coupon_id)->delete();
        foreach (languages() as $lang) {
            $data=[
                'coupon_id'=> $coupon_id,
                'language_id'=> $lang->id,
                'title'=> $request['title_'.$lang->local],
            ];
            CouponDescription::create($data);
        }
    }
    /**
     * Remove the specified coupon from storage.
     * @param Coupon $coupon
     * @return void
     */
    public function destroy(Coupon $coupon) :void
    {
        $coupon->delete();
    }

    /**
     * Remove several coupons by IDs.
     *
     * @param array $request
     * @return void
     */
    public function destroyAll(array $ids) :void
    {
         Coupon::whereIn('id', $ids)->delete();
    }

    /**
     * Restore the specified coupon from storage.
     *
     * @param Coupon $coupon
     * @return void
     */
    public function restore(Coupon $coupon) :void
    {
        $coupon->restore();
    }

    /**
     * Restore several coupons by IDs.
     *
     * @param array $request
     * @return void
     */
    public function restoreAll(array $ids) :void
    {
        Coupon::whereIn('id', $ids)->onlyTrashed()->restore();
    }
}
