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

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

$requestsFile = __DIR__ . '/../data/requests.txt';
$bannedFile   = __DIR__ . '/../data/banned_ips.txt';

$requests = file_exists($requestsFile) ? file($requestsFile, FILE_IGNORE_NEW_LINES) : [];
$banned   = file_exists($bannedFile)   ? file($bannedFile, FILE_IGNORE_NEW_LINES)   : [];

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

/* ------------------------------------------------------------
   PERMISSION CHECK FOR ALL ACTIONS
------------------------------------------------------------ */
$editActions = ['approve','delete','ban','unban','save','edit'];

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

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

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

        if ($parts[0] == $id) {
            $parts[7] = 'yes';
            $line = implode('|', $parts);
        }

        $updated[] = $line;
    }

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

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

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

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

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

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

/* ------------------------------------------------------------
   UNBAN IP
------------------------------------------------------------ */
if ($action === 'unban' && $id !== null) {
    $ip = $_GET['ip'] ?? null;

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

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

/* ------------------------------------------------------------
   SAVE EDIT
------------------------------------------------------------ */
if ($action === 'save' && $id !== null && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $updated = [];

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

        if ($parts[0] == $id) {
            $parts[1] = trim($_POST['name']);
            $parts[2] = trim($_POST['song']);
            $parts[3] = trim($_POST['artist']);
            $parts[4] = trim($_POST['message']);
            $parts[5] = trim($_POST['dedication']);
            $line = implode('|', $parts);
        }

        $updated[] = $line;
    }

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

/* ------------------------------------------------------------
   EDIT MODE
------------------------------------------------------------ */
if ($action === 'edit' && $id !== null) {

    foreach ($requests as $line) {
        $parts = explode('|', $line);
        if ($parts[0] == $id) {
            [$rid,$name,$song,$artist,$msg,$ded,$ts,$approved,$ip] = $parts;
            break;
        }
    }
    ?>

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

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

            <div class="content-box">
                <form method="POST" action="requests.php?action=save&id=<?= $id ?>">

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

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

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

                    <label>Message:</label>
                    <textarea name="message" class="input-field"><?= htmlspecialchars($msg) ?></textarea>

                    <label>Dedication:</label>
                    <input type="text" name="dedication" class="input-field" value="<?= htmlspecialchars($ded) ?>">

                    <button type="submit" class="button radio-static">Save Changes</button>
                </form>
            </div>

        </div>
    </div>

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

/* ------------------------------------------------------------
   SPLIT REQUESTS INTO PENDING + APPROVED
------------------------------------------------------------ */
$pending = [];
$approved = [];

foreach ($requests as $line) {
    $parts = explode('|', $line);
    if (count($parts) >= 8) {
        if ($parts[7] === 'yes') $approved[] = $parts;
        else $pending[] = $parts;
    }
}

$pending = array_reverse($pending);
$approved = array_reverse($approved);
?>

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

        <h1 class="section-title center-text">🎧 Manage Song Requests</h1>

        <!-- NOW PLAYING -->
        <div class="neon-card" style="margin-bottom:20px;">
            <h3 class="section-title">🎶 Now Playing</h3>
            <div class="about-text">
                <?php include __DIR__ . '/../nowplaying.php'; ?>
            </div>
        </div>

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

        <!-- PENDING REQUESTS -->
        <div class="content-box">
            <h3 class="section-title">⏳ Pending Requests</h3>

            <?php if (!$pending): ?>
                <p>No pending requests.</p>
            <?php else: ?>
                <?php foreach ($pending as $req): ?>
                    <?php list($rid,$name,$song,$artist,$msg,$ded,$ts,$appr,$ip) = $req; ?>

                    <div class="neon-card request-card">

                        <h4><?= htmlspecialchars($song) ?> — <span><?= htmlspecialchars($artist) ?></span></h4>

                        <p class="about-text">
                            Requested by <strong><?= htmlspecialchars($name) ?></strong>
                            on <?= date('M j, Y g:i A', strtotime($ts)) ?>
                        </p>

                        <?php if ($msg): ?>
                            <p class="about-text"><em>"<?= htmlspecialchars($msg) ?>"</em></p>
                        <?php endif; ?>

                        <?php if ($ded): ?>
                            <p class="about-text dedication">💙 <?= htmlspecialchars($ded) ?></p>
                        <?php endif; ?>

                        <p class="about-text"><strong>IP:</strong> <?= htmlspecialchars($ip) ?></p>

                        <?php if ($CAN_EDIT): ?>
                        <div style="margin-top:10px;">
                            <a href="requests.php?action=approve&id=<?= $rid ?>" class="button" style="margin-right:10px;">Approve</a>
                            <a href="requests.php?action=edit&id=<?= $rid ?>" class="button" style="background:#ffaa00;color:#000;margin-right:10px;">Edit</a>
                            <a href="requests.php?action=delete&id=<?= $rid ?>" class="button" style="background:#900;color:#fff;margin-right:10px;">Delete</a>

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

                    </div>

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

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

        <!-- APPROVED REQUESTS -->
        <div class="content-box">
            <h3 class="section-title">📻 Approved Requests</h3>

            <?php if (!$approved): ?>
                <p>No approved requests yet.</p>
            <?php else: ?>
                <?php foreach ($approved as $req): ?>
                    <?php list($rid,$name,$song,$artist,$msg,$ded,$ts,$appr,$ip) = $req; ?>

                    <div class="neon-card request-card">

                        <h4><?= htmlspecialchars($song) ?> — <span><?= htmlspecialchars($artist) ?></span></h4>

                        <p class="about-text">
                            Requested by <strong><?= htmlspecialchars($name) ?></strong>
                            on <?= date('M j, Y g:i A', strtotime($ts)) ?>
                        </p>

                        <?php if ($msg): ?>
                            <p class="about-text"><em>"<?= htmlspecialchars($msg) ?>"</em></p>
                        <?php endif; ?>

                        <?php if ($ded): ?>
                            <p class="about-text dedication">💙 <?= htmlspecialchars($ded) ?></p>
                        <?php endif; ?>

                        <p class="about-text"><strong>IP:</strong> <?= htmlspecialchars($ip) ?></p>

                        <?php if ($CAN_EDIT): ?>
                        <div style="margin-top:10px;">
                            <a href="requests.php?action=edit&id=<?= $rid ?>" class="button" style="background:#ffaa00;color:#000;margin-right:10px;">Edit</a>
                            <a href="requests.php?action=delete&id=<?= $rid ?>" class="button" style="background:#900;color:#fff;margin-right:10px;">Delete</a>

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

                    </div>

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

    </div>
</div>

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