<?php
// auth.php - Sistema de autenticacao
require_once __DIR__ . '/includes/functions.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

function is_logged_in(): bool {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function require_login(): void {
    if (!is_logged_in()) {
        header('Location: login.php');
        exit;
    }

    $user = current_user();
    if (!$user || (int)($user['is_active'] ?? 0) !== 1) {
        logout_user();
        header('Location: login.php');
        exit;
    }

    if (user_panel_is_expired($user)) {
        logout_user();
        header('Location: login.php?expired=1');
        exit;
    }
}

function require_admin(): void {
    require_login();

    if (!user_is_admin(current_user())) {
        header('Location: list_dns.php');
        exit;
    }
}

function current_user(): array {
    if (!is_logged_in()) {
        return [];
    }

    $stmt = db()->prepare("
        SELECT id, username, display_name, role, panel_expires_at, client_limit, is_active
          FROM app_users
         WHERE id = ?
         LIMIT 1
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();

    return $user ?: [];
}

function login_user(string $username, string $password): array {
    $stmt = db()->prepare("
        SELECT id, username, display_name, role, panel_expires_at, client_limit, password_hash, is_active
          FROM app_users
         WHERE username = ?
         LIMIT 1
    ");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user || (int)($user['is_active'] ?? 0) !== 1) {
        return ['ok' => false, 'message' => 'Usuario ou senha invalidos.'];
    }

    if (!password_verify($password, (string)($user['password_hash'] ?? ''))) {
        return ['ok' => false, 'message' => 'Usuario ou senha invalidos.'];
    }

    if (user_panel_is_expired($user)) {
        return [
            'ok' => false,
            'expired' => true,
            'message' => 'Painel VENCIDO, Renove AGORA com Admin!',
        ];
    }

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

    return ['ok' => true, 'user' => $user];
}

function logout_user(): void {
    $_SESSION = [];
    session_destroy();
    session_start();
}

function create_user(string $username, string $password): array {
    $username = str_in($username);
    $password = str_in($password);

    if (strlen($username) < 3) {
        return ['ok' => false, 'message' => 'Nome de usuario deve ter pelo menos 3 caracteres.'];
    }

    if (strlen($password) < 6) {
        return ['ok' => false, 'message' => 'Senha deve ter pelo menos 6 caracteres.'];
    }

    $stmt = db()->prepare("SELECT id FROM app_users WHERE username = ? LIMIT 1");
    $stmt->execute([$username]);
    if ($stmt->fetch()) {
        return ['ok' => false, 'message' => 'Nome de usuario ja existe.'];
    }

    try {
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $stmt = db()->prepare("INSERT INTO app_users (username, display_name, password_hash, role, is_active) VALUES (?, ?, ?, 'admin', 1)");
        $stmt->execute([$username, $username, $hash]);

        return ['ok' => true, 'id' => db()->lastInsertId()];
    } catch (Exception $e) {
        return ['ok' => false, 'message' => 'Erro ao criar usuario: ' . $e->getMessage()];
    }
}

function change_password(int $user_id, string $current_password, string $new_password): array {
    $stmt = db()->prepare("SELECT password_hash FROM app_users WHERE id = ? LIMIT 1");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    if (!$user) {
        return ['ok' => false, 'message' => 'Usuario nao encontrado.'];
    }

    if (!password_verify($current_password, $user['password_hash'])) {
        return ['ok' => false, 'message' => 'Senha atual incorreta.'];
    }

    if (strlen($new_password) < 6) {
        return ['ok' => false, 'message' => 'Nova senha deve ter pelo menos 6 caracteres.'];
    }

    try {
        $hash = password_hash($new_password, PASSWORD_BCRYPT);
        $stmt = db()->prepare("UPDATE app_users SET password_hash = ? WHERE id = ?");
        $stmt->execute([$hash, $user_id]);

        return ['ok' => true, 'message' => 'Senha alterada com sucesso!'];
    } catch (Exception $e) {
        return ['ok' => false, 'message' => 'Erro ao alterar senha.'];
    }
}
