<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthenticationController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function register(Request $request): JsonResponse
    {

        $this->validate($request, [
            'name' => 'required|max:255',
            'mobile' => 'required|unique:users,mobile|numeric',
            'email' => 'required|string|unique:users,email|max:255|email',
            'password' => 'required|string|min:8|max:25|confirmed',
        ]);
        $user = User::create([
            'name' => $request->input('name'),
            'mobile' => $request->input('mobile'),
            'email' => $request->input('email'),
            'address' => $request->input('address'),
            'latitude' => $request->input('latitude'),
            'usertype' => $request->input('usertype'),
            'longitude' => $request->input('longitude'),
            'password' => Hash::make($request->input('password')),
        ]);
        $token = $user->createToken('token')->plainTextToken;
        $response = [
            'user' => $user,
            'token' => $token,
        ];
        return response()->json($response, 201);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function logout(Request $request): JsonResponse
    {
        auth()->user()->tokens()->delete();
        return response()->json(['message' => 'Logout Successfully']);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function login(Request $request): JsonResponse
    {
        $request->validate([
            'email' => 'required|email|max:255',
            'password' => 'required|max:25|min:8',
        ]);
        $user = User::where('email', $request->input('email'))->first();

        if ($this->attemptLogin($request)) {
            return response()->json(
                [
                    'token' => $user->createToken($user->email)->plainTextToken,
                    'name' => $user->name,
                    'phone' => $user->mobile,
                    'email' => $user->email,
                    'id' => $user->id,
                    'usertype' => $user->usertype,
                    'longitude' => $user->longitude,
                    'latitude' => $user->latitude,
                    'address' => $user->address,
                ]
            );
        } else {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function change_password(Request $request): JsonResponse
    {
        $this->validate($request, [
            'password' => 'required|string|min:8|max:25|confirmed',
        ]);

        $data['password'] = Hash::make($request['password']);
        $user = User::findOrFail(auth()->user()->id);
        $user->update($data);
        return response()->json([
            'msg' => 'Password Reset Successfully'
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return JsonResponse
     */
    public function check_auth(): JsonResponse
    {
        $user = auth('sanctum')->user();
        if ($user) {
            return response()->json(['msg' => true]);
        } else {
            return response()->json(['msg' => false]);
        }
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function adminLogin(Request $request): JsonResponse
    {
        $request->validate([
            'email' => 'required|email|max:255',
            'password' => 'required|max:25|min:8',
        ]);
        $user = User::where('email', $request->email)->first();


        if ($this->attemptLogin($request) && $user->usertype == 1) {
            return response()->json(
                [
                    'token' =>$user->createToken($user->email)->plainTextToken,
                    'name'  => $user->name,
                    'phone'  => $user->phone,
                    'email'  => $user->email,
                    'id'  => $user->id,
                ]
            ) ;
        }else{
            throw ValidationException::withMessages([
                'email' => ['Sorry You are not an Admin'],
            ]);
        }
    }

    public function delete_account()
    {
        $user = User::findOrFail(auth()->user()->id);
        $user->status = 0;
        $user->previous_email = $user->email;
        $user->email = $this->checkPreviousUser();
        $user->save();
        auth()->user()->tokens()->delete();
        return response()->json(['message' => 'Your Account Deleted Successfully']);
    }
    /**
     * @return string
     */
    public function checkPreviousUser():string
    {
        $user = User::where('email', 'like', 'demo_%')->orderByDesc('email')->first();
        if ($user){
            $email = explode('@', $user);
            $email = explode('_', $email[0]);
            $count = $email[1]+1;
            return 'demo_'.$count.'@gmail.com';
        }
        return 'demo_1@gmail.com';
    }
}
