<?php
// api/session_auth.php
// Server-side bearer-session support for the PHP/XAMPP + PostgreSQL backend.

function rvu_ensure_session_table(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS user_sessions (
        id BIGSERIAL PRIMARY KEY,
        user_id BIGINT NOT NULL,
        token_hash CHAR(64) NOT NULL UNIQUE,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        expires_at TIMESTAMPTZ NOT NULL,
        revoked_at TIMESTAMPTZ NULL
    )");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_user_sessions_user_id ON user_sessions (user_id)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_user_sessions_token_hash ON user_sessions (token_hash)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_user_sessions_expires_at ON user_sessions (expires_at)");
}


function rvu_ensure_account_status_columns(PDO $pdo): void {
    // Safe migration for installations created before account suspension support.
    $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS account_status VARCHAR(30) NOT NULL DEFAULT 'active'");
    $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS suspended_at TIMESTAMPTZ NULL");
    $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS suspended_by_user_id BIGINT NULL");
    $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS suspension_reason TEXT NULL");
}

function rvu_bearer_token(): string {
    // Shared hosting, Apache, and PHP-FPM do not all expose Authorization in
    // the same server variable. Try every available form before giving up.
    $candidates = [
        $_SERVER['HTTP_AUTHORIZATION'] ?? '',
        $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '',
        $_SERVER['HTTP_X_AUTHORIZATION'] ?? '',
    ];
    if (function_exists('getallheaders')) {
        $headers = getallheaders();
        if (is_array($headers)) {
            foreach ($headers as $name => $value) {
                if (strcasecmp((string)$name, 'Authorization') === 0) {
                    $candidates[] = $value;
                    break;
                }
            }
        }
    }
    foreach ($candidates as $candidate) {
        $header = trim((string)$candidate);
        if ($header !== '' && preg_match('/^Bearer\s+(.+)$/i', $header, $matches)) {
            return trim($matches[1]);
        }
    }
    return '';
}

/** Shared CORS and preflight behavior for Flutter Web and desktop clients. */
function rvu_apply_api_headers(): void {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Authorization, If-None-Match, X-Requested-With');
    header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 600');
    header('Vary: Origin');

    if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) === 'OPTIONS') {
        http_response_code(204);
        exit;
    }
}

// Applying these when this shared auth file loads gives protected endpoints a
// consistent browser preflight response without enabling cookie credentials.
rvu_apply_api_headers();

function rvu_issue_session(PDO $pdo, int $userId, int $lifetimeDays = 30): string {
    rvu_ensure_session_table($pdo);
    rvu_ensure_account_status_columns($pdo);

    $statusStmt = $pdo->prepare("SELECT COALESCE(account_status, 'active') FROM users WHERE id = ? LIMIT 1");
    $statusStmt->execute([$userId]);
    if (strtolower((string)($statusStmt->fetchColumn() ?: 'active')) === 'suspended') {
        throw new RuntimeException('This account is suspended. Contact Rockview University administration.');
    }

    // The raw token is returned once to the client. Only its SHA-256 hash is stored.
    $token = 'rvu_session_' . bin2hex(random_bytes(32));
    $hash = hash('sha256', $token);

    $expiresAt = gmdate('Y-m-d H:i:sP', time() + ($lifetimeDays * 86400));
    $stmt = $pdo->prepare(
        "INSERT INTO user_sessions (user_id, token_hash, expires_at) VALUES (?, ?, ?)"
    );
    $stmt->execute([$userId, $hash, $expiresAt]);

    // Opportunistic cleanup of old sessions.
    $pdo->exec("DELETE FROM user_sessions WHERE expires_at <= CURRENT_TIMESTAMP OR revoked_at IS NOT NULL");

    return $token;
}

/**
 * Set database session context so PostgreSQL audit triggers can attribute
 * writes made by this authenticated API request to the signed-in account.
 */
