<?php

namespace App\Models;

class User extends BaseModel
{
    public function find(int $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT u.id, u.name, u.login_id, u.email, u.active FROM users u WHERE u.id = :id LIMIT 1');
        $stmt->execute(['id' => $id]);
        return $stmt->fetch() ?: null;
    }

    public function findByLoginId(string $loginId): ?array
    {
        $stmt = $this->pdo->prepare('SELECT u.*, r.name AS role_name FROM users u 
            JOIN roles r ON r.id = u.role_id WHERE u.login_id = :login_id LIMIT 1');
        $stmt->execute(['login_id' => $loginId]);
        $user = $stmt->fetch();
        if ($user) {
            $user['role'] = $user['role_name'];
        }
        return $user ?: null;
    }

    public function all(): array
    {
        $stmt = $this->pdo->query('SELECT u.id, u.name, u.login_id, u.email, r.name AS role, u.active, u.created_at
            FROM users u JOIN roles r ON r.id = u.role_id ORDER BY u.name ASC');
        return $stmt->fetchAll();
    }

    public function create(array $data): void
    {
        $stmt = $this->pdo->prepare('INSERT INTO users (name, login_id, email, password, role_id, active)
            VALUES (:name, :login_id, :email, :password, :role_id, :active)');
        $stmt->execute([
            'name' => $data['name'],
            'login_id' => $data['login_id'],
            'email' => $data['email'] ?? null,
            'password' => password_hash($data['password'], PASSWORD_BCRYPT),
            'role_id' => $data['role_id'],
            'active' => $data['active'] ?? 1,
        ]);
    }

    public function resetPassword(int $id, string $password): void
    {
        $stmt = $this->pdo->prepare('UPDATE users SET password = :password WHERE id = :id');
        $stmt->execute([
            'password' => password_hash($password, PASSWORD_BCRYPT),
            'id' => $id,
        ]);
    }

    public function update(int $id, array $data): void
    {
        $stmt = $this->pdo->prepare('UPDATE users SET name = :name, email = :email, active = :active WHERE id = :id');
        $stmt->execute([
            'name' => $data['name'],
            'email' => $data['email'],
            'active' => $data['active'],
            'id' => $id,
        ]);
    }

    public function delete(int $id): void
    {
        $stmt = $this->pdo->prepare('DELETE FROM users WHERE id = :id');
        $stmt->execute(['id' => $id]);
    }
}

