<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

if (!admin_is_authenticated()) {
    admin_redirect('/admin/?route=login');
}

$state = admin_refresh_state();
$config = $state['config'];
$pluginRegistry = $state['pluginRegistry'];
$pluginSlug = admin_resolve_plugin_slug((string) ($_GET['plugin'] ?? ''));
$pluginFiles = admin_plugin_files($pluginSlug);
$selectedFile = str_replace('\\', '/', trim((string) ($_GET['file'] ?? 'plugin.php')));
if ($selectedFile === '' || !in_array($selectedFile, $pluginFiles, true)) {
    $selectedFile = in_array('plugin.php', $pluginFiles, true) ? 'plugin.php' : ($pluginFiles[0] ?? 'plugin.php');
}
$pluginFile = admin_resolve_plugin_relative_file($pluginSlug, $selectedFile);
$pluginName = $pluginSlug !== '' && isset($pluginRegistry[$pluginSlug])
    ? (string) $pluginRegistry[$pluginSlug]['name']
    : ucwords(str_replace(['-', '_'], ' ', $pluginSlug));

$errors = [];
$notice = '';
$lintNotice = '';
$fileContents = '';
$fileSize = 0;
$lastModified = null;

if ($pluginSlug === '' || $pluginFile === null) {
    $errors[] = 'Plugin file could not be found.';
} else {
    $fileSize = (int) @filesize($pluginFile);
    $modified = @filemtime($pluginFile);
    $lastModified = $modified !== false ? date('Y-m-d H:i:s', $modified) : null;
    $fileContents = (string) @file_get_contents($pluginFile);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrfToken = (string) ($_POST['csrf_token'] ?? '');
    $postedSlug = admin_resolve_plugin_slug((string) ($_POST['plugin_slug'] ?? ''));
    $postedRelativeFile = str_replace('\\', '/', trim((string) ($_POST['plugin_file'] ?? 'plugin.php')));
    $postedFile = admin_resolve_plugin_relative_file($postedSlug, $postedRelativeFile);
    $submittedContents = (string) ($_POST['plugin_code'] ?? '');
    $editorAction = strtolower(trim((string) ($_POST['editor_action'] ?? 'save')));
    $newFileName = str_replace('\\', '/', trim((string) ($_POST['new_file_name'] ?? '')));

    if (!admin_verify_csrf($csrfToken)) {
        $errors[] = 'Security token mismatch. Please refresh and try again.';
    } elseif ($postedSlug === '' || $postedFile === null) {
        $errors[] = 'Plugin file could not be found.';
    } elseif ($editorAction === 'create') {
        $newFilePath = admin_resolve_plugin_relative_file($postedSlug, $newFileName);
        if ($newFileName === '' || $newFilePath === null) {
            $errors[] = 'Please enter a valid new file name.';
        } elseif (is_file($newFilePath)) {
            $errors[] = 'That file already exists.';
        } elseif (file_put_contents($newFilePath, '', LOCK_EX) === false) {
            $errors[] = 'New file could not be created.';
        } else {
            $notice = 'New file created successfully.';
            $selectedFile = str_replace('\\', '/', $newFileName);
            $pluginFiles = admin_plugin_files($postedSlug);
            $pluginFile = $newFilePath;
            $fileContents = '';
            $fileSize = 0;
            $lastModified = date('Y-m-d H:i:s');
        }
    } elseif ($editorAction === 'delete') {
        if ($postedRelativeFile === 'plugin.php') {
            $errors[] = 'plugin.php cannot be deleted.';
        } else {
            admin_backup_plugin_file($postedSlug, $postedFile);
            if (!@unlink($postedFile)) {
                $errors[] = 'File could not be deleted.';
            } else {
                $notice = 'File deleted successfully.';
                $pluginFiles = admin_plugin_files($postedSlug);
                $selectedFile = in_array('plugin.php', $pluginFiles, true) ? 'plugin.php' : ($pluginFiles[0] ?? 'plugin.php');
                $pluginFile = admin_resolve_plugin_relative_file($postedSlug, $selectedFile);
                $fileContents = $pluginFile !== null && is_file($pluginFile) ? (string) file_get_contents($pluginFile) : '';
                $fileSize = $pluginFile !== null && is_file($pluginFile) ? (int) filesize($pluginFile) : 0;
                $lastModified = $pluginFile !== null && is_file($pluginFile) ? date('Y-m-d H:i:s', (int) filemtime($pluginFile)) : null;
            }
        }
    } elseif (trim($submittedContents) === '') {
        $errors[] = 'Plugin file cannot be blank.';
    } elseif (!is_writable($postedFile)) {
        $errors[] = 'Plugin file is not writable.';
    } else {
        $extension = strtolower(pathinfo($postedRelativeFile, PATHINFO_EXTENSION));
        if ($extension === 'php') {
            $lintResult = admin_lint_php_code($submittedContents);
            if (!$lintResult['ok']) {
                $errors[] = (string) $lintResult['message'];
            } else {
                $lintNotice = (string) $lintResult['message'];
            }
        }

        if ($errors === []) {
            admin_backup_plugin_file($postedSlug, $postedFile);
            if (file_put_contents($postedFile, $submittedContents, LOCK_EX) === false) {
                $errors[] = 'Plugin file could not be saved.';
            } else {
                $notice = 'Plugin file saved successfully.';
                $pluginSlug = $postedSlug;
                $pluginFile = $postedFile;
                $selectedFile = $postedRelativeFile;
                $pluginFiles = admin_plugin_files($postedSlug);
                $fileContents = $submittedContents;
                $fileSize = strlen($submittedContents);
                $lastModified = date('Y-m-d H:i:s');
                $state = admin_refresh_state();
                $config = $state['config'];
                $pluginRegistry = $state['pluginRegistry'];
                if (isset($pluginRegistry[$pluginSlug])) {
                    $pluginName = (string) $pluginRegistry[$pluginSlug]['name'];
                }
            }
        } else {
            $fileContents = $submittedContents;
        }
    }
}

