<?php
namespace Core;

use Core\Session;
use Core\Cookie; // optional if you want remember me
use App\Models\User; // changed to user model
use function Core\Helpers\sanitize;
class Auth
{
    /**
     * Attempts to log in an user with email and password.
     *
     * @param string $email
     * @param string $password
     * @return bool
     */
    public static function attempt(string $email, string $password): bool
    {
        $user = User::where('email', sanitize($email));

        if (!$user) {
            return false;
        }

        if (!password_verify($password, $user['password'])) {
            return false;
        }

        Session::start();
        Session::set('user_id', $user['id']);
        $name = (!empty($user['first_name']) || !empty($user['last_name']))
            ? trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''))
            : ($user['full_name'] ?? 'User');

        Session::set('name', $name);
        // Session::set('name', $user['name']);
        


        return true;
    }

    public static function attemptById(int $userId): bool
    {
        $user = User::find($userId);

        if (!$user) {
            return false;
        }

        Session::start();
        Session::set('user_id', $user['id']);
        // Session::set('name', $user['name']);
        Session::set('name', $user['first_name'] . ' ' . $user['last_name']);

        return true;
    }

    /**
     * Check if an user is logged in
     *
     * @return bool
     */
    public static function check(): bool
    {
        Session::start();
        return Session::get('user_id') !== null;
    }

    /**
     * Get the current logged-in user
     *
     * @return array|null
     */
    public static function user()
    {
        if (!self::check()) {
            return null;
        }
        Session::start();

        $user_id =  Session::get('user_id') ?? null;

        return User::find($user_id) ?? [];
    }

    public static function id(): ?int
    {
        if (!self::check()) {
            return null;
        }
        Session::start();

        return Session::get('user_id') ?? null;
    }
    /**
     * Logout the user
     */
    public static function logout(): void
    {
        Session::destroy();
    }
}
