<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/db.php';

function db_table_has_column(PDO $pdo, string $table, string $column): bool {
    static $cache = [];
    $key = strtolower($table) . ':' . strtolower($column);
    if (array_key_exists($key, $cache)) {
        return $cache[$key];
    }

    $exists = false;
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?");
        $stmt->execute([$table, $column]);
        $exists = ((int)$stmt->fetchColumn() > 0);
    } catch (Throwable $e) {
        try {
            $stmt = $pdo->query("DESCRIBE `$table`");
            foreach ($stmt as $row) {
                if (($row['Field'] ?? null) === $column) {
                    $exists = true;
                    break;
                }
            }
        } catch (Throwable $e2) {
            $exists = false;
        }
    }

    $cache[$key] = $exists;
    return $exists;
}

function ensure_session_started() {
    if (session_status() !== PHP_SESSION_NONE) {
        return;
    }

    $configuredPath = (string)session_save_path();
    $pathParts = explode(';', $configuredPath);
    $configuredPath = trim((string)end($pathParts));

    $needsFallback = ($configuredPath === '' || !is_dir($configuredPath) || !is_writable($configuredPath));
    if ($needsFallback) {
        $fallbackPath = dirname(__DIR__) . '/sessions';
        if (!is_dir($fallbackPath)) {
            @mkdir($fallbackPath, 0777, true);
        }
        if (is_dir($fallbackPath)) {
            session_save_path($fallbackPath);
        }
    }

    session_start();
}

// Iniciar sessão de forma padrão e segura
ensure_session_started();

function get_nextcloud_user_info($username, $password) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, NC_CHECK_USER_URL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['OCS-APIRequest: true', 'Accept: application/json']);
    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $result = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code !== 200 || !is_string($result) || $result === '') {
        return null;
    }

    $data = json_decode($result, true);
    if (!is_array($data)) {
        return null;
    }

    return $data['ocs']['data'] ?? null;
}

function check_nextcloud_login($username, $password) {
    return get_nextcloud_user_info($username, $password) !== null;
}

function login($username, $password) {
    if (check_nextcloud_login($username, $password)) {
        // Sync user to local DB
        $pdo = get_db_connection();
        $hasNcPass = db_table_has_column($pdo, 'users', 'nc_pass');
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if (!$user) {
            // Se for o primeiro usuário do sistema, torná-lo admin
            $count = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
            $role = ($count == 0) ? 'admin' : 'user';

            if ($hasNcPass) {
                $stmt = $pdo->prepare("INSERT INTO users (username, role, nc_pass) VALUES (?, ?, ?)");
                $stmt->execute([$username, $role, $password]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO users (username, role) VALUES (?, ?)");
                $stmt->execute([$username, $role]);
            }
            $user_id = $pdo->lastInsertId();
        } else {
            $user_id = $user['id'];
            $role = $user['role'];
            // Atualizar senha armazenada se necessário
            if ($hasNcPass) {
                $stmt = $pdo->prepare("UPDATE users SET nc_pass = ? WHERE id = ?");
                $stmt->execute([$password, $user_id]);
            }
        }

        // Regenerate session ID for security
        session_regenerate_id(true);

        $_SESSION['user_id'] = $user_id;
        $_SESSION['username'] = $username;
        $_SESSION['nc_pass'] = $password; // Armazenar temporariamente para operações WebDAV
        $_SESSION['role'] = $role;
        $nc_user_info = get_nextcloud_user_info($username, $password);
        $_SESSION['nc_user_id'] = $nc_user_info['id'] ?? $username;
        header('Location: dashboard.php');
        exit;
    }
    return false;
}

function logout() {
    session_destroy();
    header('Location: login.php');
    exit;
}

function require_login($redirect = true) {
    ensure_session_started();
    
    // Se estivermos na página sign.php ou serve_file.php com um token válido, permitimos o acesso
    $current_page = basename($_SERVER['PHP_SELF']);
    if (($current_page === 'sign.php' || $current_page === 'serve_file.php') && isset($_GET['token'])) {
        return true; 
    }

    if (!isset($_SESSION['user_id'])) {
        if ($redirect) {
            header('Location: login.php');
            exit;
        }
        return false;
    }
    return true;
}
