<?php

namespace App\Http\Controllers\API;

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

class AuthController extends Controller
{
    /**
     * Login The User
     * @param Request $request
     * @return User
     */
    public function login(Request $request): JsonResponse
    {
        try {

            $request->validate([
                'phone' => 'required|string',
                'password' => 'required',
                'fcm' => 'sometimes|string'
            ]);

            // Check phone
            $user = User::where('phone', $request->phone)->first();
            // Check user and password
            if (is_null($user) || !Hash::check($request->password, $user->password)) {
                return response()->failed('Credentials are not correct.');
            }
            // Check if the user is blocked
            if ($user->isBlocked()) {
                return response()->failed('Your account is blocked. Please contact support for assistance.');
            }
            // Check if the user role is "agent"
            if (!$user->isAgent()) {
                return response()->falied('You are not authorized to access this resource.');
            }

            // creating token
            $token = $user->createToken('myapptoken')->plainTextToken;

            if (filled($request->fcm)) {
                $user->fcm = $request->fcm;
                $user->save();
            }

            return response()
                ->success('User logged in Successfully', [
                    'token' => $token,
                    'user' => $user
                ]);
        } catch (\Throwable $th) {
            return response()->failed($th->getMessage());
        }
    }

    public function logout(Request $request): JsonResponse
    {
        /**
         * @var User  $user
         */
        $user = Auth::user();
        $user->fcm = null;
        $user->save();
        $request->user()->tokens()->delete();
        return response()->success('Logged out successfully');
    }
}
