<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/db_remote.php';

// USER FUNCTIONS DEFINITIVE

function getUserByUsername($username) {
    global $conn;
    $sql = "SELECT id, username, password_hash, full_name, avatar_url, role, is_active
            FROM users WHERE username = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return null;
    $stmt->bind_param("s", $username);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc() ?: null;
}

function getUserById($id) {
    global $conn;
    $sql = "SELECT id, username, full_name, avatar_url, role, is_active
            FROM users WHERE id = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return null;
    $stmt->bind_param("i", $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc() ?: null;
}

function authenticate($username, $password) {
    $user = getUserByUsername($username);
    if (!$user) return false;
    if (!$user['is_active']) return false;
    if (!password_verify($password, $user['password_hash'])) return false;
    updateUserLastLogin($user['id']);
    return $user;
}

function updateUserLastLogin($user_id) {
    global $conn;
    $sql = "UPDATE users SET updated_at = NOW() WHERE id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
    }
}

function getUserPermissions($user_id) {
    global $conn;
    $sql = "SELECT permission FROM user_permissions WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return [];
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $perms = [];
    while ($row = $result->fetch_assoc()) {
        $perms[] = $row['permission'];
    }
    return $perms;
}

function userHasPermission($permission) {
    if (!isset($_SESSION['user'])) return false;

    if (($_SESSION['user']['role'] ?? '') === 'admin') {
        return true;
    }

    if (!isset($_SESSION['user']['permissions']) || !is_array($_SESSION['user']['permissions'])) {
        $_SESSION['user']['permissions'] = getUserPermissions($_SESSION['user']['id']);
    }

    return in_array($permission, $_SESSION['user']['permissions'], true);
}

function requireLogin() {
    if (!isset($_SESSION['user'])) {
        header("Location: /auth/login.php");
        exit;
    }
}

function userHasRole($role) {
    return isset($_SESSION['user']) &&
           ($_SESSION['user']['role'] ?? null) === $role;
}

function userLogout() {
    session_unset();
    session_destroy();
}

function user_has_role($role) { return userHasRole($role); }
function user_has_permission($p) { return userHasPermission($p); }
