<?php

namespace App\Http\Controllers;

use App\Facades\File\FileFacade;
use App\Http\Requests\Profile\ChangeAvatarRequest;
use App\Http\Requests\Profile\ChangePasswordRequest;
use App\Http\Resources\Admin\UserResource;
use App\Http\Traits\ApiResponse;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class ProfileController extends Controller
{
    use ApiResponse;

    public function info(): JsonResponse
    {
        return $this->successResponse(new UserResource(auth()->user()));
    }

    public function changePassword(ChangePasswordRequest $request): JsonResponse
    {
        $user = auth()->user();
        if (! Hash::check($request->current_password, $user->passwored)){
            return $this->errorResponse(__('messages.wrong_current_password'));
        }
        $user->update([
            'password' => Hash::make($request->new_password)
        ]);

        return $this->successResponse();
    }

    public function changeAvatar(ChangeAvatarRequest $request): JsonResponse
    {
        $user = auth()->user();

        if ($user->avatar){
            FileFacade::delete($user->avatar, true);
        }

        $user->update([
            'avatar' => FileFacade::save($request->file('avatar'), 'users/avatars/' . $request->username)
        ]);

        return $this->successResponse();
    }

    public function online(Request $request): JsonResponse
    {
        User::query()
            ->firstWhere('telephone_id', '=', $request->telephone_id)
            ->update(['is_online' => true,]);

        return $this->successResponse();
    }

    public function offline(Request $request): JsonResponse
    {
        User::query()
            ->firstWhere('telephone_id', '=', $request->telephone_id)
            ->update(['is_online' => false]);

        return $this->successResponse();
    }

    public function permissions(): JsonResponse
    {
        return $this->successResponse(auth()->user()->getAllPermissions()->pluck('name'));
    }
}