$sizeWarning = $fileSize > 200000;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo admin_escape(admin_site_title($config)); ?> Plugin Editor</title>
    <?php echo admin_shared_styles("
        body { font-family:Consolas, Monaco, monospace; }
        .content { color:#e5e7eb; }
        .page-title { color:#f8fafc; }
        .page-subtitle { color:#94a3b8; }
        .meta { color:var(--muted); margin-bottom:16px; }
        .panel { background:rgba(15,23,42,.92); border:1px solid var(--line); border-radius:18px; padding:22px; box-shadow:0 16px 40px rgba(2,6,23,.35); }
        textarea { width:100%; min-height:72vh; padding:18px; border:1px solid var(--line); border-radius:16px; background:#020617; color:#e2e8f0; font:14px/1.6 Consolas, Monaco, monospace; resize:vertical; }
        .btn { display:inline-flex; align-items:center; justify-content:center; gap:8px; border:0; border-radius:12px; padding:12px 18px; background:var(--accent); color:#fff; cursor:pointer; font:600 14px Arial, sans-serif; }
        .btn:hover { background:var(--accent-dark); }
        .btn.secondary { background:#1e293b; }
        .btn.danger { background:#991b1b; }
        .toolbar { display:flex; justify-content:space-between; gap:16px; align-items:center; margin-bottom:16px; flex-wrap:wrap; font-family:Arial, sans-serif; }
        .warning { color:#fbbf24; }
        .editor-shell { display:grid; grid-template-columns:260px 1fr; gap:18px; align-items:start; }
        .file-browser { border:1px solid var(--line); border-radius:16px; overflow:hidden; background:#020617; }
        .file-browser h3 { margin:0; padding:14px 16px; font:600 15px Arial, sans-serif; background:#0b1220; border-bottom:1px solid var(--line); }
        .file-list { padding:8px; display:grid; gap:6px; max-height:72vh; overflow:auto; }
        .file-list a { display:block; padding:10px 12px; border-radius:10px; color:#cbd5e1; font-size:14px; }
        .file-list a.active, .file-list a:hover { background:rgba(14,165,233,.12); color:#fff; }
        .editor-pane { display:grid; gap:16px; }
        .mini-form { display:grid; gap:10px; }
        .mini-form input[type='text'] { width:100%; padding:12px 14px; border:1px solid var(--line); border-radius:12px; background:#020617; color:#e2e8f0; font:14px Arial, sans-serif; }
        @media (max-width: 1100px) { .editor-shell { grid-template-columns:1fr; } }
    "); ?>
</head>
<body>
    <div class="app">
        <?php admin_render_sidebar('plugins'); ?>
        <main class="content">
            <div class="page-header">
                <h1 class="page-title"><?php echo admin_escape($pluginName !== '' ? $pluginName : 'Plugin Editor'); ?></h1>
                <p class="page-subtitle">Plugin files ko single place se manage karein, bina plugin structure change kiye.</p>
            </div>
            <div class="meta">
                <?php if ($pluginSlug !== ''): ?>Plugin: <strong><?php echo admin_escape($pluginSlug); ?></strong><?php endif; ?>
                <?php if ($selectedFile !== ''): ?> | File: <strong><?php echo admin_escape($selectedFile); ?></strong><?php endif; ?>
                <?php if ($lastModified !== null): ?> | Last modified: <strong><?php echo admin_escape($lastModified); ?></strong><?php endif; ?>
                | Size: <strong><?php echo number_format($fileSize); ?> bytes</strong>
                <?php if ($sizeWarning): ?><span class="warning"> | Large file warning</span><?php endif; ?>
            </div>
            <div class="panel">
                <?php if ($notice !== ''): ?><div class="message success"><?php echo admin_escape($notice); ?></div><?php endif; ?>
                <?php if ($lintNotice !== ''): ?><div class="message success"><?php echo admin_escape($lintNotice); ?></div><?php endif; ?>
                <?php foreach ($errors as $error): ?><div class="message error"><?php echo admin_escape($error); ?></div><?php endforeach; ?>
                <div class="toolbar">
                    <div>Editing: <strong><?php echo admin_escape($pluginFile !== null ? $pluginFile : 'Unavailable'); ?></strong></div>
                    <div style="display:flex; gap:10px; flex-wrap:wrap;">
                        <a class="btn secondary" href="/admin/plugins.php">Back to Plugins</a>
                    </div>
                </div>
                <?php if ($pluginFile !== null): ?>
                    <div class="editor-shell">
                        <aside class="file-browser">
                            <h3>Plugin Files</h3>
                            <div class="file-list">
                                <?php foreach ($pluginFiles as $fileItem): ?>
                                    <a href="/admin/plugin-editor.php?plugin=<?php echo rawurlencode($pluginSlug); ?>&file=<?php echo rawurlencode($fileItem); ?>" class="<?php echo $fileItem === $selectedFile ? 'active' : ''; ?>"><?php echo admin_escape($fileItem); ?></a>
                                <?php endforeach; ?>
                            </div>
                        </aside>
                        <div class="editor-pane">
                            <form method="post" action="/admin/plugin-editor.php?plugin=<?php echo rawurlencode($pluginSlug); ?>&file=<?php echo rawurlencode($selectedFile); ?>">
                                <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                                <input type="hidden" name="plugin_slug" value="<?php echo admin_escape($pluginSlug); ?>">
                                <input type="hidden" name="plugin_file" value="<?php echo admin_escape($selectedFile); ?>">
                                <input type="hidden" name="editor_action" value="save">
                                <textarea id="plugin_code" name="plugin_code" spellcheck="false"><?php echo admin_escape($fileContents); ?></textarea>
                                <div style="margin-top:16px; display:flex; justify-content:space-between; gap:12px; align-items:center; flex-wrap:wrap;">
                                    <div style="font-family:Arial, sans-serif; color:var(--muted);">Backups are saved in <code>/content/plugins/<?php echo admin_escape($pluginSlug); ?>/backup/</code></div>
                                    <div style="display:flex; gap:10px; flex-wrap:wrap;">
                                        <?php if ($selectedFile !== 'plugin.php'): ?>
                                            <button class="btn danger" type="submit" form="delete-file-form">Delete File</button>
                                        <?php endif; ?>
                                        <button class="btn" type="submit">Save File</button>
                                    </div>
                                </div>
                            </form>

                            <?php if ($selectedFile !== 'plugin.php'): ?>
                                <form id="delete-file-form" method="post" action="/admin/plugin-editor.php?plugin=<?php echo rawurlencode($pluginSlug); ?>">
                                    <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                                    <input type="hidden" name="plugin_slug" value="<?php echo admin_escape($pluginSlug); ?>">
                                    <input type="hidden" name="plugin_file" value="<?php echo admin_escape($selectedFile); ?>">
                                    <input type="hidden" name="editor_action" value="delete">
                                </form>
                            <?php endif; ?>

                            <div class="file-browser">
                                <h3>Create New File</h3>
                                <form class="mini-form" method="post" action="/admin/plugin-editor.php?plugin=<?php echo rawurlencode($pluginSlug); ?>">
                                    <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                                    <input type="hidden" name="plugin_slug" value="<?php echo admin_escape($pluginSlug); ?>">
                                    <input type="hidden" name="plugin_file" value="<?php echo admin_escape($selectedFile); ?>">
                                    <input type="hidden" name="editor_action" value="create">
                                    <input type="text" name="new_file_name" placeholder="helper.php or assets/style.css">
                                    <button class="btn secondary" type="submit">Create File</button>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>
<script>
(function () {
    var textarea = document.getElementById('plugin_code');
    if (!textarea) {
        return;
    }
    textarea.addEventListener('keydown', function (event) {
        if (event.key === 'Tab') {
            event.preventDefault();
            var start = textarea.selectionStart;
            var end = textarea.selectionEnd;
            textarea.value = textarea.value.substring(0, start) + '    ' + textarea.value.substring(end);
            textarea.selectionStart = textarea.selectionEnd = start + 4;
        }
    });
})();
</script>
</body>
</html>
