<?php
// admin/media_library.php  — minimal Media Library for osConcert Admin
// -------------------------------------------------------------------
// Features:
// - Upload multiple files to /images/uploads/YYYY/MM[/event_###]/
// - MIME + extension whitelist, size limit
// - Browse latest files (recursively), copy URL to clipboard
// - Soft delete to a .trash folder (can be toggled to hard delete)
// - Works without DB (filesystem scan). Uses your existing configure.php.
// -------------------------------------------------------------------
// Optional: create /images/.htaccess to block script execution (recommended)
//
// RemoveHandler .php .phtml .php3 .php4 .php5 .php7 .php8
// RemoveType .php .phtml .php3 .php4 .php5 .php7 .php8
// AddType text/plain .php .phtml .php3 .php4 .php5 .php7 .php8
// Options -ExecCGI
// -------------------------------------------------------------------

define('_FEXEC', 1);
	require('includes/application_top.php');
	require(DIR_WS_INCLUDES.'/tweak/general.php');
	frequire($FSESSION->language.'/media_upload.php',RLANG);
	$languages = tep_get_languages();
	tep_get_last_access_file();

// ---------- Helpers ----------
if (!function_exists('fs_join')) {
  function fs_join(...$parts) {
    $out = array_shift($parts);
    foreach ($parts as $p) $out = rtrim($out, "/\\") . DIRECTORY_SEPARATOR . ltrim($p, "/\\");
    return $out;
  }
}
if (!function_exists('ws_join')) {
  function ws_join(...$parts) {
    $out = array_shift($parts);
    foreach ($parts as $p) $out = rtrim($out, "/") . '/' . ltrim($p, "/");
    return $out;
  }
}
function ensure_dir($path) {
  return is_dir($path) || mkdir($path, 0775, true);
}
function sanitize_hex_color($v) {
  $v = trim((string)$v);
  return preg_match('/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$/', $v) ? $v : '';
}
function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// ---------- Derive uploads paths from your existing configure.php ----------
if (!defined('DIR_FS_UPLOADS')) {
  define('DIR_FS_UPLOADS', fs_join(DIR_FS_CATALOG_IMAGES, 'uploads') . DIRECTORY_SEPARATOR);
}
if (!defined('DIR_WS_UPLOADS')) {
  define('DIR_WS_UPLOADS', ws_join(DIR_WS_CATALOG_IMAGES, 'uploads') . '/');
}
$http_catalog = (defined('HTTP_CATALOG_SERVER') ? HTTP_CATALOG_SERVER : (defined('HTTP_SERVER') ? HTTP_SERVER : ''));

