<?php

namespace App\Core\Auth\Services;

use App\Core\Auth\Models\UserModel;
use Config\Database;

class AuthService
{
    public function attempt(string $email, string $password): bool
    {
        $users = new UserModel();
        $user = $users->findByEmail($email);

        if (! $user || $user['status'] !== 'active' || ! password_verify($password, $user['password_hash'])) {
            return false;
        }

        session()->set('core_user_id', (int) $user['id']);
        $users->update($user['id'], ['last_login_at' => date('Y-m-d H:i:s')]);

        return true;
    }

    public function logout(): void
    {
        session()->remove(['core_user_id', 'core_permissions']);
    }

    public function check(): bool
    {
        return (bool) session('core_user_id');
    }

    public function id(): ?int
    {
        return session('core_user_id') ? (int) session('core_user_id') : null;
    }

    public function user(): ?array
    {
        $id = $this->id();

        return $id ? (new UserModel())->find($id) : null;
    }

    public function permissions(): array
    {
        if (! $this->id()) {
            return [];
        }

        $rows = Database::connect()->table('core_permissions p')
            ->select('p.name')
            ->join('core_role_permissions rp', 'rp.permission_id = p.id')
            ->join('core_user_roles ur', 'ur.role_id = rp.role_id')
            ->where('ur.user_id', $this->id())
            ->get()
            ->getResultArray();

        return array_values(array_unique(array_column($rows, 'name')));
    }

    public function can(string $permission): bool
    {
        return in_array($permission, $this->permissions(), true);
    }
}
