<?php
session_start();
include __DIR__ . '/auth.php'; // sets $CAN_EDIT

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';

$newsFile = __DIR__ . '/../data/news.txt';
$uploadDir = __DIR__ . '/../uploads/news/';

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

/* ------------------------------------------------------------
   LOAD NEWS POSTS
------------------------------------------------------------ */
$posts = [];

if (file_exists($newsFile)) {
    $lines = file($newsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    foreach ($lines as $line) {
        $parts = explode('|', $line);

        if (count($parts) >= 8) {
            $posts[] = [
                'id'       => $parts[0],
                'title'    => $parts[1],
                'author'   => $parts[2],
                'date'     => $parts[3],
                'category' => $parts[4],
                'content'  => $parts[5],
                'featured' => $parts[6],
                'image'    => $parts[7]
            ];
        }
    }
}

/* ------------------------------------------------------------
   DELETE POST (EDIT PERMISSION REQUIRED)
------------------------------------------------------------ */
if (isset($_GET['delete'])) {

    if (!$CAN_EDIT) {
        die("<h1>Access Denied</h1><p>You cannot delete news posts.</p>");
    }

    $deleteId = $_GET['delete'];
    $newList = [];

    foreach ($posts as $post) {
        if ($post['id'] !== $deleteId) {
            $newList[] = implode('|', [
                $post['id'],
                $post['title'],
                $post['author'],
                $post['date'],
                $post['category'],
                $post['content'],
                $post['featured'],
                $post['image']
            ]);
        }
    }

    file_put_contents($newsFile, implode("\n", $newList));
    header("Location: news.php");
    exit;
}

/* ------------------------------------------------------------
   ADD / EDIT POST (EDIT PERMISSION REQUIRED)
------------------------------------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!$CAN_EDIT) {
        die("<h1>Access Denied</h1><p>You cannot modify news posts.</p>");
    }

    $id       = $_POST['id'] ?: uniqid();
    $title    = trim($_POST['title']);
    $author   = trim($_POST['author']);
    $category = trim($_POST['category']);
    $content  = trim($_POST['content']);
    $featured = isset($_POST['featured']) ? 'yes' : 'no';
    $date     = $_POST['date'] ?: date('Y-m-d H:i:s');

    $image = $_POST['existing_image'] ?? '';

    /* Handle image upload */
    if (!empty($_FILES['image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));

        if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) {
            $image = uniqid('news_') . '.' . $ext;
            move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $image);
        }
    }

    /* Rebuild list */
    $newList = [];
    $updated = false;

    foreach ($posts as $post) {
        if ($post['id'] === $id) {
            $newList[] = implode('|', [
                $id, $title, $author, $date, $category, $content, $featured, $image
            ]);
            $updated = true;
        } else {
            $newList[] = implode('|', [
                $post['id'], $post['title'], $post['author'], $post['date'],
                $post['category'], $post['content'], $post['featured'], $post['image']
            ]);
        }
    }

    if (!$updated) {
        $newList[] = implode('|', [
            $id, $title, $author, $date, $category, $content, $featured, $image
        ]);
    }

    file_put_contents($newsFile, implode("\n", $newList));
    header("Location: news.php");
    exit;
}

/* ------------------------------------------------------------
   EDIT MODE
------------------------------------------------------------ */
$editPost = null;

if (isset($_GET['edit'])) {
    foreach ($posts as $post) {
        if ($post['id'] === $_GET['edit']) {
            $editPost = $post;
            break;
        }
    }
}
?>

<style>
.news-card {
    padding: 30px;
    margin-bottom: 30px;
    text-align: left;
}

.news-card h2 {
    color: #4ff;
    margin-bottom: 10px;
    text-shadow: 0 0 10px rgba(0,255,255,0.45);
}

textarea.input-field {
    min-height: 140px;
    resize: vertical;
}
</style>

