<?php

namespace App\Repositories;


use App\Models\Product;

use App\Models\User;
use App\Models\UserAgent;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\WalkThrough;

use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;


/**
 * Class AppConfigurationRepository
 */
class UserRepository extends BaseRepository
{
    public $fieldSearchable = [
        'key',
    ];

    /**
     * @inheritDoc
     */
    public function getFieldsSearchable()
    {
        return $this->fieldSearchable;
    }

    /**
     * @inheritDoc
     */
    public function model()
    {
        return UserAgent::class;
    }

    /**
     * @param $input
     *
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|void
     */

    public function changePassword($input)
    {
        try {
            /** @var User $user */
            $user = Auth::user();
            
            if (!Hash::check($input['password_current'], $user->password)) {
                throw new UnprocessableEntityHttpException('Current password is invalid.');
            }
            $input['password'] = Hash::make($input['password']);
            $user->update($input);

            return true;
        } catch (Exception $e) {
            throw new UnprocessableEntityHttpException($e->getMessage());
        }
    }

    public function update($input,$id)
    {
        try {
            DB::beginTransaction();
            $userAgent = UserAgent::findOrFail($id);
            $userAgent->update($input);

            DB::commit();

            return $userAgent;
        } catch (Exception $e) {
            DB::rollBack();

            throw new UnprocessableEntityHttpException($e->getMessage());
        }
    }

    /**
     * @param $userInput
     * @return bool
     */
    public function updateProfile($userInput)
    {
        try {
            DB::beginTransaction();

            $user = Auth::user();

            $user->update($userInput);

            if ((!empty($userInput['image']))) {
                $user->clearMediaCollection(User::USER_IMAGE);
                $user->media()->delete();
                $user->addMedia($userInput['image'])->toMediaCollection(User::USER_IMAGE, config('app.media_disc'));
            }

            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();

            throw new UnprocessableEntityHttpException($e->getMessage());
        }
    }
}
