<?php

namespace App\Http\Controllers;

use App\Http\Requests\Auth\ChangePasswordRequest;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Requests\Auth\SignUpRequest;
use App\Http\Requests\Auth\UserIdRequest;
use App\Http\Requests\FCM\NotificationUpdatefcmtokenRequest;
use App\Http\Resources\Auth\LoginResource;

use App\Repositories\PublicRepository;

use App\Models\User;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;

use Illuminate\Validation\ValidationException;
use PhpParser\Node\Expr\FuncCall;

class AuthController extends Controller
{
    public function __construct(public PublicRepository $publicRepository) {}

    public function login(LoginRequest $request)
    {
        $arr = Arr::only($request->validated(), ['email', 'password']);
        $where = ['email' => $arr['email']];

        $user = $this->publicRepository->ShowAll(User::class, $where)->first();

        if (!Hash::check($arr['password'], $user->password)) {
            throw ValidationException::withMessages([__('public.password_wrong')]);
        }
        $user['token'] = $user->createToken('authToken');

        if ($user->getRoleNames()[0]) {
            $user['role'] = $user->getRoleNames()[0];
        } else {
            $user['role'] = null;
        }

        return \SuccessData(__('public.login'), new LoginResource($user));
    }
    public function SignUp(SignUpRequest $request)
    {
        try {
            $userArr = Arr::only(
                $request->validated(),
                ['email', 'password', 'name', 'phone']
            );
            $user = $this->publicRepository->Create(User::class, $userArr);
            $user->assignRole('admin');
            return \Success(__('public.register'));
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Registration failed: ' . $e->getMessage(),
                'code' => 500,
                'data' => null,
            ], 500);
        }
    }
    public function Admins()
    {
        $admins = User::role('admin')->get();
        return \SuccessData(__('public.Show'), $admins);
    }
    public function DeleteAdmin(UserIdRequest $request)
    {
        $arr = Arr::only($request->validated(), ['userId']);
        $user = $this->publicRepository->ShowById(User::class, $arr['userId']);
        $user->tokens()->where('scopes')->delete();
        $user->delete();
        return \Success(__('public.Delete'));
    }
    public function Logout()
    {
        $user = auth()->user();
        $user->tokens()->where('scopes')->delete();
        return \Success(__('public.logout'));
    }


    public function updateFcmToken(NotificationUpdatefcmtokenRequest $request)
    {
        $userArr = Arr::only(
            $request->validated(),
            ['fcm_token']
        );
        $user = \Auth::user();
        $user->fcm_token = $userArr['fcm_token'];
        $user->save();
        return \Success(__('public.Show'));
    }



    public function loginError()
    {
        return response()->json([
            'success' => false,
            'message' => 'تحتاج الى تسجيل دخول قبل القيام بهذا الأمر ',
            'code' => 403,
        ], 403);
    }

    public function SelfChangePassword(ChangePasswordRequest $request)
    {
        $arr = Arr::only($request->validated(), ['old_password', 'new_password']);
        $person = \auth()->user();
        $model = get_class($person);
        if (!Hash::check($arr['old_password'], $person->password)) {
            throw ValidationException::withMessages([__('public.authFailed')]);
        }
        $this->publicRepository->update($model, $person->id, ['password' => $arr['new_password']]);
        $person->tokens()->delete();
        return \Success(__('public.password_update'));
    }
}
