<?php

namespace App\Service\Admin;

use App\Models\Admin;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

use App\Traits\JsonResponseTrait;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;

class AuthService
{
    use JsonResponseTrait;
    public function createAdmin(array $data)
    {
        $data['password'] = Hash::make($data['password']);
        $admin = Admin::create($data);
        return $this->successDataResponse(data: $admin, message: "Created successfully");
    }

    public function login(array $credentials)
    {
        $user = Admin::where('email', $credentials['email'])->first();
        // Check if user exists and password is correct
        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            return $this->errorResponse(statusCode: 401, message: 'Invalid email or password');
        }

        $token = JWTAuth::claims(['admin_id' => $user->admin_id])->fromUser($user);
        return $this->successDataResponse(data: ['admin' => $user, 'accessToken' => $token], message: "login successful");
    }

    // public function changePassword(string $oldPassword, string $newPassword)
    // {
    //     if (!Hash::check($oldPassword, $admin->password)) {
    //         return false; // Incorrect old password
    //     }

    //     $admin->password = Hash::make($newPassword);
    //     $admin->save();

    //     return true;
    // }

    public function resetPassword(Admin $admin, string $newPassword)
    {
        $admin->password = Hash::make($newPassword);
        $admin->save();

        return true;
    }
}
