<?php
/**
 * WebEngine CMS - Media Gallery (Galería de Fotos)
 * Gestiona las imágenes y videos del slider de la galería en el home (template nexoraves6).
 *
 * @version 1.0
 * @author Gabo Dev <https://www.gabodevelop.com/>
 */

if (!defined('access')) die('Direct access not permitted.');

$configKey = 'media_gallery';
$configFile = __PATH_CONFIGS__ . $configKey . '.json';

function saveMediaGallery($items) {
	$path = __PATH_CONFIGS__ . 'media_gallery.json';
	if (!is_writable($path)) {
		message('error', 'The configuration file is not writable.');
		return false;
	}
	$json = json_encode(array_values($items), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
	if (file_put_contents($path, $json) === false) {
		message('error', 'Error saving gallery.');
		return false;
	}
	message('success', 'Media gallery saved.');
	return true;
}

// Delete item
if (isset($_POST['delete_item']) && is_numeric($_POST['delete_item'])) {
	$cfg = loadConfig($configKey);
	if (is_array($cfg)) {
		$id = (int) $_POST['delete_item'];
		if (isset($cfg[$id])) {
			array_splice($cfg, $id, 1);
			saveMediaGallery($cfg);
		}
	}
	header('Location: ' . admincp_base('media_gallery'));
	exit;
}

// Add new item
if (isset($_POST['add_item'])) {
	$cfg = loadConfig($configKey);
	if (!is_array($cfg)) $cfg = array();
	$newImg = isset($_POST['new_img']) ? trim($_POST['new_img']) : '';
	$newVideo = isset($_POST['new_video']) ? trim($_POST['new_video']) : '';
	if ($newImg !== '') {
		$cfg[] = array('img' => $newImg, 'video' => $newVideo);
		saveMediaGallery($cfg);
		header('Location: ' . admincp_base('media_gallery'));
		exit;
	}
}

// Update existing items
if (isset($_POST['gallery_update']) && !empty($_POST['gallery_update']) && is_array($_POST['items'])) {
	$items = array();
	foreach ($_POST['items'] as $idx => $data) {
		$img = isset($data['img']) ? trim($data['img']) : '';
		if ($img === '') continue;
		$items[] = array(
			'img'  => $img,
			'video' => isset($data['video']) ? trim($data['video']) : ''
		);
	}
	saveMediaGallery($items);
	header('Location: ' . admincp_base('media_gallery'));
	exit;
}

$gallery = loadConfig($configKey);
if (!is_array($gallery)) $gallery = array();
?>
<h1 class="page-header">Media Gallery (Galería de Fotos)</h1>
<p>Images and optional video embeds shown in the home page gallery slider (template nexoraves6). <strong>Image</strong>: use a path relative to the template img folder (e.g. <code>slider-img-1.jpg</code>, <code>profiles/knight.jpg</code>) or a full external URL (e.g. <code>https://example.com/image.jpg</code>). <strong>Video</strong>: optional embed URL; leave empty for image only.</p>

<?php if (!empty($gallery)) { ?>
<form method="post" action="">
	<input type="hidden" name="gallery_update" value="1" />
	<table class="table table-bordered table-striped table-hover">
		<thead>
			<tr>
				<th style="width:60px;">#</th>
				<th>Image (path or URL)</th>
				<th>Video URL (optional)</th>
				<th style="width:100px;">Actions</th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ($gallery as $idx => $item) {
				$img = is_array($item) ? (isset($item['img']) ? $item['img'] : '') : '';
				$video = is_array($item) && isset($item['video']) ? $item['video'] : '';
			?>
			<tr>
				<td><?php echo (int)$idx + 1; ?></td>
				<td>
					<input type="text" name="items[<?php echo (int)$idx; ?>][img]" class="form-control" value="<?php echo htmlspecialchars($img); ?>" placeholder="slider-img-1.jpg or https://..." />
				</td>
				<td>
					<input type="text" name="items[<?php echo (int)$idx; ?>][video]" class="form-control" value="<?php echo htmlspecialchars($video); ?>" placeholder="https://www.youtube.com/embed/... (optional)" />
				</td>
				<td>
					<form method="post" action="<?php echo admincp_base('media_gallery'); ?>" style="display:inline" onsubmit="return confirm('Delete this item?');"><input type="hidden" name="delete_item" value="<?php echo (int)$idx; ?>"><button type="submit" class="btn btn-danger btn-xs">Delete</button></form>
				</td>
			</tr>
			<?php } ?>
		</tbody>
	</table>
	<button type="submit" class="btn btn-primary">Save changes</button>
</form>
<?php } else { ?>
	<p class="text-muted">No items yet. Add one below.</p>
<?php } ?>

<hr />
<h3>Add new item</h3>
<form method="post" action="">
	<div class="form-group">
		<label>Image (path or URL)</label>
		<input type="text" name="new_img" class="form-control" placeholder="slider-img-1.jpg or https://example.com/image.jpg" required />
		<span class="help-block">Relative path from template img folder (e.g. <code>slider-img-1.jpg</code>) or full external URL (e.g. <code>https://example.com/photo.jpg</code>).</span>
	</div>
	<div class="form-group">
		<label>Video embed URL <small class="text-muted">(optional)</small></label>
		<input type="text" name="new_video" class="form-control" placeholder="https://www.youtube.com/embed/..." />
		<span class="help-block">Leave empty for image only. If set, clicking the thumbnail opens this video in the lightbox.</span>
	</div>
	<button type="submit" name="add_item" value="1" class="btn btn-success">Add item</button>
</form>
