<?php
// One-time script to reorder buy-logs.php — run once then delete
$file = dirname(__DIR__) . '/user/buy-logs.php';
$content = file_get_contents($file);

// Markers
$apiSectionStart = '<?php if ($xtl_enabled && !empty($xtl_products)): ?>' . "\n" . '<!-- ── XtraLogTools API Products Section';
$apiSectionEnd   = '<?php endif; ?>' . "\n" . "\n" . '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
$catFilterStart  = '<!-- ── Category filter bar ──────────────────────────────────── -->';

// Find positions
$apiStart = strpos($content, $apiSectionStart);
$apiEnd   = strpos($content, $apiSectionEnd, $apiStart);
$catPos   = strpos($content, $catFilterStart);

if ($apiStart === false || $apiEnd === false || $catPos === false) {
    die("Could not find markers. apiStart=$apiStart, apiEnd=$apiEnd, catPos=$catPos");
}

// Extract the API section (including the endif and sweetalert script tag)
$apiBlock = substr($content, $apiStart, ($apiEnd + strlen($apiSectionEnd)) - $apiStart);

// Remove the API section from its current position
$contentWithout = substr($content, 0, $apiStart) . '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>' . substr($content, $apiEnd + strlen($apiSectionEnd));

// Now find the category filter position again in the modified content
$catPos2 = strpos($contentWithout, $catFilterStart);
if ($catPos2 === false) {
    die("Could not find category filter in modified content");
}

// Insert API section before the category filter
$final = substr($contentWithout, 0, $catPos2) . $apiBlock . "\n\n" . substr($contentWithout, $catPos2);

// Fix: remove the duplicate sweetalert script
$final = str_replace(
    '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>' . "\n\n" . '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>',
    '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>',
    $final
);

file_put_contents($file, $final);
echo "Done! API section moved to before category filter. File size: " . strlen($final) . " bytes";
