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

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

$friendsFile = __DIR__ . '/../data/friends.txt';
$imageDir = __DIR__ . '/assets/friends/';
$webImageDir = 'assets/friends/';

$friends = [];

/* ------------------------------------------------------------
   LOAD FRIENDS
------------------------------------------------------------ */
if (file_exists($friendsFile)) {
    $lines = file($friendsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    foreach ($lines as $line) {
        list($id, $name, $desc, $link, $image) = explode('|', $line);

        $imgSrc = '';
        if ($image) {
            $imgSrc = str_starts_with($image, 'http')
                ? $image
                : ($webImageDir . $image);
        }

        $friends[] = [
            'id'        => $id,
            'name'      => $name,
            'desc'      => $desc,
            'link'      => $link,
            'image'     => $imgSrc,
            'raw_image' => $image
        ];
    }
}

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

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

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

    foreach ($order as $index) {
        $f = $friends[$index];
        $newList[] = implode('|', [
            $f['id'],
            $f['name'],
            $f['desc'],
            $f['link'],
            $f['raw_image']
        ]);
    }

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

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

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

    $id   = uniqid();
    $name = trim($_POST['name']);
    $desc = trim($_POST['desc']);
    $link = trim($_POST['link']);
    $imageURL = trim($_POST['image_url']);
    $upload = $_FILES['image_upload'];

    $finalImage = $imageURL;

    if ($upload['size'] > 0) {
        $ext = strtolower(pathinfo($upload['name'], PATHINFO_EXTENSION));
        $filename = $id . '.' . $ext;
        move_uploaded_file($upload['tmp_name'], $imageDir . $filename);
        $finalImage = $filename;
    }

    $entry = implode('|', [$id, $name, $desc, $link, $finalImage]) . "\n";
    file_put_contents($friendsFile, $entry, FILE_APPEND);

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

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

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

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

    foreach ($friends as $f) {
        if ($f['id'] !== $id) {
            $newList[] = implode('|', [
                $f['id'],
                $f['name'],
                $f['desc'],
                $f['link'],
                $f['raw_image']
            ]);
        }
    }

    file_put_contents($friendsFile, implode("\n", $newList));
    header("Location: friends.php");
    exit;
}
?>

<style>
.friends-grid-admin {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 30px;
}
.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 Friends</h1>
        <div class="vinyl-divider center-divider"></div>

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

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

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

                <label>Description (single line):</label>
                <input type="text" name="desc" class="input-field" required>

                <label>Website Link:</label>
                <input type="text" name="link" class="input-field">

                <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_friend" class="button radio-static">Save Friend</button>
            </form>
        </div>
        <?php else: ?>
            <div class="neon-card center-text" style="opacity:0.6;">
                <p>You can view Friends, but you cannot add new ones.</p>
            </div>
        <?php endif; ?>

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

        <h3 class="section-title center-text">🎛️ Drag to Reorder Friends</h3>

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

            <div id="friendsList" class="friends-grid-admin">

                <?php foreach ($friends as $i => $f): ?>
                    <div class="neon-card friend-card <?= $CAN_EDIT ? 'draggable' : '' ?>"
                         <?= $CAN_EDIT ? 'draggable="true"' : '' ?>
                         data-index="<?= $i ?>">

                        <?php if ($f['image']): ?>
                            <div class="friend-image-wrap">
                                <img src="<?= htmlspecialchars($f['image']) ?>" class="friend-image">
                            </div>
                        <?php endif; ?>

                        <h2 class="friend-name"><?= htmlspecialchars($f['name']) ?></h2>
                        <p class="friend-desc"><?= htmlspecialchars($f['desc']) ?></p>

                        <?php if ($f['link']): ?>
                            <a href="<?= htmlspecialchars($f['link']) ?>" target="_blank" class="button radio-static">🔗 Visit</a>
                        <?php endif; ?>

                        <?php if ($CAN_EDIT): ?>
                            <a href="friends.php?delete=<?= $f['id'] ?>"
                               class="button"
                               style="background:#900;color:#fff;margin-top:10px;">
                               Delete
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>

            </div>

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

    </div>
</div>

<?php if ($CAN_EDIT): ?>
<script>
/* Drag & Drop only enabled if CAN_EDIT */
const list = document.getElementById('friendsList');
let dragSrc = null;

list.addEventListener('dragstart', e => {
    dragSrc = e.target;
    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'; ?>
