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

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

$pollFile  = __DIR__ . '/../data/poll.txt';
$voteFile  = __DIR__ . '/../data/poll_votes.txt';

$poll  = file_exists($pollFile) ? file($pollFile, FILE_IGNORE_NEW_LINES) : [];
$votes = file_exists($voteFile) ? file($voteFile, FILE_IGNORE_NEW_LINES) : [];

$action = $_GET['action'] ?? null;

/* ============================================================
   BLOCK EDIT ACTIONS IF USER CANNOT EDIT
============================================================ */
$editActions = ['save','delete','reset','edit','create'];

if (in_array($action, $editActions) && !$CAN_EDIT) {
    die("<h1>Access Denied</h1><p>You do not have permission to modify the poll.</p>");
}

/* ============================================================
   SAVE NEW / EDITED POLL
============================================================ */
if ($action === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {

    $question = trim($_POST['question']);
    $options  = array_filter(array_map('trim', $_POST['options']));

    if ($question && count($options) >= 2) {
        $data = array_merge([$question], $options);
        file_put_contents($pollFile, implode("\n", $data));

        // Reset votes
        $voteData = array_fill(0, count($options), 0);
        file_put_contents($voteFile, implode("\n", $voteData));

        header("Location: poll.php");
        exit;
    }
}

/* ============================================================
   DELETE POLL
============================================================ */
if ($action === 'delete') {
    @unlink($pollFile);
    @unlink($voteFile);
    header("Location: poll.php");
    exit;
}

/* ============================================================
   RESET VOTES
============================================================ */
if ($action === 'reset') {
    if ($poll) {
        $voteData = array_fill(0, count($poll) - 1, 0);
        file_put_contents($voteFile, implode("\n", $voteData));
    }
    header("Location: poll.php");
    exit;
}
?>

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

        <h1 class="section-title center-text">📊 Manage Station Poll</h1>

        <?php if (($action === 'edit' || $action === 'create') && $CAN_EDIT): ?>

            <?php
            $question = $poll[0] ?? '';
            $options  = array_slice($poll, 1);
            ?>

            <div class="content-box">
                <h3 class="section-title">
                    <?= $action === 'create' ? '➕ Create Poll' : '✏️ Edit Poll' ?>
                </h3>

                <form method="POST" action="poll.php?action=save" id="pollForm">

                    <label>Question:</label>
                    <input type="text" name="question" class="input-field"
                           value="<?= htmlspecialchars($question) ?>" required>

                    <label>Answers:</label>

                    <div id="answerFields">
                        <?php if ($options): ?>
                            <?php foreach ($options as $i => $opt): ?>
                                <div class="answer-row">
                                    <input type="text" name="options[]" class="input-field"
                                           value="<?= htmlspecialchars($opt) ?>" required>
                                    <button type="button" class="remove-btn" onclick="this.parentNode.remove()">❌</button>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="answer-row">
                                <input type="text" name="options[]" class="input-field" placeholder="Answer 1" required>
                            </div>
                            <div class="answer-row">
                                <input type="text" name="options[]" class="input-field" placeholder="Answer 2" required>
                            </div>
                        <?php endif; ?>
                    </div>

                    <button type="button" class="button" id="addAnswerBtn" style="margin-top:10px;">
                        ➕ Add Answer
                    </button>

                    <div style="margin-top:10px; font-size:14px; color:#aaa;">
                        Minimum 2 answers required to save.
                    </div>

                    <button type="submit" class="button" style="margin-top:20px;">
                        Save Poll
                    </button>

                </form>
            </div>

            <script>
                document.getElementById('addAnswerBtn').addEventListener('click', function () {
                    const container = document.getElementById('answerFields');
                    const count = container.querySelectorAll('.answer-row').length;
                    const row = document.createElement('div');
                    row.className = 'answer-row';
                    row.innerHTML = `
                        <input type="text" name="options[]" class="input-field" placeholder="Answer ${count + 1}" required>
                        <button type="button" class="remove-btn" onclick="this.parentNode.remove()">❌</button>
                    `;
                    container.appendChild(row);
                });
            </script>

        <?php elseif (!$poll): ?>

            <div class="content-box center-text">
                <p>No poll currently active.</p>

                <?php if ($CAN_EDIT): ?>
                    <a href="poll.php?action=create" class="button">Create New Poll</a>
                <?php endif; ?>
            </div>

        <?php else: ?>

            <div class="content-box">
                <h3 class="section-title">Current Poll</h3>

                <p><strong><?= htmlspecialchars($poll[0]) ?></strong></p>

                <?php foreach (array_slice($poll, 1) as $i => $opt): ?>
                    <p><?= htmlspecialchars($opt) ?> — <strong><?= $votes[$i] ?? 0 ?></strong> votes</p>
                <?php endforeach; ?>

                <?php if ($CAN_EDIT): ?>
                    <div style="margin-top:20px;">
                        <a href="poll.php?action=edit" class="button" style="margin-right:10px;">Edit Poll</a>
                        <a href="poll.php?action=reset" class="button" style="background:#ffaa00;color:#000;margin-right:10px;">Reset Votes</a>
                        <a href="poll.php?action=delete" class="button" style="background:#900;color:#fff;">Delete Poll</a>
                    </div>
                <?php endif; ?>
            </div>

        <?php endif; ?>

    </div>
</div>

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