<?php
/**
 * Nexora VE Networks - Content Hub
 * AdminCP manager for visual guides and community media shown on the home page.
 */
if (!defined('access')) die('Direct access not permitted.');

$nexContentConfigKey = 'content_hub';
$nexContentConfigFile = __PATH_CONFIGS__ . 'content_hub.json';
$nexContentUploadDir = __PATH_TEMPLATE_ROOT__ . 'img/content-hub/';
$nexContentPublicBase = __PATH_TEMPLATE_IMG__ . 'content-hub/';

function nexoraContentHubLoadConfig() {
    $cfg = loadConfig('content_hub');
    if (!is_array($cfg)) $cfg = array();
    if (!isset($cfg['settings']) || !is_array($cfg['settings'])) $cfg['settings'] = array();
    if (!isset($cfg['items']) || !is_array($cfg['items'])) $cfg['items'] = array();
    return $cfg;
}

function nexoraContentHubEnsureStorage() {
    global $nexContentConfigFile, $nexContentUploadDir;
    if (!is_dir($nexContentUploadDir)) {
        if (!@mkdir($nexContentUploadDir, 0755, true) && !is_dir($nexContentUploadDir)) {
            throw new Exception('Could not create the content upload directory.');
        }
    }
    if (!file_exists($nexContentConfigFile)) {
        $initial = array('settings' => array(), 'items' => array());
        if (@file_put_contents($nexContentConfigFile, json_encode($initial, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n", LOCK_EX) === false) {
            throw new Exception('Could not create content_hub.json.');
        }
    }
    if (!is_writable($nexContentConfigFile)) {
        throw new Exception('content_hub.json is not writable.');
    }
    if (!is_writable($nexContentUploadDir)) {
        throw new Exception('The content-hub image folder is not writable.');
    }
}

function nexoraContentHubSaveConfig($cfg) {
    global $nexContentConfigFile;
    $json = json_encode($cfg, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($json === false || @file_put_contents($nexContentConfigFile, $json . "\n", LOCK_EX) === false) {
        throw new Exception('Could not save the Content Hub configuration.');
    }
}

function nexoraContentHubCleanText($value, $maxLength) {
    $value = trim(strip_tags((string)$value));
    if (function_exists('mb_substr')) return mb_substr($value, 0, $maxLength, 'UTF-8');
    return substr($value, 0, $maxLength);
}

function nexoraContentHubNormalizeUrl($value) {
    $value = trim((string)$value);
    if ($value === '') return '';
    if (!filter_var($value, FILTER_VALIDATE_URL)) {
        throw new Exception('The external link is not a valid URL.');
    }
    $scheme = strtolower((string)parse_url($value, PHP_URL_SCHEME));
    if (!in_array($scheme, array('http', 'https'), true)) {
        throw new Exception('Only http:// and https:// links are allowed.');
    }
    return $value;
}

function nexoraContentHubMakeId($title) {
    $slug = strtolower(trim((string)$title));
    if (function_exists('iconv')) {
        $converted = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $slug);
        if ($converted !== false) $slug = $converted;
    }
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    $slug = trim($slug, '-');
    if ($slug === '') $slug = 'contenido';
    return $slug . '-' . date('ymdHis') . '-' . substr(md5(uniqid('', true)), 0, 5);
}

function nexoraContentHubFindIndex($items, $id) {
    foreach ($items as $idx => $item) {
        if (is_array($item) && isset($item['id']) && (string)$item['id'] === (string)$id) return $idx;
    }
    return -1;
}

function nexoraContentHubNormalizeUploadArray($field) {
    $out = array();
    if (!isset($_FILES[$field])) return $out;
    $f = $_FILES[$field];
    if (is_array($f['name'])) {
        foreach ($f['name'] as $i => $name) {
            $out[] = array(
                'name' => $name,
                'type' => isset($f['type'][$i]) ? $f['type'][$i] : '',
                'tmp_name' => isset($f['tmp_name'][$i]) ? $f['tmp_name'][$i] : '',
                'error' => isset($f['error'][$i]) ? $f['error'][$i] : UPLOAD_ERR_NO_FILE,
                'size' => isset($f['size'][$i]) ? $f['size'][$i] : 0,
            );
        }
    } else {
        $out[] = $f;
    }
    return $out;
}

function nexoraContentHubStoreUpload($file, $itemId) {
    global $nexContentUploadDir;
    if (!isset($file['error']) || (int)$file['error'] === UPLOAD_ERR_NO_FILE) return '';
    if ((int)$file['error'] !== UPLOAD_ERR_OK) throw new Exception('An image upload failed. Error code: ' . (int)$file['error']);
    if (!isset($file['size']) || (int)$file['size'] <= 0 || (int)$file['size'] > 8 * 1024 * 1024) {
        throw new Exception('Each image must be smaller than 8 MB.');
    }
    if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
        throw new Exception('Invalid uploaded file.');
    }

    $info = @getimagesize($file['tmp_name']);
    if (!$info || empty($info['mime'])) throw new Exception('One uploaded file is not a valid image.');
    if ((int)$info[0] > 7000 || (int)$info[1] > 7000) throw new Exception('Image dimensions are too large. Maximum: 7000 x 7000 px.');

    $mimeMap = array(
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        'image/gif' => 'gif'
    );
    $mime = strtolower($info['mime']);
    if (!isset($mimeMap[$mime])) throw new Exception('Allowed image formats: JPG, PNG, WEBP and GIF.');

    $safeId = preg_replace('/[^a-z0-9_-]+/i', '-', (string)$itemId);
    $filename = 'content-' . trim($safeId, '-') . '-' . date('YmdHis') . '-' . substr(md5(uniqid('', true)), 0, 8) . '.' . $mimeMap[$mime];
    $target = $nexContentUploadDir . $filename;
    if (!@move_uploaded_file($file['tmp_name'], $target)) throw new Exception('Could not store an uploaded image.');
    @chmod($target, 0644);
    return $filename;
}

function nexoraContentHubDeleteFile($file) {
    global $nexContentUploadDir;
    $file = trim((string)$file);
    if ($file === '' || preg_match('#^https?://#i', $file)) return;
    $base = basename(str_replace('\\', '/', $file));
    if ($base !== $file) return;
    $path = $nexContentUploadDir . $base;
    if (is_file($path)) @unlink($path);
}

function nexoraContentHubRedirect() {
    header('Location: ' . admincp_base('content_hub'));
    exit;
}

try {
    nexoraContentHubEnsureStorage();
    $cfg = nexoraContentHubLoadConfig();

    if (isset($_POST['content_settings_save'])) {
        $cfg['settings']['title'] = nexoraContentHubCleanText(isset($_POST['section_title']) ? $_POST['section_title'] : '', 100);
        $cfg['settings']['subtitle'] = nexoraContentHubCleanText(isset($_POST['section_subtitle']) ? $_POST['section_subtitle'] : '', 240);
        nexoraContentHubSaveConfig($cfg);
        message('success', 'Content Hub section settings updated.');
    }

    if (isset($_POST['content_add'])) {
        $title = nexoraContentHubCleanText(isset($_POST['title']) ? $_POST['title'] : '', 100);
        if ($title === '') throw new Exception('Title is required.');
        $id = nexoraContentHubMakeId($title);
        $item = array(
            'id' => $id,
            'enabled' => 1,
            'category' => nexoraContentHubCleanText(isset($_POST['category']) ? $_POST['category'] : 'Contenido', 60),
            'title' => $title,
            'description' => nexoraContentHubCleanText(isset($_POST['description']) ? $_POST['description'] : '', 500),
            'credit' => nexoraContentHubCleanText(isset($_POST['credit']) ? $_POST['credit'] : '', 100),
            'link' => nexoraContentHubNormalizeUrl(isset($_POST['link']) ? $_POST['link'] : ''),
            'link_label' => nexoraContentHubCleanText(isset($_POST['link_label']) ? $_POST['link_label'] : 'Ver recurso', 50),
            'media' => array()
        );
        foreach (nexoraContentHubNormalizeUploadArray('content_files') as $upload) {
            $stored = nexoraContentHubStoreUpload($upload, $id);
            if ($stored !== '') $item['media'][] = array('file' => $stored, 'caption' => '');
        }
        if (empty($item['media'])) throw new Exception('Upload at least one image for the new content item.');
        $cfg['items'][] = $item;
        nexoraContentHubSaveConfig($cfg);
        nexoraContentHubRedirect();
    }

    if (isset($_POST['content_save']) && isset($_POST['item_id'])) {
        $id = (string)$_POST['item_id'];
        $idx = nexoraContentHubFindIndex($cfg['items'], $id);
        if ($idx < 0) throw new Exception('Content item not found.');
        $cfg['items'][$idx]['enabled'] = isset($_POST['enabled']) ? 1 : 0;
        $cfg['items'][$idx]['category'] = nexoraContentHubCleanText(isset($_POST['category']) ? $_POST['category'] : '', 60);
        $cfg['items'][$idx]['title'] = nexoraContentHubCleanText(isset($_POST['title']) ? $_POST['title'] : '', 100);
        if ($cfg['items'][$idx]['title'] === '') throw new Exception('Title is required.');
        $cfg['items'][$idx]['description'] = nexoraContentHubCleanText(isset($_POST['description']) ? $_POST['description'] : '', 500);
        $cfg['items'][$idx]['credit'] = nexoraContentHubCleanText(isset($_POST['credit']) ? $_POST['credit'] : '', 100);
        $cfg['items'][$idx]['link'] = nexoraContentHubNormalizeUrl(isset($_POST['link']) ? $_POST['link'] : '');
        $cfg['items'][$idx]['link_label'] = nexoraContentHubCleanText(isset($_POST['link_label']) ? $_POST['link_label'] : 'Ver recurso', 50);
        nexoraContentHubSaveConfig($cfg);
        nexoraContentHubRedirect();
    }

    if (isset($_POST['content_add_media']) && isset($_POST['item_id'])) {
        $id = (string)$_POST['item_id'];
        $idx = nexoraContentHubFindIndex($cfg['items'], $id);
        if ($idx < 0) throw new Exception('Content item not found.');
        if (!isset($cfg['items'][$idx]['media']) || !is_array($cfg['items'][$idx]['media'])) $cfg['items'][$idx]['media'] = array();
        $added = 0;
        foreach (nexoraContentHubNormalizeUploadArray('content_files') as $upload) {
            $stored = nexoraContentHubStoreUpload($upload, $id);
            if ($stored !== '') {
                $cfg['items'][$idx]['media'][] = array('file' => $stored, 'caption' => '');
                $added++;
            }
        }
        if ($added < 1) throw new Exception('Select at least one image to upload.');
        nexoraContentHubSaveConfig($cfg);
        nexoraContentHubRedirect();
    }

    if (isset($_POST['content_save_media']) && isset($_POST['item_id'])) {
        $id = (string)$_POST['item_id'];
        $idx = nexoraContentHubFindIndex($cfg['items'], $id);
        if ($idx < 0) throw new Exception('Content item not found.');
        $mediaIndex = isset($_POST['media_index']) ? (int)$_POST['media_index'] : -1;
        if (!isset($cfg['items'][$idx]['media'][$mediaIndex])) throw new Exception('Media page not found.');
        $cfg['items'][$idx]['media'][$mediaIndex]['caption'] = nexoraContentHubCleanText(isset($_POST['caption']) ? $_POST['caption'] : '', 120);
        $uploads = nexoraContentHubNormalizeUploadArray('replacement_file');
        $oldFileToDelete = '';
        if (!empty($uploads) && isset($uploads[0]['error']) && (int)$uploads[0]['error'] !== UPLOAD_ERR_NO_FILE) {
            $newFile = nexoraContentHubStoreUpload($uploads[0], $id);
            if ($newFile !== '') {
                $oldFileToDelete = isset($cfg['items'][$idx]['media'][$mediaIndex]['file']) ? $cfg['items'][$idx]['media'][$mediaIndex]['file'] : '';
                $cfg['items'][$idx]['media'][$mediaIndex]['file'] = $newFile;
            }
        }
        nexoraContentHubSaveConfig($cfg);
        if ($oldFileToDelete !== '') nexoraContentHubDeleteFile($oldFileToDelete);
        nexoraContentHubRedirect();
    }

    if (isset($_POST['content_delete_media']) && isset($_POST['item_id'])) {
        $id = (string)$_POST['item_id'];
        $idx = nexoraContentHubFindIndex($cfg['items'], $id);
        $mediaIndex = isset($_POST['media_index']) ? (int)$_POST['media_index'] : -1;
        if ($idx < 0 || !isset($cfg['items'][$idx]['media'][$mediaIndex])) throw new Exception('Media page not found.');
        $oldFile = isset($cfg['items'][$idx]['media'][$mediaIndex]['file']) ? $cfg['items'][$idx]['media'][$mediaIndex]['file'] : '';
        array_splice($cfg['items'][$idx]['media'], $mediaIndex, 1);
        nexoraContentHubSaveConfig($cfg);
        nexoraContentHubDeleteFile($oldFile);
        nexoraContentHubRedirect();
    }

    if (isset($_POST['content_move_media']) && isset($_POST['item_id'])) {
        $id = (string)$_POST['item_id'];
        $idx = nexoraContentHubFindIndex($cfg['items'], $id);
        $mediaIndex = isset($_POST['media_index']) ? (int)$_POST['media_index'] : -1;
        $direction = isset($_POST['direction']) ? (string)$_POST['direction'] : '';
        if ($idx < 0 || !isset($cfg['items'][$idx]['media'][$mediaIndex])) throw new Exception('Media page not found.');
        $target = $direction === 'up' ? $mediaIndex - 1 : ($direction === 'down' ? $mediaIndex + 1 : $mediaIndex);
        if ($target >= 0 && $target < count($cfg['items'][$idx]['media']) && $target !== $mediaIndex) {
            $tmp = $cfg['items'][$idx]['media'][$target];
            $cfg['items'][$idx]['media'][$target] = $cfg['items'][$idx]['media'][$mediaIndex];
            $cfg['items'][$idx]['media'][$mediaIndex] = $tmp;
            nexoraContentHubSaveConfig($cfg);
        }
        nexoraContentHubRedirect();
    }

    if (isset($_POST['content_move_item']) && isset($_POST['item_id'])) {
        $id = (string)$_POST['item_id'];
        $idx = nexoraContentHubFindIndex($cfg['items'], $id);
        $direction = isset($_POST['direction']) ? (string)$_POST['direction'] : '';
        if ($idx < 0) throw new Exception('Content item not found.');
        $target = $direction === 'up' ? $idx - 1 : ($direction === 'down' ? $idx + 1 : $idx);
        if ($target >= 0 && $target < count($cfg['items']) && $target !== $idx) {
            $tmp = $cfg['items'][$target];
            $cfg['items'][$target] = $cfg['items'][$idx];
            $cfg['items'][$idx] = $tmp;
            nexoraContentHubSaveConfig($cfg);
        }
        nexoraContentHubRedirect();
    }

    if (isset($_POST['content_delete_item']) && isset($_POST['item_id'])) {
        $id = (string)$_POST['item_id'];
        $idx = nexoraContentHubFindIndex($cfg['items'], $id);
        if ($idx < 0) throw new Exception('Content item not found.');
        $filesToDelete = array();
        if (isset($cfg['items'][$idx]['media']) && is_array($cfg['items'][$idx]['media'])) {
            foreach ($cfg['items'][$idx]['media'] as $media) {
                if (is_array($media) && isset($media['file'])) $filesToDelete[] = $media['file'];
            }
        }
        array_splice($cfg['items'], $idx, 1);
        nexoraContentHubSaveConfig($cfg);
        foreach ($filesToDelete as $fileToDelete) nexoraContentHubDeleteFile($fileToDelete);
        nexoraContentHubRedirect();
    }

    $cfg = nexoraContentHubLoadConfig();
} catch (Exception $ex) {
    message('error', $ex->getMessage());
    $cfg = nexoraContentHubLoadConfig();
}

$sectionTitle = isset($cfg['settings']['title']) ? $cfg['settings']['title'] : 'Contenido y guías clave';
$sectionSubtitle = isset($cfg['settings']['subtitle']) ? $cfg['settings']['subtitle'] : '';
?>
<style>
.nex-admin-content-card{border-left:4px solid #7a4b9e}.nex-admin-content-card .panel-heading{display:flex;justify-content:space-between;align-items:center;gap:10px}.nex-admin-media-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:14px}.nex-admin-media{border:1px solid #ddd;border-radius:5px;padding:10px;background:#fafafa}.nex-admin-media img{display:block;width:100%;height:220px;object-fit:contain;background:#111;border-radius:4px;margin-bottom:10px}.nex-admin-actions{display:flex;gap:5px;flex-wrap:wrap}.nex-admin-order{display:flex;gap:4px}.nex-admin-help{background:#f5f0fb;border:1px solid #e2d6ef;padding:12px 14px;border-radius:5px;margin-bottom:18px}.nex-admin-status{font-size:11px;text-transform:uppercase;letter-spacing:.06em}.nex-admin-status.on{color:#1d7a36}.nex-admin-status.off{color:#a94442}
</style>

<h1 class="page-header">Nexora Content Hub</h1>
<div class="nex-admin-help">
    This module controls the visual content block that replaced the old class slider on the home page. Create guides, community showcases or key announcements; each item can contain one or many image pages. Images are uploaded directly from AdminCP.
</div>

<div class="panel panel-default">
    <div class="panel-heading"><strong>Section heading</strong></div>
    <div class="panel-body">
        <form method="post" action="<?php echo htmlspecialchars(admincp_base('content_hub'), ENT_QUOTES, 'UTF-8'); ?>">
            <div class="form-group">
                <label>Title</label>
                <input type="text" name="section_title" class="form-control" maxlength="100" value="<?php echo htmlspecialchars($sectionTitle, ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div class="form-group">
                <label>Subtitle</label>
                <input type="text" name="section_subtitle" class="form-control" maxlength="240" value="<?php echo htmlspecialchars($sectionSubtitle, ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <button type="submit" name="content_settings_save" value="1" class="btn btn-primary"><i class="fa fa-save"></i> Save section</button>
        </form>
    </div>
</div>

<h2>Published content</h2>
<?php if (empty($cfg['items'])) { ?>
    <div class="alert alert-info">There is no content yet. Create the first item below.</div>
<?php } ?>

<?php foreach ($cfg['items'] as $itemIndex => $item) {
    if (!is_array($item)) continue;
    $itemId = isset($item['id']) ? $item['id'] : '';
    $mediaList = isset($item['media']) && is_array($item['media']) ? $item['media'] : array();
    $isEnabled = !isset($item['enabled']) || (int)$item['enabled'] === 1;
?>
<div class="panel panel-default nex-admin-content-card">
    <div class="panel-heading">
        <div>
            <strong><?php echo htmlspecialchars(isset($item['title']) ? $item['title'] : 'Untitled', ENT_QUOTES, 'UTF-8'); ?></strong>
            <span class="nex-admin-status <?php echo $isEnabled ? 'on' : 'off'; ?>">&nbsp;<?php echo $isEnabled ? 'Visible' : 'Hidden'; ?></span>
        </div>
        <div class="nex-admin-order">
            <form method="post" action="" style="display:inline"><input type="hidden" name="item_id" value="<?php echo htmlspecialchars($itemId, ENT_QUOTES, 'UTF-8'); ?>"><input type="hidden" name="direction" value="up"><button type="submit" name="content_move_item" value="1" class="btn btn-default btn-xs" <?php echo $itemIndex === 0 ? 'disabled' : ''; ?>><i class="fa fa-arrow-up"></i></button></form>
            <form method="post" action="" style="display:inline"><input type="hidden" name="item_id" value="<?php echo htmlspecialchars($itemId, ENT_QUOTES, 'UTF-8'); ?>"><input type="hidden" name="direction" value="down"><button type="submit" name="content_move_item" value="1" class="btn btn-default btn-xs" <?php echo $itemIndex >= count($cfg['items']) - 1 ? 'disabled' : ''; ?>><i class="fa fa-arrow-down"></i></button></form>
        </div>
    </div>
    <div class="panel-body">
        <form method="post" action="" class="row">
            <input type="hidden" name="item_id" value="<?php echo htmlspecialchars($itemId, ENT_QUOTES, 'UTF-8'); ?>">
            <div class="col-md-3 form-group">
                <label>Category</label>
                <input type="text" name="category" class="form-control" maxlength="60" value="<?php echo htmlspecialchars(isset($item['category']) ? $item['category'] : '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Guía, Comunidad, Evento...">
            </div>
            <div class="col-md-5 form-group">
                <label>Title</label>
                <input type="text" name="title" class="form-control" maxlength="100" required value="<?php echo htmlspecialchars(isset($item['title']) ? $item['title'] : '', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div class="col-md-4 form-group">
                <label>Credit / creator</label>
                <input type="text" name="credit" class="form-control" maxlength="100" value="<?php echo htmlspecialchars(isset($item['credit']) ? $item['credit'] : '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Nexora VE Networks / Player name">
            </div>
            <div class="col-md-12 form-group">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="2" maxlength="500"><?php echo htmlspecialchars(isset($item['description']) ? $item['description'] : '', ENT_QUOTES, 'UTF-8'); ?></textarea>
            </div>
            <div class="col-md-8 form-group">
                <label>External link <small class="text-muted">(optional)</small></label>
                <input type="url" name="link" class="form-control" value="<?php echo htmlspecialchars(isset($item['link']) ? $item['link'] : '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="https://youtube.com/... or community post">
            </div>
            <div class="col-md-4 form-group">
                <label>Link button text</label>
                <input type="text" name="link_label" class="form-control" maxlength="50" value="<?php echo htmlspecialchars(isset($item['link_label']) ? $item['link_label'] : 'Ver recurso', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div class="col-md-12 form-group">
                <label><input type="checkbox" name="enabled" value="1" <?php echo $isEnabled ? 'checked' : ''; ?>> Visible on website</label>
            </div>
            <div class="col-md-12">
                <button type="submit" name="content_save" value="1" class="btn btn-primary"><i class="fa fa-save"></i> Save content</button>
            </div>
        </form>

        <hr>
        <h4>Slides / guide pages <small>(<?php echo count($mediaList); ?>)</small></h4>
        <div class="nex-admin-media-grid">
            <?php foreach ($mediaList as $mediaIndex => $media) {
                if (!is_array($media) || empty($media['file'])) continue;
                $file = (string)$media['file'];
                $src = preg_match('#^https?://#i', $file) ? $file : $nexContentPublicBase . rawurlencode(basename($file));
            ?>
            <div class="nex-admin-media">
                <img src="<?php echo htmlspecialchars($src, ENT_QUOTES, 'UTF-8'); ?>" alt="Slide <?php echo (int)$mediaIndex + 1; ?>" loading="lazy">
                <form method="post" action="" enctype="multipart/form-data">
                    <input type="hidden" name="item_id" value="<?php echo htmlspecialchars($itemId, ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="hidden" name="media_index" value="<?php echo (int)$mediaIndex; ?>">
                    <div class="form-group">
                        <label>Page <?php echo (int)$mediaIndex + 1; ?> caption</label>
                        <input type="text" name="caption" class="form-control input-sm" maxlength="120" value="<?php echo htmlspecialchars(isset($media['caption']) ? $media['caption'] : '', ENT_QUOTES, 'UTF-8'); ?>">
                    </div>
                    <div class="form-group">
                        <label>Replace image <small class="text-muted">(optional)</small></label>
                        <input type="file" name="replacement_file" accept="image/jpeg,image/png,image/webp,image/gif" class="form-control input-sm">
                    </div>
                    <div class="nex-admin-actions">
                        <button type="submit" name="content_save_media" value="1" class="btn btn-success btn-xs"><i class="fa fa-save"></i> Save / replace</button>
                        <button type="submit" name="content_move_media" value="1" class="btn btn-default btn-xs" formaction="" onclick="this.form.direction.value='up'" <?php echo $mediaIndex === 0 ? 'disabled' : ''; ?>><i class="fa fa-arrow-left"></i></button>
                        <button type="submit" name="content_move_media" value="1" class="btn btn-default btn-xs" formaction="" onclick="this.form.direction.value='down'" <?php echo $mediaIndex >= count($mediaList) - 1 ? 'disabled' : ''; ?>><i class="fa fa-arrow-right"></i></button>
                        <input type="hidden" name="direction" value="">
                        <button type="submit" name="content_delete_media" value="1" class="btn btn-danger btn-xs" onclick="return confirm('Delete this slide?');"><i class="fa fa-trash"></i></button>
                    </div>
                </form>
            </div>
            <?php } ?>
        </div>

        <hr>
        <form method="post" action="" enctype="multipart/form-data">
            <input type="hidden" name="item_id" value="<?php echo htmlspecialchars($itemId, ENT_QUOTES, 'UTF-8'); ?>">
            <div class="form-group">
                <label>Add more slides</label>
                <input type="file" name="content_files[]" multiple accept="image/jpeg,image/png,image/webp,image/gif" class="form-control">
                <span class="help-block">You can select several images at once. They are appended in upload order. Maximum 8 MB per image.</span>
            </div>
            <button type="submit" name="content_add_media" value="1" class="btn btn-success"><i class="fa fa-plus"></i> Upload slides</button>
        </form>
    </div>
    <div class="panel-footer">
        <form method="post" action="" onsubmit="return confirm('Delete this entire content item and its uploaded images?');">
            <input type="hidden" name="item_id" value="<?php echo htmlspecialchars($itemId, ENT_QUOTES, 'UTF-8'); ?>">
            <button type="submit" name="content_delete_item" value="1" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i> Delete content item</button>
        </form>
    </div>
</div>
<?php } ?>

<hr>
<h2>Create new content</h2>
<div class="panel panel-success">
    <div class="panel-heading"><strong>New guide / community feature</strong></div>
    <div class="panel-body">
        <form method="post" action="" enctype="multipart/form-data" class="row">
            <div class="col-md-4 form-group">
                <label>Category</label>
                <input type="text" name="category" class="form-control" maxlength="60" value="Guía" placeholder="Guía, Comunidad, Evento...">
            </div>
            <div class="col-md-8 form-group">
                <label>Title</label>
                <input type="text" name="title" class="form-control" maxlength="100" required placeholder="Ej. Guía de Wings / Clip de la comunidad">
            </div>
            <div class="col-md-12 form-group">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="3" maxlength="500" placeholder="Qué encontrará el jugador en este contenido."></textarea>
            </div>
            <div class="col-md-4 form-group">
                <label>Credit / creator</label>
                <input type="text" name="credit" class="form-control" maxlength="100" placeholder="Nexora VE Networks / nombre del jugador">
            </div>
            <div class="col-md-5 form-group">
                <label>External link <small class="text-muted">(optional)</small></label>
                <input type="url" name="link" class="form-control" placeholder="https://youtube.com/...">
            </div>
            <div class="col-md-3 form-group">
                <label>Button text</label>
                <input type="text" name="link_label" class="form-control" maxlength="50" value="Ver recurso">
            </div>
            <div class="col-md-12 form-group">
                <label>Images / guide pages</label>
                <input type="file" name="content_files[]" multiple required accept="image/jpeg,image/png,image/webp,image/gif" class="form-control">
                <span class="help-block">JPG, PNG, WEBP or GIF. Select one image for a showcase or several images for a paginated guide.</span>
            </div>
            <div class="col-md-12">
                <button type="submit" name="content_add" value="1" class="btn btn-success"><i class="fa fa-plus-circle"></i> Create content</button>
            </div>
        </form>
    </div>
</div>
