<?php
namespace App\Models;

use App\Core\Database;
use PDO;

class User
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function attempt(string $email, string $password): ?array
    {
        $stmt = $this->db->prepare("
            SELECT * FROM users
            WHERE email = :email
            AND is_active = 1
            LIMIT 1
        ");
        $stmt->execute([':email' => $email]);
        $user = $stmt->fetch();

        if (!$user) {
            return null;
        }

        // IMPORTANT: use password_hash column
        if (!password_verify($password, $user['password_hash'])) {
            return null;
        }

        return [
            'id'         => $user['id'],
            'org_id'     => $user['org_id'],
            'email'      => $user['email'],
            'first_name' => $user['first_name'],
            'last_name'  => $user['last_name'],
            'role'       => $this->mapRole((int)$user['role_id']),
            'lang'       => $user['preferred_lang'] ?? 'en'
        ];
    }

    private function mapRole(int $roleId): string
    {
        return match ($roleId) {
            1 => 'superadmin',
            2 => 'conference_chair',
            3 => 'track_chair',
            4 => 'reviewer',
            5 => 'author',
            default => 'guest'
        };
    }
}
