<?php
// upload.php - Remote File Uploader Tool
// SECURITY WARNING: This file allows modifying server files. 
// Delete this file immediately after you are done with maintenance!

$secret_key = 'TraeAdmin123'; // This key protects the uploader

// 1. Security Check
$req_key = $_POST['key'] ?? $_GET['key'] ?? '';
if ($req_key !== $secret_key) {
    http_response_code(403);
    die('Access Denied. Invalid Key.');
}

// 2. Simple UI for Manual Upload (if accessed via browser with key)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo '
    <div style="font-family: sans-serif; padding: 20px; max-width: 500px; margin: 0 auto; border: 1px solid #ccc; border-radius: 8px;">
        <h3>🚀 Remote Uploader</h3>
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="key" value="'.$secret_key.'">
            <div style="margin-bottom: 15px;">
                <label>Select File:</label><br>
                <input type="file" name="file" required>
            </div>
            <div style="margin-bottom: 15px;">
                <label>Target Path (relative to public_html):</label><br>
                <input type="text" name="path" placeholder="e.g. session-manager.php or api/save-session.php" style="width: 100%; padding: 5px;" required>
            </div>
            <button type="submit" style="padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer;">Upload File</button>
        </form>
    </div>';
    exit;
}

// 3. Handle File Upload (API)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['file']) || !isset($_POST['path'])) {
        die('Missing file or path.');
    }

    // Security: Prevent going up directories
    $clean_path = str_replace('..', '', $_POST['path']);
    $clean_path = ltrim($clean_path, '/');
    
    $target_path = __DIR__ . '/' . $clean_path;
    $dir = dirname($target_path);

    // Create directory if it doesn't exist
    if (!is_dir($dir)) {
        if (!mkdir($dir, 0755, true)) {
            die("Error: Failed to create directory $dir");
        }
    }

    if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
        echo "Success: File uploaded to " . htmlspecialchars($clean_path);
    } else {
        echo "Error: Failed to move uploaded file to $target_path. Check permissions.";
    }
}
?>