<?php

namespace Modules\User\Repositories;

use App\Models\UserModule;
use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Interfaces\UserRepositoryInterface;
use Modules\User\Models\User;
use Modules\User\Models\UserCanteenModule;
use Modules\User\Models\UserDescription;

class UserRepository implements UserRepositoryInterface
{
    public function get(array $request)
    {
        $builder = User::query();
        return $builder;
    }

    public function getItem(int $id)
    {
        return User::find($id);
    }

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

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

    public function create(array $request): User
    {
        $user = User::create($request);
        return $user;
    }
    public function canteenUser(int $id)
    {
        return User::where('role',UserRoleEnum::CANTEEN->value)->where('canteen_id', $id)->first();
    }

    public function update(array $request, User $user): User
    {
        $user->update($request);

        return $user;
    }

    public function saveData(array $request, $user_id)
    {
        UserModule::where('user_id', $user_id)->delete();
        if (@$request['modules']) {
            foreach ($request['modules'] as $module_id) {
                UserModule::create([
                    'module_id' => $module_id,
                    'user_id' => $user_id
                ]);
            }
        }
    }
    public function saveDataCanteen(array $request, $user_id)
    {
        UserCanteenModule::where('user_id', $user_id)->delete();
        if (@$request['canteen_modules']) {
            foreach ($request['canteen_modules'] as $module_id) {
                UserCanteenModule::create([
                    'canteen_module_id' => $module_id,
                    'user_id' => $user_id
                ]);
            }
        }
    }

    /**
     * Remove the specified user from storage.
     * @param User $user
     * @return void
     */
    public function destroy(User $user): void
    {
        $user->delete();
    }

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

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

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