<?php

namespace App\Http\Controllers\Api;

use App\Enums\UserRole;
use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\RegisterUserRequest;
use App\Mail\ForgotPasswordMail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class AuthController extends Controller
{
    public function register(RegisterUserRequest $request)
    {
        User::create($request->validated())->refresh();

        return ApiResponse::created("Registered successfully!");
    }

    public function login(Request $request)
    {
        $request->validate([
            "email" => "sometimes|email",
            'password' => 'required|string'
        ]);

        // Check email
        if ($request->has('email')) {
            $user = User::where('email', $request->email)->first();
        } elseif ($request->has('phone')) {
            $user = User::where('phone', $request->phone)->first();
        } else {
            return ApiResponse::unauthorized('Invalid credentials!!');
        }

        // Check password
        if (!$user || !Hash::check($request->password, $user->password)) {
            return ApiResponse::unauthorized('Invalid credentials!!');
        }

        // delete previous tokens and generate a new token
        $user->tokens()->delete();
        $token = $user->createToken('app_token')->plainTextToken;


        return ApiResponse::success([
            "user" => $user,
            "token" => $token
        ], "Login successfully!");
    }


    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();

        return ApiResponse::noContent();
    }

    public function forgotPassword(Request $request)
    {
        $fields = Validator::make($request->all(), [
            'email' => 'required|string|email',
        ]);

        if ($fields->fails()) {
            return response()->json(['error' => $fields->errors()], 422);
        }

        $user = User::where('email', $request->email)->first();

        if (!isset($user)) {
            return ApiResponse::success("Password reset link has been sent to the provided email if it exists in our system");
        }

        $user->forgot_password_token = Str::random(32);
        Mail::to($user->email)->send(new ForgotPasswordMail($user));
        $user->save();

        return ApiResponse::success('Password reset link has been sent to your registered email id. Click on it to reset your password.');
    }

    public function updatePassword(Request $request)
    {
        $fields = Validator::make($request->all(), [
            'token' => 'required|string',
            'password' => 'required|string',
            'confirmation_password' => 'required|string|same:password'
        ]);

        if ($fields->fails()) {
            return ApiResponse::validationError($fields->errors());
        }

        $user = User::where('forget_password_token', $request->token)->first();

        if (!$user) {
            return ApiResponse::unauthorized('User does not exists or token expired');
        }

        $user->password = $request->password;
        $user->save();
        return ApiResponse::success('Password changed successfully');
    }

    public function profile()
    {
        return ApiResponse::success(auth()->user());
    }
}
