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

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

$commentsFile = __DIR__ . '/../data/comments.txt';
$bannedFile   = __DIR__ . '/../data/banned_ips.txt';

$comments = file_exists($commentsFile) ? file($commentsFile, FILE_IGNORE_NEW_LINES) : [];
$banned   = file_exists($bannedFile)   ? file($bannedFile, FILE_IGNORE_NEW_LINES)   : [];

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

/* ============================================================
   HANDLE ACTIONS (EDIT PERMISSIONS REQUIRED)
   ============================================================ */

if (in_array($action, ['approve','delete','ban','unban','save']) && !$CAN_EDIT) {
    die("<h1>Access Denied</h1><p>You do not have permission to modify comments.</p>");
}

/* APPROVE */
if ($action === 'approve' && $id !== null) {
    $updated = [];

    foreach ($comments as $line) {
        $parts = explode('|', $line);
        if ($parts[0] == $id) {
            $parts[5] = 'yes';
            $line = implode('|', $parts);
        }
        $updated[] = $line;
    }

    file_put_contents($commentsFile, implode("\n", $updated));
    header("Location: comments.php");
    exit;
}

/* DELETE */
if ($action === 'delete' && $id !== null) {
    $updated = [];

    foreach ($comments as $line) {
        $parts = explode('|', $line);
        if ($parts[0] == $id) continue;
        $updated[] = $line;
    }

    file_put_contents($commentsFile, implode("\n", $updated));
    header("Location: comments.php");
    exit;
}

/* BAN */
if ($action === 'ban' && $id !== null) {
    foreach ($comments as $line) {
        $parts = explode('|', $line);
        if ($parts[0] == $id) {
            $ip = $parts[3];
            if (!in_array($ip, $banned)) {
                file_put_contents($bannedFile, $ip . "\n", FILE_APPEND);
            }
            break;
        }
    }

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

/* UNBAN */
if ($action === 'unban' && $id !== null) {
    foreach ($comments as $line) {
        $parts = explode('|', $line);
        if ($parts[0] == $id) {
            $ip = $parts[3];
            break;
        }
    }

    $banned = array_diff($banned, [$ip]);
    file_put_contents($bannedFile, implode("\n", $banned));

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

/* ============================================================
   EDIT MODE (EDIT PERMISSION REQUIRED)
   ============================================================ */

if ($action === 'edit' && $id !== null) {

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

    foreach ($comments as $line) {
        $parts = explode('|', $line);
        if ($parts[0] == $id) {
            $editName = $parts[1];
            $editMsg  = $parts[2];
            break;
        }
    }
    ?>

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

            <h1 class="section-title center-text">✏️ Edit Comment</h1>

            <div class="content-box">
                <form method="POST" action="comments.php?action=save&id=<?= $id ?>">
                    <input type="text" name="name" class="input-field" value="<?= htmlspecialchars($editName) ?>" required>
                    <textarea name="msg" class="input-field" required><?= htmlspecialchars($editMsg) ?></textarea>
                    <button type="submit" class="button">Save Changes</button>
                </form>
            </div>

        </div>
    </div>

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

/* ============================================================
   SAVE EDITED COMMENT
   ============================================================ */

if ($action === 'save' && $id !== null) {

    if (!$CAN_EDIT) {
        die("<h1>Access Denied</h1><p>You cannot save edited comments.</p>");
    }

    $newName = trim($_POST['name']);
    $newMsg  = trim($_POST['msg']);

    $updated = [];

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

        if ($parts[0] == $id) {
            $parts[1] = $newName;
            $parts[2] = $newMsg;
            $line = implode('|', $parts);
        }

        $updated[] = $line;
    }

    file_put_contents($commentsFile, implode("\n", $updated));
    header("Location: comments.php");
    exit;
}
?>

<!-- ============================================================
     MAIN COMMENT ADMIN LIST
     ============================================================ -->

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

        <h1 class="section-title center-text">💬 Manage Comments</h1>

        <div class="admin-grid">

            <?php if (!$comments): ?>
                <p>No comments found.</p>
            <?php else: ?>

                <?php foreach ($comments as $line): 
                    [$cid, $name, $msg, $ip, $ts, $approved] = explode('|', $line);
                ?>
                    <div class="admin-card" style="text-align:left;">

                        <strong><?= htmlspecialchars($name) ?></strong><br>
                        <small><?= date('M j, Y g:i A', strtotime($ts)) ?></small><br>
                        <small>IP: <?= htmlspecialchars($ip) ?></small>

                        <div style="margin:10px 0;"><?= nl2br(htmlspecialchars($msg)) ?></div>

                        <!-- APPROVE -->
                        <?php if ($approved === 'yes'): ?>
                            <span style="color:#4ff;font-weight:bold;">Approved</span>
                        <?php elseif ($CAN_EDIT): ?>
                            <a href="comments.php?action=approve&id=<?= $cid ?>" class="button" style="margin-right:10px;">Approve</a>
                        <?php endif; ?>

                        <!-- EDIT -->
                        <?php if ($CAN_EDIT): ?>
                            <a href="comments.php?action=edit&id=<?= $cid ?>" class="button" style="background:#ffaa00;color:#000;margin-right:10px;">Edit</a>
                        <?php endif; ?>

                        <!-- DELETE -->
                        <?php if ($CAN_EDIT): ?>
                            <a href="comments.php?action=delete&id=<?= $cid ?>" class="button" style="background:#900;color:#fff;margin-right:10px;">Delete</a>
                        <?php endif; ?>

                        <!-- BAN / UNBAN -->
                        <?php if ($CAN_EDIT): ?>
                            <?php if (in_array($ip, $banned)): ?>
                                <span style="color:#ff0033;font-weight:bold;">IP BANNED</span>
                                <a href="comments.php?action=unban&id=<?= $cid ?>" class="button" style="background:#4ff;color:#000;">Unban</a>
                            <?php else: ?>
                                <a href="comments.php?action=ban&id=<?= $cid ?>" class="button" style="background:#ff0033;color:#fff;">Ban IP</a>
                            <?php endif; ?>
                        <?php endif; ?>

                    </div>
                <?php endforeach; ?>

            <?php endif; ?>

        </div>

    </div>
</div>

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