<?php
// Local-only endpoint to fetch the last N lines of the api_place_order log
header('Content-Type: application/json; charset=utf-8');

// Restrict access to localhost for safety
$remote = $_SERVER['REMOTE_ADDR'] ?? '';
if (!in_array($remote, ['127.0.0.1', '::1'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Forbidden: local access only', 'remote' => $remote]);
    exit;
}

$logDir = __DIR__ . '/logs';
$filename = 'api_place_order.log';
$path = $logDir . '/' . $filename;

if (!file_exists($path)) {
    echo json_encode(['success' => false, 'message' => 'Log file not found', 'path' => $path]);
    exit;
}

$lines = isset($_GET['lines']) ? (int)$_GET['lines'] : 50;
if ($lines < 1) $lines = 50;

// Read file into array (safe for moderate log sizes)
$all = @file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($all === false) {
    echo json_encode(['success' => false, 'message' => 'Unable to read log file']);
    exit;
}

$tail = array_slice($all, -$lines);
$raw = implode("\n", $tail);

echo json_encode([
    'success' => true,
    'file' => $filename,
    'lines_requested' => $lines,
    'lines_returned' => count($tail),
    'content' => $raw,
    'lines' => array_values($tail)
]);
