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

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

$djsFile     = __DIR__ . '/../data/djs.txt';
$imageDir    = __DIR__ . '/assets/djs/';   // filesystem path for uploads
$webImageDir = 'assets/djs/';              // web path prefix

$djs = [];

/* ------------------------------------------------------------
   LOAD DJ DATA
   Format per entry:
   Name
   Bio (one or more lines)
   Image path or URL
   ---
------------------------------------------------------------ */
if (file_exists($djsFile)) {
    $raw = file_get_contents($djsFile);
    $entries = preg_split('/^\s*---\s*$/m', $raw);

    foreach ($entries as $entry) {
        $entry = trim($entry);
        if ($entry === '') {
            continue;
        }

        $lines = array_filter(explode("\n", $entry), 'strlen');
        $lines = array_map('trim', $lines);

        if (count($lines) < 2) {
            continue;
        }

        $name = array_shift($lines);
        $rawImage = array_pop($lines);
        $bio = trim(implode("\n", $lines));

        $imgSrc = '';
        if (!empty($rawImage)) {
            if (filter_var($rawImage, FILTER_VALIDATE_URL)) {
                $imgSrc = $rawImage;
            } else {
                // Treat as web path relative to public root
                $imgSrc = $rawImage;
            }
        }

        $djs[] = [
            'name'      => $name,
            'bio'       => $bio,
            'image'     => $imgSrc,
            'raw_image' => $rawImage
        ];
    }
}

/* ------------------------------------------------------------
   SAVE ORDER (EDIT ACTION)
------------------------------------------------------------ */
if (isset($_POST['order'])) {

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

    $newOrder = json_decode($_POST['order'], true);
    $newList = [];

    foreach ($newOrder as $index) {
        if (!isset($djs[$index])) {
            continue;
        }
        $dj = $djs[$index];

        $entry = $dj['name'] . "\n" .
                 $dj['bio'] . "\n" .
                 $dj['raw_image'] . "\n---\n";

        $newList[] = $entry;
    }

    file_put_contents($djsFile, implode('', $newList));
    header("Location: djs.php");
    exit;
}