<div class="main-wrap">
    <div class="content-panel">

        <h1 class="section-title center-text">📰 News Manager</h1>

        <div class="vinyl-divider center-divider"></div>

        <!-- ADD / EDIT FORM -->
        <div class="neon-card news-card">

            <h2><?= $editPost ? "Edit Post" : "Add New Post" ?></h2>

            <form method="POST" enctype="multipart/form-data">

                <input type="hidden" name="id" value="<?= $editPost['id'] ?? '' ?>">
                <input type="hidden" name="date" value="<?= $editPost['date'] ?? '' ?>">

                <input type="text" name="title" class="input-field"
                       value="<?= htmlspecialchars($editPost['title'] ?? '') ?>"
                       placeholder="Title"
                       <?= $CAN_EDIT ? '' : 'readonly' ?>
                       required>

                <input type="text" name="author" class="input-field"
                       value="<?= htmlspecialchars($editPost['author'] ?? '') ?>"
                       placeholder="Author"
                       <?= $CAN_EDIT ? '' : 'readonly' ?>
                       required>

                <input type="text" name="category" class="input-field"
                       value="<?= htmlspecialchars($editPost['category'] ?? '') ?>"
                       placeholder="Category"
                       <?= $CAN_EDIT ? '' : 'readonly' ?>
                       required>

                <textarea name="content" class="input-field"
                          placeholder="Content"
                          <?= $CAN_EDIT ? '' : 'readonly' ?>
                          required><?= htmlspecialchars($editPost['content'] ?? '') ?></textarea>

                <?php if ($CAN_EDIT): ?>
                    <label>
                        <input type="checkbox" name="featured"
                            <?= isset($editPost['featured']) && $editPost['featured'] === 'yes' ? 'checked' : '' ?>>
                        <span style="color:#4ff;font-weight:bold;">Featured Post</span>
                    </label>
                <?php else: ?>
                    <?php if (isset($editPost['featured']) && $editPost['featured'] === 'yes'): ?>
                        <p style="color:#ff0033;font-weight:bold;">⭐ Featured Post</p>
                    <?php endif; ?>
                <?php endif; ?>

                <br><br>

                <?php if ($CAN_EDIT): ?>
                    <label class="about-text">Upload Image (JPG, PNG, WEBP):</label>
                    <input type="file" name="image" class="input-field" accept=".jpg,.jpeg,.png,.webp">
                <?php endif; ?>

                <input type="hidden" name="existing_image" value="<?= $editPost['image'] ?? '' ?>">

                <?php if (!empty($editPost['image'])): ?>
                    <p class="about-text">Current Image:</p>
                    <img src="../uploads/news/<?= htmlspecialchars($editPost['image']) ?>"
                         style="max-width:200px;border:2px solid #4ff;border-radius:8px;">
                <?php endif; ?>

                <br><br>

                <?php if ($CAN_EDIT): ?>
                    <button type="submit" class="button radio-static">💾 Save Post</button>
                <?php else: ?>
                    <div class="content-box center-text" style="opacity:0.6;">
                        <p>You can view posts, but you cannot edit or create them.</p>
                    </div>
                <?php endif; ?>

            </form>
        </div>

        <div class="vinyl-divider center-divider"></div>

        <!-- LIST OF POSTS -->
        <?php foreach ($posts as $post): ?>
            <div class="neon-card news-card">

                <h2><?= htmlspecialchars($post['title']) ?></h2>

                <p><strong style="color:#4ff;">Author:</strong> <?= htmlspecialchars($post['author']) ?></p>
                <p><strong style="color:#4ff;">Date:</strong> <?= htmlspecialchars($post['date']) ?></p>
                <p><strong style="color:#4ff;">Category:</strong> <?= htmlspecialchars($post['category']) ?></p>

                <?php if (!empty($post['image'])): ?>
                    <img src="../uploads/news/<?= htmlspecialchars($post['image']) ?>"
                         style="max-width:200px;border:2px solid #4ff;border-radius:8px;margin-bottom:10px;">
                <?php endif; ?>

                <p><?= nl2br(htmlspecialchars($post['content'])) ?></p>

                <?php if ($post['featured'] === 'yes'): ?>
                    <p style="color:#ff0033;font-weight:bold;">⭐ Featured Post</p>
                <?php endif; ?>

                <?php if ($CAN_EDIT): ?>
                    <a href="news.php?edit=<?= $post['id'] ?>" class="button">Edit</a>
                    <a href="news.php?delete=<?= $post['id'] ?>" class="button" style="background:#900;color:#fff;">Delete</a>
                <?php endif; ?>

            </div>

            <div class="vinyl-divider center-divider"></div>
        <?php endforeach; ?>

    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