function rvu_set_audit_context(PDO $pdo, ?array $user = null): void {
    try {
        $stmt = $pdo->prepare("SELECT
            set_config('rvu.audit_actor_id', ?, false),
            set_config('rvu.audit_actor_name', ?, false),
            set_config('rvu.audit_actor_role', ?, false),
            set_config('rvu.audit_actor_campus', ?, false),
            set_config('rvu.audit_ip_address', ?, false)");
        $stmt->execute([
            $user ? (string)(int)$user['id'] : '',
            $user ? (string)($user['full_name'] ?? 'Unknown user') : '',
            $user ? (string)($user['role'] ?? '') : '',
            $user ? (string)($user['campus'] ?? '') : '',
            (string)($_SERVER['REMOTE_ADDR'] ?? ''),
        ]);
    } catch (Throwable $e) {
        // Keep normal API requests working if the audit migration has not run yet.
        error_log('Could not set audit context: ' . $e->getMessage());
    }
}

/** Record successful sign-in and sign-out actions. */
function rvu_record_auth_audit(PDO $pdo, array $actor, string $action, string $summary): void {
    try {
        $stmt = $pdo->prepare("INSERT INTO system_audit_log
            (actor_id, actor_name, actor_role, campus, entity, record_id, action, summary, ip_address)
            VALUES (?, ?, ?, ?, 'authentication', ?, ?, ?, ?)");
        $stmt->execute([
            (int)$actor['id'],
            (string)($actor['full_name'] ?? 'Unknown user'),
            (string)($actor['role'] ?? ''),
            (string)($actor['campus'] ?? ''),
            (string)(int)$actor['id'],
            $action,
            $summary,
            (string)($_SERVER['REMOTE_ADDR'] ?? ''),
        ]);
    } catch (Throwable $e) {
        // Authentication must not fail just because audit storage is unavailable.
        error_log('Could not write authentication audit event: ' . $e->getMessage());
    }
}

function rvu_current_user(PDO $pdo): ?array {
    rvu_ensure_session_table($pdo);
    rvu_ensure_account_status_columns($pdo);

    // Clear any prior connection context first, which also protects persistent PDO connections.
    rvu_set_audit_context($pdo, null);
    $token = rvu_bearer_token();
    if ($token === '') return null;

    $hash = hash('sha256', $token);
    $stmt = $pdo->prepare(
        "SELECT
            u.id,
            u.full_name,
            u.email,
            u.phone,
            u.nrc,
            u.role,
            u.gender,
            u.country,
            u.campus,
            u.school,
            u.program,
            u.permissions,
            u.profile_picture,
            u.account_status,
            u.suspended_at,
            u.suspension_reason
         FROM user_sessions s
         INNER JOIN users u ON u.id = s.user_id
         WHERE s.token_hash = ?
           AND s.revoked_at IS NULL
           AND s.expires_at > CURRENT_TIMESTAMP
           AND COALESCE(u.account_status, 'active') <> 'suspended'
         LIMIT 1"
    );
    $stmt->execute([$hash]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user) {
        rvu_set_audit_context($pdo, $user);
        return $user;
    }

    return null;
}

/**
 * Set audit context when an older endpoint accepts a bearer token but does not
 * otherwise call rvu_current_user(). This only reads an existing session and
 * does not block the endpoint when the request is anonymous or the session table
 * has not been created yet.
 */
function rvu_audit_context_from_request(PDO $pdo): ?array {
    rvu_set_audit_context($pdo, null);
    $token = rvu_bearer_token();
    if ($token === '') return null;

    try {
        $stmt = $pdo->prepare("SELECT u.id, u.full_name, u.role, u.campus
            FROM user_sessions s
            INNER JOIN users u ON u.id = s.user_id
            WHERE s.token_hash = ?
              AND s.revoked_at IS NULL
              AND s.expires_at > CURRENT_TIMESTAMP
            LIMIT 1");
        $stmt->execute([hash('sha256', $token)]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user) rvu_set_audit_context($pdo, $user);
        return $user ?: null;
    } catch (Throwable $e) {
        // Older/public routes keep their existing behavior if sessions are unavailable.
        return null;
    }
}

function rvu_revoke_current_session(PDO $pdo): void {
    rvu_ensure_session_table($pdo);
    $token = rvu_bearer_token();
    if ($token === '') return;

    $hash = hash('sha256', $token);
    $stmt = $pdo->prepare("UPDATE user_sessions SET revoked_at = CURRENT_TIMESTAMP WHERE token_hash = ?");
    $stmt->execute([$hash]);
}
