<?php

require_once __DIR__ . '/activity_logger.php';

function loginUser(string $username, string $password): ?array
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

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

    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['role'] = $user['role'];

    logActivity($user['id'], 'login', 'Usuario inició sesión');

    return $user;
}

function registerUser(string $username, string $password, string $role = 'user'): ?int
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$username]);
    
    if ($stmt->fetch()) {
        return null;
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
    $stmt = $pdo->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
    $stmt->execute([$username, $hashedPassword, $role]);

    return (int) $pdo->lastInsertId();
}

function updateUserPassword(int $userId, string $newPassword): bool
{
    $pdo = getDbConnection();
    
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    
    $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
    return $stmt->execute([$hashedPassword, $userId]);
}

function getUserById(int $userId): ?array
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("SELECT id, username, role, telegram_chat_id, created_at FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    
    return $stmt->fetch() ?: null;
}

function getAllUsers(): array
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->query("SELECT id, username, role, telegram_chat_id, created_at FROM users ORDER BY username");
    return $stmt->fetchAll();
}

function updateUserTelegramChatId(int $userId, string $telegramChatId): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("UPDATE users SET telegram_chat_id = ? WHERE id = ?");
    return $stmt->execute([$telegramChatId, $userId]);
}

function deleteUser(int $userId): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
    return $stmt->execute([$userId]);
}