/* ------------------------------------------------------------
   ADD / EDIT DJ (ADD ACTION)
------------------------------------------------------------ */
if (isset($_POST['save_dj'])) {

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

    $name      = trim($_POST['name']);
    $bio       = trim($_POST['bio']);
    $imageURL  = trim($_POST['image_url']);
    $upload    = $_FILES['image_upload'] ?? null;

    $slug = strtolower(preg_replace('/[^a-z0-9]+/', '_', $name));
    $finalImage = $imageURL;

    // Handle upload
    if (!empty($upload['tmp_name']) && $upload['size'] > 0) {
        $ext = strtolower(pathinfo($upload['name'], PATHINFO_EXTENSION));
        $filename = $slug . '.' . $ext;
        $target = $imageDir . $filename;

        if (move_uploaded_file($upload['tmp_name'], $target)) {
            $finalImage = $webImageDir . $filename;
        }
    }

    if ($finalImage === '') {
        $finalImage = $webImageDir . $slug . '.jpg'; // optional fallback guess
    }

    $entry = $name . "\n" .
             $bio . "\n" .
             $finalImage . "\n---\n";

    file_put_contents($djsFile, $entry, FILE_APPEND);

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

/* ------------------------------------------------------------
   DELETE DJ (EDIT ACTION)
------------------------------------------------------------ */
if (isset($_GET['delete'])) {

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

    $index = (int)$_GET['delete'];
    if (isset($djs[$index])) {
        unset($djs[$index]);
    }

    $newList = [];
    foreach ($djs as $dj) {
        $entry = $dj['name'] . "\n" .
                 $dj['bio'] . "\n" .
                 $dj['raw_image'] . "\n---\n";
        $newList[] = $entry;
    }

    file_put_contents($djsFile, implode('', $newList));
    header("Location: djs.php");
    exit;
}
?>

<style>
.draggable { cursor: grab; }
.draggable:active { cursor: grabbing; }
.drag-over {
    outline: 3px dashed #4ff;
    border-radius: 10px;
}
</style>

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

        <h1 class="section-title center-text">🎧 Manage DJs</h1>
        <div class="vinyl-divider center-divider"></div>

        <!-- ADD DJ FORM (ONLY IF CAN EDIT) -->
        <?php if ($CAN_EDIT): ?>
        <div class="neon-card">
            <h3 class="section-title">➕ Add New DJ</h3>

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

                <label>Name:</label>
                <input type="text" name="name" class="input-field" required>

                <label>Bio:</label>
                <textarea name="bio" class="input-field" required></textarea>

                <label>Image URL (optional):</label>
                <input type="text" name="image_url" class="input-field">

                <label>Upload Image (optional):</label>
                <input type="file" name="image_upload" class="input-field">

                <button type="submit" name="save_dj" class="button radio-static">Save DJ</button>
            </form>
        </div>
        <?php else: ?>
            <div class="neon-card center-text" style="opacity:0.6;">
                <p>You can view DJs, but you cannot add new ones.</p>
            </div>
        <?php endif; ?>

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

        <!-- DRAG & DROP DJ LIST -->
        <h3 class="section-title center-text">🎛️ Drag to Reorder DJs</h3>

        <form method="POST" id="orderForm">
            <input type="hidden" name="order" id="orderInput">

            <div id="djList">
                <?php foreach ($djs as $i => $dj): ?>
                    <div class="neon-card dj-card <?= $CAN_EDIT ? 'draggable' : '' ?>"
                         <?= $CAN_EDIT ? 'draggable="true"' : '' ?>
                         data-index="<?= $i ?>">

                        <?php if (!empty($dj['image'])): ?>
                            <div class="dj-image-wrap">
                                <img src="<?= htmlspecialchars($dj['image']) ?>" class="dj-image" alt="<?= htmlspecialchars($dj['name']) ?>">
                            </div>
                        <?php endif; ?>

                        <h2 class="dj-name"><?= htmlspecialchars($dj['name']) ?></h2>
                        <p class="dj-bio"><?= nl2br(htmlspecialchars($dj['bio'])) ?></p>

                        <?php if ($CAN_EDIT): ?>
                            <a href="djs.php?delete=<?= $i ?>"
                               class="button"
                               style="background:#900;color:#fff;">
                               Delete
                            </a>
                        <?php endif; ?>
                    </div>

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

            <?php if ($CAN_EDIT): ?>
            <div class="content-box center-text">
                <button type="submit" class="button radio-static">💾 Save Order</button>
            </div>
            <?php endif; ?>
        </form>

    </div>
</div>

<?php if ($CAN_EDIT): ?>
<script>
const list = document.getElementById('djList');
let dragSrc = null;

list.addEventListener('dragstart', e => {
    const card = e.target.closest('.draggable');
    if (!card) return;
    dragSrc = card;
    e.dataTransfer.effectAllowed = 'move';
});

list.addEventListener('dragover', e => {
    e.preventDefault();
    const target = e.target.closest('.draggable');
    if (target && target !== dragSrc) {
        target.classList.add('drag-over');
    }
});

list.addEventListener('dragleave', e => {
    const target = e.target.closest('.draggable');
    if (target) target.classList.remove('drag-over');
});

list.addEventListener('drop', e => {
    e.preventDefault();
    const target = e.target.closest('.draggable');
    if (target && target !== dragSrc) {
        target.classList.remove('drag-over');
        list.insertBefore(dragSrc, target);
    }
});

document.getElementById('orderForm').addEventListener('submit', () => {
    const order = [];
    document.querySelectorAll('.draggable').forEach(card => {
        order.push(card.dataset.index);
    });
    document.getElementById('orderInput').value = JSON.stringify(order);
});
</script>
<?php endif; ?>

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