<?php

namespace App\Services;

use App\Repositories\UserRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthService
{
    protected $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function register(array $data): User
    {
        $data['password'] = Hash::make($data['password']);
        return $this->userRepository->create($data);
    }

    public function login(array $credentials): bool
    {
        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            if ($user->status != 1) {
                Auth::logout();
                throw new \Exception('Your account is blocked. Please contact the administrator.');
            }
            return true;
        }
        return false;
    }

    public function logout(): void
    {
        Auth::logout();
    }

    public function updateProfile(int $userId, array $data): bool
    {
        return $this->userRepository->update($userId, $data);
    }

    public function updatePassword(int $userId, string $oldPassword, string $newPassword): bool
    {
        $user = $this->userRepository->find($userId);
        
        if (!Hash::check($oldPassword, $user->password)) {
            throw new \Exception('Old password does not match.');
        }

        return $this->userRepository->update($userId, ['password' => Hash::make($newPassword)]);
    }
}