// ---------- CSRF Token ----------
if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf_token = $_SESSION['csrf_token'];
function check_csrf() {
  if (!isset($_POST['csrf']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf'])) {
    die('Invalid CSRF token');
  }
}

// ---------- Config ----------
$MAX_BYTES  = 10 * 1024 * 1024; // 10MB
$ALLOW_EXT  = ['jpg','jpeg','png','webp','gif','svg','pdf'];
$ALLOW_MIME = ['image/jpeg','image/png','image/webp','image/gif','image/svg+xml','application/pdf'];

// ---------- Actions ----------
$notice = $_SESSION['media_notice'] ?? '';
$error  = $_SESSION['media_error'] ?? '';

unset($_SESSION['media_notice'], $_SESSION['media_error']);

function media_redirect($section = '') {
  $url = tep_href_link(basename($_SERVER['PHP_SELF']));
  if ($section !== '') {
    $url .= '#' . $section;
  }
  tep_redirect($url);
  exit;
}

if (!is_dir(DIR_FS_UPLOADS)) {
  if (!ensure_dir(DIR_FS_UPLOADS)) $error = 'Cannot create uploads base folder: ' . DIR_FS_UPLOADS;
}

	  
	  
	  // ---------- Template image manager config ----------
	$bg_items = array(
		'HERO_BG' => array(
			'label' => 'Hero Background',
			'placeholder' => 'images/uploads/hero-bg.webp',
			'overlay' => 'HERO_BG_OVERLAY',
			'accent' => 'HERO_BG_OVERLAY_ACCENT'
		),

		'HERO_IMG' => array(
			'label' => 'Hero Image',
			'placeholder' => 'images/uploads/hero-img.png',
			'overlay' => false
		),

		'FOOTER_BG' => array(
			'label' => 'Footer Background',
			'placeholder' => 'images/uploads/footer.webp',
			'overlay' => 'FOOTER_BG_OVERLAY',
			'accent' => 'FOOTER_BG_OVERLAY_ACCENT'
		)
	);
	
	$allowed_bg_keys = array_keys($bg_items);

// Background image manager save
if (isset($_POST['save_bg'])) {
  check_csrf();

  $key   = $_POST['bg_key'] ?? '';
  $value = trim($_POST['bg_value'] ?? '');

  if (in_array($key, $allowed_bg_keys, true)) {

    tep_db_query("
      UPDATE " . TABLE_CONFIGURATION . "
      SET configuration_value = '" . tep_db_input($value) . "',
          last_modified = now()
      WHERE configuration_key = '" . tep_db_input($key) . "'
    ");

    if (!empty($bg_items[$key]['overlay'])) {

      $overlay = (int)($_POST['bg_overlay'] ?? 0);

      if ($overlay < 0) $overlay = 0;
      if ($overlay > 85) $overlay = 85;

      $overlay_key = $bg_items[$key]['overlay'];

      tep_db_query("
        UPDATE " . TABLE_CONFIGURATION . "
        SET configuration_value = '" . (int)$overlay . "',
            last_modified = now()
        WHERE configuration_key = '" . tep_db_input($overlay_key) . "'
      ");
    }
	
	if (!empty($bg_items[$key]['accent'])) {

		$accent = isset($_POST['bg_accent']) ? 1 : 0;

		$accent_key = $bg_items[$key]['accent'];

		tep_db_query("
			UPDATE " . TABLE_CONFIGURATION . "
			SET configuration_value = '" . (int)$accent . "',
				last_modified = now()
			WHERE configuration_key = '" . tep_db_input($accent_key) . "'
		");
	}

    $_SESSION['media_notice'] = 'Saved ' . $bg_items[$key]['label'];
  }

  media_redirect('template-images');
}


// Hero embed video save
if (isset($_POST['save_embed_video']) || isset($_POST['clear_embed_video'])) {
  check_csrf();

  $embed_type  = $_POST['embed_type'] ?? '';
  $embed_value = trim($_POST['embed_value'] ?? '');

  $allowed_types = array('videochain', 'youtube');

  if (isset($_POST['clear_embed_video'])) {
    $embed_value = '';
  }

  if (in_array($embed_type, $allowed_types, true) && $embed_value !== '') {

    $stored_value = $embed_type . '|' . $embed_value;

    tep_db_query("
      UPDATE " . TABLE_CONFIGURATION . "
      SET configuration_value = '" . tep_db_input($stored_value) . "',
          last_modified = now()
      WHERE configuration_key = 'EMBED_VIDEO'
    ");

    $_SESSION['media_notice'] = 'Embed video saved.';

  } else {

    tep_db_query("
      UPDATE " . TABLE_CONFIGURATION . "
      SET configuration_value = '',
          last_modified = now()
      WHERE configuration_key = 'EMBED_VIDEO'
    ");

    $_SESSION['media_notice'] = 'Embed video cleared.';
  }

  media_redirect('hero-embed-video');
}


// Upload handler
if (!$error && isset($_POST['action']) && $_POST['action'] === 'upload') {
  check_csrf();

  $event_id = isset($_POST['event_id']) && $_POST['event_id'] !== '' ? (int)$_POST['event_id'] : null;

  // Optional: subfolder input (e.g., "banners") — keep it simple/alnum-dash-underscore
  $subfolder = isset($_POST['subfolder']) ? preg_replace('~[^a-zA-Z0-9_\-]~', '', $_POST['subfolder']) : '';

  $year = date('Y'); $month = date('m');
  $parts = [$year, $month];
  if ($event_id) $parts[] = "event_" . $event_id;
  if ($subfolder !== '') $parts[] = $subfolder;

  $targetFs = fs_join(DIR_FS_UPLOADS, ...$parts);
  $targetWs = ws_join(DIR_WS_UPLOADS, ...$parts) . '/';

  if (!ensure_dir($targetFs)) $error = 'Cannot create target folder: ' . $targetFs;

  if (!$error && isset($_FILES['files'])) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $count_ok = 0; $count_fail = 0;
    foreach ($_FILES['files']['error'] as $i => $err) {
      if ($err !== UPLOAD_ERR_OK) { $count_fail++; continue; }
      $tmp  = $_FILES['files']['tmp_name'][$i];
      $orig = $_FILES['files']['name'][$i];
      $size = (int)$_FILES['files']['size'][$i];

      if ($size <= 0 || $size > $MAX_BYTES) { $count_fail++; continue; }

      $mime = $finfo->file($tmp) ?: '';
      $ext  = strtolower(pathinfo($orig, PATHINFO_EXTENSION));

      if (!in_array($ext, $ALLOW_EXT, true)) { $count_fail++; continue; }
      if (!in_array($mime, $ALLOW_MIME, true)) { $count_fail++; continue; }
	  


	

      // generate random filename
      $stored = bin2hex(random_bytes(8)) . '.' . $ext;
      $dest = fs_join($targetFs, $stored);

      if (!move_uploaded_file($tmp, $dest)) { $count_fail++; continue; }

      // success (no DB insert; listing is filesystem-based)
      $count_ok++;
    }
    $_SESSION['media_notice'] = "Uploaded: $count_ok, Failed: $count_fail";
media_redirect('media-library');
  }
}

// Delete handler (soft delete to .trash)
if (!$error && isset($_POST['action']) && $_POST['action'] === 'delete') {
  check_csrf();
  $rel = isset($_POST['rel']) ? (string)$_POST['rel'] : '';
  // Expected format begins with "images/uploads/..."
  if (strpos($rel, 'images/uploads/') !== 0) {
    $error = 'Invalid path';
  } else {
    // Build FS path from REL by replacing the leading ws root with fs root
    $rel_after = substr($rel, strlen('images/uploads/')); // e.g. 2025/11/XXXX.webp
    $src = fs_join(DIR_FS_UPLOADS, $rel_after);

    // Ensure path is within uploads
    $realUploads = realpath(DIR_FS_UPLOADS);
    $realSrc     = realpath($src);
    if (!$realSrc || strpos($realSrc, $realUploads) !== 0) {
      $error = 'Forbidden path';
    } else {
      $trashFs = fs_join(DIR_FS_UPLOADS, '.trash');
      ensure_dir($trashFs);
      $trashTarget = fs_join($trashFs, basename($src));
      if (@rename($src, $trashTarget)) {
        $_SESSION['media_notice'] = 'Moved to trash: ' . basename($src);
media_redirect('media-library');
      } else {
        $error = 'Delete failed (rename)';
      }
    }
  }
}

// ---------- Listing (scan filesystem) ----------
function list_uploads($base, $limit = 200) {
  // Recursively list files newest first
  $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS));
  $files = [];
  foreach ($rii as $file) {
    if ($file->isDir()) continue;
    $path = $file->getPathname();
    // skip .trash
    if (strpos($path, DIRECTORY_SEPARATOR . '.trash' . DIRECTORY_SEPARATOR) !== false) continue;
    $mtime = $file->getMTime();
    $files[] = ['path' => $path, 'mtime' => $mtime, 'size' => $file->getSize()];
  }
  usort($files, function($a,$b){ return $b['mtime'] <=> $a['mtime']; });
  if (count($files) > $limit) $files = array_slice($files, 0, $limit);
  return $files;
}

$items = [];
if (!$error && is_dir(DIR_FS_UPLOADS)) {
  $items = list_uploads(DIR_FS_UPLOADS, 200);
}
$is_picker = isset($_GET['picker']) && $_GET['picker'] == '1';

// Map FS path -> web path relative (images/uploads/…)
function fs_to_rel_web($fsPath) {
  // $fsPath starts with DIR_FS_UPLOADS
  $prefix = realpath(DIR_FS_UPLOADS);
  $real   = realpath($fsPath);
  if (!$real || strpos($real, $prefix) !== 0) return null;
  $rest = ltrim(substr($real, strlen($prefix)), DIRECTORY_SEPARATOR);
  return 'images/uploads/' . str_replace(DIRECTORY_SEPARATOR, '/', $rest);
}

?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
  <title><?php echo TEXT_MEDIA_LIBRARY; ?></title>
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
  <style>
    .media-card img { max-width: 100%; height: 140px; object-fit: cover; }
    .media-grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(220px,1fr)); gap: 12px; }
    .truncate { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
    .copy-badge { cursor:pointer; }
  </style>
</head>
<body>
<?php 

define('NAVBAR_TITLE', 'Media Upload');
define('HEADING_TITLE', 'Media Upload');
?>
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>

<div id="media-library" class="container my-3">
  <h4 class="mb-3"><?php echo TEXT_MEDIA_LIBRARY; ?>   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="shop_template_configuration.php"><button class="btn btn-primary">
            Back to Template Editor
          </button></a></h4>

  <?php if ($notice): ?>
    <div class="alert alert-success"><?php echo h($notice); ?></div>
  <?php endif; ?>
  <?php if ($error): ?>
    <div class="alert alert-danger"><?php echo h($error); ?></div>
  <?php endif; ?>

  <div class="card mb-4">
    <div class="card-body">
      <form method="post" enctype="multipart/form-data" class="row gy-2 gx-2 align-items-end">
        <input type="hidden" name="action" value="upload">
        <input type="hidden" name="csrf" value="<?php echo h($csrf_token); ?>">

        <div class="col-md-3">
          <label class="form-label"><?php echo TEXT_FILES; ?></label>
          <input type="file" name="files[]" multiple class="form-control" accept="image/*,application/pdf">
        </div>
        <div class="col-md-2">
          <label class="form-label"><?php echo TEXT_EVENT_ID_OPTIONAL; ?></label>
          <input type="number" name="event_id" class="form-control" placeholder="e.g. 123">
        </div>
        <div class="col-md-2">
          <label class="form-label"><?php echo TEXT_SUBFOLDER_OPTIONAL; ?></label>
          <input type="text" name="subfolder" class="form-control" placeholder="banners">
        </div>
        <div class="col-md-3">
          <label class="form-label"><?php echo TEXT_WHERE_IT_GOES; ?></label>
          <input type="text" class="form-control" value="<?php echo h(DIR_WS_UPLOADS) ?>YYYY/MM[/event_X]/[sub]" disabled>
        </div>
        <div class="col-md-2">
          <button class="btn btn-primary w-100">
            <i class="bi bi-cloud-upload"></i> <?php echo TEXT_UPLOAD; ?>
          </button>
        </div>
      </form>
    </div>
  </div>

  <div class="d-flex justify-content-between align-items-center mb-2">
    <div><strong><?php echo TEXT_LATEST_FILES; ?></strong> <?php echo TEXT_SHOWING_UP_TO_200; ?></div>
    <div class="text-muted">
      <?php echo TEXT_BASE_URL; ?> <?php echo h($http_catalog . DIR_WS_UPLOADS); ?>
    </div>
  </div>

  <div class="media-grid">
    <?php if (empty($items)): ?>
      <div class="text-muted"><?php echo TEXT_NO_FILES_YET; ?>.</div>
    <?php else: ?>
      <?php foreach ($items as $it):
        $fs   = $it['path'];
        $rel  = fs_to_rel_web($fs);
        if ($rel === null) continue;
        $abs  = $http_catalog . ws_join(DIR_WS_CATALOG, $rel);
        $ext  = strtolower(pathinfo($fs, PATHINFO_EXTENSION));
        $isImg = in_array($ext, ['jpg','jpeg','png','webp','gif','svg'], true);
      ?>
        <div class="card media-card">
          <div class="card-img-top bg-light d-flex align-items-center justify-content-center" style="height:140px;">
            <?php if ($isImg): ?>
              <img src="<?php echo h($abs); ?>" alt="">
            <?php else: ?>
              <div class="text-center">
                <i class="bi bi-file-earmark-pdf" style="font-size:48px;"></i>
                <div class="small text-muted mt-1">PDF</div>
              </div>
            <?php endif; ?>
          </div>
          <div class="card-body p-2">
            <div class="small truncate" title="<?php echo h($rel); ?>"><?php echo h($rel); ?></div>
            <div class="d-flex gap-1 mt-2">
  <?php if ($is_picker): ?>
    <button class="btn btn-sm btn-primary"
            type="button"
            onclick="insertAndClose('<?php echo h($rel); ?>','<?php echo h($abs); ?>')">
      <?php echo TEXT_INSERT; ?>
    </button>
  <?php else: ?>
    <button class="btn btn-sm btn-outline-secondary"
            type="button"
            onclick="copyToClipboard('<?php echo h($rel); ?>', this)">
      <?php echo TEXT_COPY_REL; ?>
    </button>
    <button class="btn btn-sm btn-outline-secondary"
            type="button"
            onclick="copyToClipboard('<?php echo h($abs); ?>', this)">
      <?php echo TEXT_COPY_URL; ?>
    </button>
    <form method="post" onsubmit="return confirm('Move to trash?');" class="ms-auto">
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="csrf" value="<?php echo h($csrf_token); ?>">
      <input type="hidden" name="rel" value="<?php echo h($rel); ?>">
      <button class="btn btn-sm btn-outline-danger" type="submit">
        <i class="bi bi-trash"></i>
      </button>
    </form>
  <?php endif; ?>
</div>

          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

</div>
<hr>
<?php

// Load current values
$config_keys = array();

foreach ($bg_items as $key => $item) {
    $config_keys[] = "'" . tep_db_input($key) . "'";

    if (!empty($item['overlay'])) {
        $config_keys[] = "'" . tep_db_input($item['overlay']) . "'";
    }
	
	if (!empty($item['accent'])) {
		$config_keys[] = "'" . tep_db_input($item['accent']) . "'";
	}
}

$bg_values = array();

$query = tep_db_query("
    SELECT configuration_key, configuration_value
    FROM " . TABLE_CONFIGURATION . "
    WHERE configuration_key IN (" . implode(',', $config_keys) . ")
");

while ($row = tep_db_fetch_array($query)) {
    $bg_values[$row['configuration_key']] = $row['configuration_value'];
}

$overlay_options = array(
    0  => 'None',
    25 => 'Light - 25%',
    50 => 'Medium - 50%',
    70 => 'Strong - 70%',
    85 => 'Very Strong - 85%'
);
?>

<div id="template-images" class="container my-3" style="padding:40px 0;">
  <h4 class="mb-3"><?php echo TEXT_TEMPLATE_IMAGES; ?></h4>
  <p class="text-muted">
    <?php echo TEXT_ADD_IMAGE_PATHS_FOR_HERO_FOOTER_BACKGROUNDS; ?>
  </p>

  <?php foreach ($bg_items as $key => $item): ?>
    <?php
      $has_overlay = !empty($item['overlay']);
      $overlay_key = $has_overlay ? $item['overlay'] : '';
      $current_value = $bg_values[$key] ?? '';
      $current_overlay = $has_overlay ? (int)($bg_values[$overlay_key] ?? 0) : 0;
	  $current_accent = !empty($item['accent']) ? (int)($bg_values[$item['accent']] ?? 0) : 0;
    ?>

	<form method="post" class="p-3 mb-3">
	  <div class="row g-3 align-items-end">

		<!-- INPUT -->
		<div class="<?php echo $has_overlay ? 'col-lg-6' : 'col-lg-9'; ?>">
		  <input type="hidden" name="csrf" value="<?php echo h($csrf_token); ?>">

		  <label class="form-label">
			<?php echo htmlspecialchars($item['label']); ?>
			<small class="text-muted">(<?php echo htmlspecialchars($key); ?>)</small>
		  </label>

		  <input type="text"
				 name="bg_value"
				 class="form-control"
				 value="<?php echo htmlspecialchars($current_value, ENT_QUOTES, 'UTF-8'); ?>"
				 placeholder="<?php echo htmlspecialchars($item['placeholder'], ENT_QUOTES, 'UTF-8'); ?>">
		</div>

		<?php if ($has_overlay): ?>

		  <!-- DROPDOWN -->
		  <div class="col-lg-2">
			<label class="form-label small"><?php echo TEXT_OVERLAY; ?></label>

			<select name="bg_overlay" class="form-select">
			  <?php foreach ($overlay_options as $ovalue => $olabel): ?>
				<option value="<?php echo (int)$ovalue; ?>" <?php echo ($current_overlay == $ovalue) ? 'selected' : ''; ?>>
				  <?php echo htmlspecialchars($olabel); ?>
				</option>
			  <?php endforeach; ?>
			</select>
		  </div>

		  <!-- CHECKBOX -->
		  <div class="col-lg-2 d-flex align-items-center">
			<?php if (!empty($item['accent'])): ?>
			  <div class="form-check mt-4">
				<input class="form-check-input"
					   type="checkbox"
					   id="bg_accent_<?php echo htmlspecialchars($key); ?>"
					   name="bg_accent"
					   value="1"
					   <?php echo ($current_accent == 1) ? 'checked' : ''; ?>>

				<label class="form-check-label small" for="bg_accent_<?php echo htmlspecialchars($key); ?>">
				  <?php echo TEXT_ACCENT; ?>
				</label>
			  </div>
			<?php endif; ?>
		  </div>

		<?php endif; ?>

		<!-- SAVE BUTTON -->
		<div class="col-lg-2">
		  <input type="hidden" name="bg_key" value="<?php echo htmlspecialchars($key); ?>">

		  <button type="submit" name="save_bg" class="btn btn-primary w-100">
			<?php echo TEXT_SAVE; ?>
		  </button>
		</div>

	  </div>
	</form>
  <?php endforeach; ?>
</div>
<hr>
<?php
// -------------------------------
// HERO EMBED VIDEO ADMIN
// Stores plain text in configuration key EMBED_VIDEO
// Format: type|value
// Example: videochain|my-video-chain-slug
// Example: youtube|https://www.youtube.com/watch?v=xxxx
// -------------------------------


// Load saved value
$embed_type  = 'videochain';
$embed_value = '';

$embed_query = tep_db_query("
    SELECT configuration_value
    FROM " . TABLE_CONFIGURATION . "
    WHERE configuration_key = 'EMBED_VIDEO'
    LIMIT 1
");

if ($embed_row = tep_db_fetch_array($embed_query)) {
    $saved_embed = trim($embed_row['configuration_value']);

    if ($saved_embed !== '' && strpos($saved_embed, '|') !== false) {
        list($saved_type, $saved_value) = explode('|', $saved_embed, 2);

        if (in_array($saved_type, array('videochain', 'youtube'), true)) {
            $embed_type  = $saved_type;
            $embed_value = $saved_value;
        }
    }
}
?>

<div id="hero-embed-video" class="container my-3">
  <h4 class="mb-3"><?php echo TEXT_HERO_EMBED_VIDEO; ?></h4>

  <?php //echo $embed_message; ?>

  <form method="post">
    <div class="row g-4 align-items-start">

      <!-- LEFT: INPUT -->
      <div class="col-lg-6">
        <div class="mb-3">
		<input type="hidden" name="csrf" value="<?php echo h($csrf_token); ?>">
          <label class="form-label"><?php echo TEXT_EMBED_TYPE; ?></label>
          <select name="embed_type" id="embed_type" class="form-select">
            <option value="videochain" <?php echo ($embed_type == 'videochain') ? 'selected' : ''; ?>>
              <?php echo TEXT_VIDEO_CHAIN; ?>
            </option>
            <option value="youtube" <?php echo ($embed_type == 'youtube') ? 'selected' : ''; ?>>
              YouTube
            </option>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label"><?php echo TEXT_VIDEO_CHAIN_SLUG_OR_YOUTUBE_URL_ID; ?></label>
          <textarea name="embed_value" id="embed_value" rows="5" class="form-control"
            placeholder="Example: my-video-chain-slug or https://www.youtube.com/watch?v=xxxx"><?php
              echo htmlspecialchars($embed_value, ENT_QUOTES, 'UTF-8');
            ?></textarea>
        </div>

        <button type="submit" name="save_embed_video" class="btn btn-primary">
          <?php echo TEXT_SAVE_EMBED_VIDEO; ?>
        </button>

        <button type="submit" name="clear_embed_video" class="btn btn-outline-danger"
          onclick="document.getElementById('embed_value').value='';">
          <?php echo TEXT_CLEAR; ?>
        </button>
      </div>

      <!-- RIGHT: PREVIEW -->
      <div class="col-lg-6">
        <label class="form-label"><?php echo TEXT_PREVIEW; ?></label>
        <div id="embed_preview" class="border rounded p-2 bg-light">
          <div class="ratio ratio-16x9">
            <iframe id="embed_preview_iframe"
              src=""
              style="border:0;"
              allow="autoplay; encrypted-media; picture-in-picture"
              allowfullscreen></iframe>
          </div>
        </div>
        <small class="text-muted d-block mt-2">
         <?php echo TEXT_PREVIEW_UPDATES_FROM_SELECTED_TYPE; ?>
        </small>
      </div>

    </div>
  </form>
</div>

<script>
function extractYouTubeId(value) {
  value = value.trim();

  var match = value.match(/(?:v=|youtu\.be\/|embed\/)([a-zA-Z0-9_-]{11})/);
  if (match && match[1]) {
    return match[1];
  }

  value = value.replace(/[^a-zA-Z0-9_-]/g, '');
  return value.length >= 11 ? value.substring(0, 11) : '';
}

function updateEmbedPreview() {
  var type = document.getElementById('embed_type').value;
  var value = document.getElementById('embed_value').value.trim();
  var iframe = document.getElementById('embed_preview_iframe');

  iframe.src = '';

  if (!value) {
    return;
  }

  if (type === 'videochain') {
    var slug = value.replace(/[^a-zA-Z0-9-]/g, '');

    if (slug) {
      iframe.src = 'https://www.videochainmaker.com/embed.php?slug=' + encodeURIComponent(slug);
    }
  }

  if (type === 'youtube') {
    var videoId = extractYouTubeId(value);

    if (videoId) {
      iframe.src = 'https://www.youtube.com/embed/' + encodeURIComponent(videoId);
    }
  }
}

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('embed_type').addEventListener('change', updateEmbedPreview);
  document.getElementById('embed_value').addEventListener('input', updateEmbedPreview);

  updateEmbedPreview();
});
</script>

<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

<script>
function copyToClipboard(text, btn) {
  navigator.clipboard.writeText(text).then(function() {
    const old = btn.textContent;
    btn.textContent = 'Copied!';
    setTimeout(()=>{ btn.textContent = old; }, 900);
  });
}

// Picker mode: post selection to opener and close
function insertAndClose(rel, url) {
  if (window.opener && window.opener.postMessage) {
    window.opener.postMessage({ type: 'media-pick', rel: rel, url: url }, '*');
  }
  window.close();
}
</script>

</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
