<?php
// admin/media_picker.php — lightweight picker for opening in a popup
define('_FEXEC', 1);
require('includes/application_top.php');

// ------- helpers -------
if (!function_exists('fs_join')) {
  function fs_join(...$p){ $o=array_shift($p); foreach($p as $x){ $o=rtrim($o,"/\\").DIRECTORY_SEPARATOR.ltrim($x,"/\\"); } return $o; }
}
if (!function_exists('ws_join')) {
  function ws_join(...$p){ $o=array_shift($p); foreach($p as $x){ $o=rtrim($o,"/").'/'.ltrim($x,"/"); } return $o; }
}
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// ------- derive paths from 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_BASE = defined('HTTP_CATALOG_SERVER') ? HTTP_CATALOG_SERVER : (defined('HTTP_SERVER') ? HTTP_SERVER : '');

// ------- params -------
$q       = trim($_GET['q'] ?? '');
$limit   = max(24, (int)($_GET['limit'] ?? 120));      // how many to show
$imagesOnly = (isset($_GET['type']) && $_GET['type']==='img'); // filter

// ------- list files (newest first) -------
function list_uploads($base, $q, $imagesOnly, $limit) {
  $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS));
  $rows = [];
  foreach ($rii as $f) {
    if ($f->isDir()) continue;
    $path = $f->getPathname();
    if (strpos($path, DIRECTORY_SEPARATOR.'.trash'.DIRECTORY_SEPARATOR) !== false) continue;

    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    $isImg = in_array($ext, ['jpg','jpeg','png','webp','gif','svg'], true);
    if ($imagesOnly && !$isImg) continue;

    // name filter on filename only (fast)
    $name = basename($path);
    if ($q !== '' && stripos($name, $q) === false) continue;

    $rows[] = [
      'fs'   => $path,
      'name' => $name,
      'ext'  => $ext,
      'img'  => $isImg,
      'ts'   => $f->getMTime(),
      'size' => $f->getSize()
    ];
  }
  usort($rows, fn($a,$b) => $b['ts'] <=> $a['ts']);
  return array_slice($rows, 0, $limit);
}

// fs → rel web: images/uploads/...
function fs_to_rel($fs) {
  $root = realpath(DIR_FS_UPLOADS);
  $real = realpath($fs);
  if (!$real || strpos($real, $root) !== 0) return null;
  $rest = ltrim(substr($real, strlen($root)), DIRECTORY_SEPARATOR);
  return 'images/uploads/'.str_replace(DIRECTORY_SEPARATOR,'/',$rest);
}

$items = is_dir(DIR_FS_UPLOADS) ? list_uploads(DIR_FS_UPLOADS, $q, $imagesOnly, $limit) : [];

?>
<!doctype html>
<html <?php echo HTML_PARAMS; ?>>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
  <title>Pick Media</title>
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <style>
    body { padding: 10px; }
    .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:10px; }
    .card { border:1px solid #e5e5e5; }
    .thumb { height:120px; display:flex; align-items:center; justify-content:center; background:#f7f7f7; }
    .thumb img { max-width:100%; max-height:100%; object-fit:cover; }
    .name { font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    .toolbar { display:flex; gap:8px; align-items:center; margin-bottom:10px; }
    .toolbar input[type="text"] { width:280px; }
  </style>
</head>
<body>
  <div class="toolbar">
    <form method="get" class="d-flex gap-2">
      <input type="hidden" name="picker" value="1">
      <input type="text" name="q" class="form-control form-control-sm" placeholder="Search filename..." value="<?php echo h($q); ?>">
      <select name="type" class="form-select form-select-sm" style="width:140px;">
        <option value="">All types</option>
        <option value="img" <?php echo $imagesOnly?'selected':''; ?>>Images only</option>
      </select>
      <select name="limit" class="form-select form-select-sm" style="width:120px;">
        <?php foreach ([60,120,180,240] as $opt): ?>
          <option <?php echo $limit==$opt?'selected':''; ?>><?php echo $opt; ?></option>
        <?php endforeach; ?>
      </select>
      <button class="btn btn-sm btn-primary"><i class="bi bi-search"></i></button>
    </form>
    <button class="btn btn-sm btn-outline-secondary ms-auto" onclick="window.close()">Close</button>
  </div>

  <?php if (empty($items)): ?>
    <div class="alert alert-info py-2">No files found<?php echo $q ? ' for “'.h($q).'”' : ''; ?>.</div>
  <?php else: ?>
    <div class="grid">
      <?php foreach ($items as $it):
        $rel = fs_to_rel($it['fs']); if ($rel===null) continue;
        $abs = $HTTP_BASE . ws_join(DIR_WS_CATALOG, $rel);
      ?>
        <div class="card">
          <div class="thumb">
            <?php if ($it['img']): ?>
              <img src="<?php echo h($abs); ?>" alt="">
            <?php else: ?>
              <div class="text-muted text-center">
                <i class="bi bi-file-earmark-text" style="font-size:40px;"></i>
              </div>
            <?php endif; ?>
          </div>
          <div class="p-2">
            <div class="name" title="<?php echo h($it['name']); ?>"><?php echo h($it['name']); ?></div>
            <div class="d-flex gap-1 mt-2">
              <button class="btn btn-sm btn-primary w-100" type="button" onclick="insertAndClose('<?php echo h($rel); ?>','<?php echo h($abs); ?>')">Insert</button>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

<script>
  // Send selection back to opener
  function insertAndClose(rel, url) {
    if (window.opener && window.opener.postMessage) {
      window.opener.postMessage({ type: 'media-pick', rel: rel, url: url }, '*'); // TODO: set to your exact origin
    }
    window.close();
  }
</script>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
