<?php

namespace Modules\Package\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Package\Interfaces\PackageRepositoryInterface;
use Modules\Package\Models\Package;
use Modules\Package\Models\PackageDescription;

class PackageRepository implements PackageRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Package::query()
            ->join('package_descriptions AS sd', 'packages.id', 'sd.package_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'packages.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return PackageDescription::where('package_id', $id)
            ->join('languages', 'languages.id', 'package_descriptions.language_id')
            ->join('packages', 'packages.id', 'package_descriptions.package_id')
            ->select(['package_descriptions.*', 'languages.local','packages.*'])->get();
    }

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

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

    public function create(array $request): Package
    {
        $package = Package::create($request);
        return $package;
    }

    public function update(array $request, ?Package $package): Package
    {
        $package->update($request);

        return $package;
    }

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

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

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

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