<?php
session_start();
require_once "../config.php";

if (!isset($_SESSION['user_id'])) {
    die("Not logged in.");
}

$user = $_SESSION['user_id'];
$root = "../userfiles/$user/";
if (!is_dir($root)) mkdir($root, 0777, true);

$file = $_GET['file'] ?? "";
$full = realpath($root . $file);

// Security check
if ($file && (!$full || strpos($full, realpath($root)) !== 0)) {
    die("Invalid file path.");
}

// Save file
if ($_SERVER['REQUEST_METHOD'] === "POST") {
    $filename = basename($_POST['filename']);
    $content = $_POST['content'];

    file_put_contents($root . $filename, $content);

    echo "<script>alert('Saved!');</script>";
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Notepad</title>
<style>
    body { background:#111; color:white; font-family:Arial; margin:0; padding:10px; }
    textarea {
        width:100%;
        height:80vh;
        background:#000;
        color:#0f0;
        border:1px solid #0ff;
        padding:10px;
        font-family: monospace;
        font-size: 14px;
    }
    input {
        width: 200px;
        padding: 6px;
        margin-bottom: 10px;
        border:1px solid #0ff;
        background:#000;
        color:#0ff;
    }
    button {
        padding: 6px 12px;
        background:#0ff;
        border:none;
        cursor:pointer;
        font-weight:bold;
    }
</style>
</head>
<body>

<h2>📝 Notepad</h2>

<form method="POST">
    <input type="text" name="filename" placeholder="filename.txt"
           value="<?= htmlspecialchars($file) ?>" required>

    <textarea name="content"><?php
        if ($file && file_exists($full)) {
            echo htmlspecialchars(file_get_contents($full));
        }
    ?></textarea>

    <br><br>
    <button type="submit">Save</button>
</form>

</body>
</html>