<?php
$file = 'c:\xampp\htdocs\inveetaire\app\views\public\identity.php';
$content = file_get_contents($file);

// 1. Extract Head
$headStart = strpos($content, '<head>');
$headEnd = strpos($content, '</head>') + 7;
if ($headStart !== false && $headEnd !== false) {
    $headContent = substr($content, $headStart, $headEnd - $headStart);
    file_put_contents(__DIR__ . '/app/views/public/identity/partials/head.php', trim($headContent) . "\n");
    $content = substr_replace($content, "<?php require __DIR__ . '/identity/partials/head.php'; ?>\n", $headStart, $headEnd - $headStart);
}

// 2. Extract Scripts (Before body closes)
$scriptLabel = '<!-- JAVASCRIPT HELPERS & FLOATING MUSIC ENGINE                        -->';
$scriptStart = strpos($content, $scriptLabel);
$scriptEnd = strpos($content, '</body>');

if ($scriptStart !== false && $scriptEnd !== false) {
    // There are scripts after </html> too, let's just take everything from JAVASCRIPT HELPERS to end of file,
    // but keep </body>\n</html> in identity.php
    
    // Actually, why not just grab everything from JAVASCRIPT HELPERS, remove </body></html> from it, save it to scripts,
    // and then put </body></html> back in identity.php?
    
    $scriptsContent = substr($content, $scriptStart);
    $scriptsContent = str_replace(['</body>', '</html>'], '', $scriptsContent);
    file_put_contents(__DIR__ . '/app/views/public/identity/partials/scripts.php', trim($scriptsContent) . "\n");
    
    $content = substr_replace($content, "<?php require __DIR__ . '/identity/partials/scripts.php'; ?>\n</body>\n</html>\n", $scriptStart);
}

file_put_contents($file, $content);
echo "Done layout extraction!\n";
