<?php
$files = [
    'admin/dashboard.php',
    'admin/add-product.php',
    'admin/edit-product.php',
    'admin/add-category.php',
    'admin/manage-users.php',
    'admin/orders.php',
    'admin/settings.php',
    'admin/view-order.php'
];

foreach ($files as $file) {
    if (!file_exists($file)) continue;
    $content = file_get_contents($file);

    // Replace the HTML block
    $start_html = strpos($content, '<div class="sidebar">');
    if ($start_html !== false) {
        $start = strpos($content, '<div class="sidebar">');
        $end = strpos($content, '<div class="main-content">');
        
        if ($start !== false && $end !== false) {
            // The substring to replace is from <div class="sidebar"> to just before <div class="main-content">
            $sidebar_block = substr($content, $start, $end - $start);
            $content = str_replace($sidebar_block, "<!-- Sidebar -->\n    <?php include \"includes/sidebar.php\"; ?>\n\n    ", $content);
        }
    }

    // Replace CSS: remove the .sidebar {...} up to .sidebar-menu i {...}
    // We will use a regex to match from .sidebar { to .sidebar-menu i {...} safely
    $pattern = '/\.sidebar\s*\{.*?\.sidebar-menu i\s*\{[^\}]*\}/s';
    $content = preg_replace($pattern, '/* Replaced sidebar CSS */', $content);

    // In most files .main-content has margin-left: 250px;, we should change it to margin-left: 200px;
    $content = str_replace('margin-left: 250px;', 'margin-left: 220px;', $content);

    file_put_contents($file, $content);
    echo "Refactored $file\n";
}
?>
