<?php
header('Content-Type: application/json');

// Check API permission
check_api_permission('terminal');

require_once('/docker/whp/web/libs/mysqlmgmt.php');

$response = ['success' => false, 'error' => 'Unknown error'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['error'] = 'Invalid request method';
    echo json_encode($response);
    exit;
}

try {
    $MySQLMgmt = new mysqlmgmt();
    $db = $MySQLMgmt->getMySQLConnection();
    if (!$db) {
        $response = ['success' => false, 'error' => 'Database connection failed'];
        echo json_encode($response);
        exit;
    }
    
    // Generate a temporary auth token for WebSocket connection
    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', time() + 60); // Token valid for 1 minute
    
    // Store token in database
    $stmt = $db->prepare("
        INSERT INTO whp.api_tokens (token, username, expires_at, ip_address) 
        VALUES (?, ?, ?, ?)
    ");
    $stmt->execute([
        $token,
        AUTH_USER,
        $expires,
        $_SERVER['REMOTE_ADDR']
    ]);
    
    $response = [
        'success' => true,
        'token' => $token,
        'expires_in' => 60
    ];
} catch (Exception $e) {
    error_log("Terminal auth error: " . $e->getMessage());
    $response = ['success' => false, 'error' => 'Failed to generate auth token'];
}

echo json_encode($response);