<?php

namespace Modules\Bank\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Bank\Interfaces\BankRepositoryInterface;
use Modules\Bank\Models\Bank;
use Modules\Bank\Models\BankDescription;

class BankRepository implements BankRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Bank::query()
            ->join('bank_descriptions AS sd', 'banks.id', 'sd.bank_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'banks.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return BankDescription::where('bank_id', $id)
            ->join('languages', 'languages.id', 'bank_descriptions.language_id')
            ->join('banks', 'banks.id', 'bank_descriptions.bank_id')
            ->select(['bank_descriptions.*', 'languages.local','banks.*'])->get();
    }

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

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

    public function create(array $request): Bank
    {
        $bank = Bank::create($request);
        return $bank;
    }

    public function update(array $request, ?Bank $bank): Bank
    {
        $bank->update($request);

        return $bank;
    }

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

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

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

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