<?php
require_once 'admin/config.php';
require_login();

$error = '';
$success = '';

$file_path = isset($_GET['file']) ? $_GET['file'] : '';

if (empty($file_path)) {
    header('Location: admin.php');
    exit;
}

// Security check: Ensure the path is within the project root and does not contain '..'
$real_path = realpath($file_path);
if ($real_path === false || strpos($real_path, realpath(__DIR__)) !== 0) {
    die('Invalid file path.');
}

if (!file_exists($file_path)) {
    die('File not found.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file_content = isset($_POST['file_content']) ? $_POST['file_content'] : '';

    if (empty($file_content)) {
        $error = 'File content cannot be empty.';
    } else {
        if (file_put_contents($file_path, $file_content)) {
             $success = 'File updated successfully.';
        } else {
            $error = 'Failed to write updated file.';
        }
    }
} else {
    $file_content = file_get_contents($file_path);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit File</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/admin.css">
    <link rel="icon" href="/assets/images/favicon.jpg" type="image/jpeg">
</head>
<body>
<div class="wrapper">
    <!-- Sidebar -->
    <nav id="sidebar">
        <div class="sidebar-header">
            <h3>Admin Panel</h3>
        </div>

        <ul class="list-unstyled components">
            <li>
                <a href="admin.php">Templates</a>
            </li>
            <li>
                <a href="logout.php">Logout</a>
            </li>
        </ul>
    </nav>

    <!-- Page Content -->
    <div id="content">
        <h1 class="page-title">Edit File: <?php echo htmlspecialchars(basename($file_path)); ?></h1>

        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>

        <div class="card">
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label for="file_content" class="form-label">File Content</label>
                        <textarea class="form-control" id="file_content" name="file_content" rows="20" required><?php echo htmlspecialchars($file_content); ?></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Update File</button>
                    <a href="admin.php" class="btn btn-secondary">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>