<?php
// index.php — Galerie mit Applaus-Button (👏) pro Post + Live-Zähler
// Daten liegen in data.json (gleiche Struktur wie beim Upload). Optionales Feld: 'claps'.

declare(strict_types=1);
session_start();
date_default_timezone_set('Europe/Berlin');

function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

$jsonFile = __DIR__ . '/data.json';
if (!file_exists($jsonFile)) file_put_contents($jsonFile, json_encode([]));
$raw = file_get_contents($jsonFile);
$items = json_decode($raw, true);
if (!is_array($items)) $items = [];

function item_id(array $it): string {
  $key = ($it['file'] ?? '') . '|' . ($it['time'] ?? 0) . '|' . ($it['type'] ?? '');
  return substr(sha1($key), 0, 12);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   
  $payload = [];
  $ct = $_SERVER['CONTENT_TYPE'] ?? '';
  if (stripos($ct, 'application/json') !== false) {
    $payload = json_decode(file_get_contents('php://input'), true) ?: [];
  } else {
    $payload = $_POST;
  }

  if (($payload['action'] ?? '') === 'clap' && !empty($payload['id'])) {
    $id = preg_replace('/[^a-z0-9]/i', '', (string)$payload['id']);

    $now = microtime(true);
    if (!isset($_SESSION['last_clap'])) $_SESSION['last_clap'] = [];
    if (isset($_SESSION['last_clap'][$id]) && ($now - $_SESSION['last_clap'][$id]) < 10) {
      header('Content-Type: application/json');
      http_response_code(429);
      echo json_encode(['ok'=>false, 'error'=>'Too fast']);
      exit;
    }

    $updated = false;
    foreach ($items as &$it) {
      $curId = item_id($it);
      if ($curId === $id) {
        $it['claps'] = isset($it['claps']) && is_numeric($it['claps']) ? (int)$it['claps'] + 1 : 1;
        $updated = true;
        $newCount = (int)$it['claps'];
        break;
      }
    }
    unset($it);

    header('Content-Type: application/json');
    if ($updated) {
      file_put_contents($jsonFile, json_encode($items, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
      $_SESSION['last_clap'][$id] = $now;
      echo json_encode(['ok'=>true, 'count'=>$newCount]);
    } else {
      http_response_code(404);
      echo json_encode(['ok'=>false, 'error'=>'Not found']);
    }
    exit;
  }

  header('Content-Type: application/json');
  http_response_code(400);
  echo json_encode(['ok'=>false, 'error'=>'Bad request']);
  exit;
}

$items = array_reverse($items);
?>
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="ownyoursocial.ico" type="image/x-icon"><!--Hier mit eigenem Icon ersetzen-->
<link rel="apple-touch-icon" href="ownyoursocial.ico" /><!--Hier mit eigenem Icon ersetzen-->
<title>OwnYourSocial</title><!--Hier mit eigenem Text ersetzen-->
<style>
:root{--gap:16px;--radius:14px;--shadow:0 6px 20px rgba(0,0,0,.08)}
*{box-sizing:border-box}
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;margin:0;background:#c9c9c9;color:#111}

.header{position:sticky;top:0px;width:100%;background:#c9c9c9;padding:16px 16px;display:flex;align-items:center;justify-content:space-between;z-index:10;text-align:center;}
.header h1{margin:0;font-size:24px;color:#585959;text-align:center;}
.header a{display:inline-flex;align-items:center;gap:8px;text-decoration:none;background:#111;color:#fff;padding:10px 14px;border-radius:12px;border:1px solid #2a2a34}

.container{max-width:1100px;margin:24px auto;padding:0 16px}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:var(--gap)}
.card{background:#fff;border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;border:1px solid #eee;display:flex;flex-direction:column}
.card figure{margin:0}
.card img,.card video{width:100%;height:auto;display:block;aspect-ratio:4/5;object-fit:cover;background:#000}
.card figcaption{padding:10px 12px;font-size:.95rem;line-height:1.35;border-top:1px solid #f0f0f0;white-space:pre-wrap}
.meta{padding:10px 12px;color:#666;font-size:.8rem;border-top:1px dashed #f2f2f2}

.actions{display:flex;align-items:center;gap:10px;padding:10px 12px;border-top:1px solid #f5f5f5}
.btn{display:inline-flex;align-items:center;gap:8px;padding:5px 14px;border-radius:12px;background:#b0b0b0;color:#fff;border:1px solid #b0b0b0;border-style: outset;font-weight:700;cursor:pointer}
.btn:hover{background:#2ea300}
.btn:active{transform:translateY(1px)}
.count{min-width:2ch;text-align:right;font-variant-numeric:tabular-nums}
.icon{font-size:18px;line-height:1}
.center {display: block;margin-left: auto;margin-right: auto;width: 100%;}
.empty{text-align:center;color:#666;padding:60px 0}
.footer{color:#666;text-align:center;padding:30px 16px}
</style>
</head>
<body>
  <div class="header">
    <h1 class="center">OwnYourSocial.online</h1><!--Hier mit eigenem Text ersetzen-->
  </div>

  <div class="container">
    <?php if (empty($items)): ?>
      <p class="empty">Noch nichts da. <a href="upload.php">Lade das erste Bild/Video hoch</a> ✨</p>
    <?php else: ?>
      <div class="grid" id="grid">
        <?php foreach ($items as $it): 
          $id = item_id($it);
          $isVideo = (($it['type'] ?? '') === 'video');
          $file = (string)($it['file'] ?? '');
          $poster = (string)($it['poster'] ?? '');
          $caption = (string)($it['caption'] ?? '');
          $claps = isset($it['claps']) && is_numeric($it['claps']) ? (int)$it['claps'] : 0;
        ?>
          <article class="card" data-id="<?=h($id)?>">
            <figure>
              <?php if ($isVideo): ?>
                <video controls playsinline preload="none"
                  <?php if (!empty($poster)): ?>poster="<?=h($poster)?>"<?php endif; ?>
                  src="<?=h($file)?>"></video>
              <?php else: ?>
                <img loading="lazy" src="<?=h($file)?>" alt="">
              <?php endif; ?>
              <?php if ($caption !== ''): ?>
                <figcaption><?=nl2br(h($caption))?></figcaption>
              <?php endif; ?>
            </figure>

            <div class="actions">
              <span style="color:#666;font-size:.9rem"><?=date('d.m.Y H:i', (int)($it['time'] ?? time()))?></span>
                <button class="btn clap" type="button" aria-label="Applaus geben">
                <span class="icon">👏</span>
              
              <span class="count" aria-live="polite" data-count><?=h((string)$claps)?></span>
                  </button>
              
            </div>
          </article>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>

  <div class="footer">© <?=date('Y')?> NEUMEdIER.de</div><!--Hier mit eigenem Text ersetzen-->

<script>

document.getElementById('grid')?.addEventListener('click', async (e)=>{
  const btn = e.target.closest('.clap');
  if (!btn) return;
  const card = btn.closest('.card');
  if (!card) return;

  const id = card.dataset.id;
  const countEl = card.querySelector('[data-count]');
  if (!id || !countEl) return;

  const oldVal = parseInt(countEl.textContent || '0', 10) || 0;
  countEl.textContent = (oldVal + 1).toString();

  try {
    const res = await fetch(location.href, {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({action:'clap', id})
    });
    if (!res.ok) throw new Error('Network/Server');
    const data = await res.json();
    if (data?.ok && typeof data.count === 'number') {
      countEl.textContent = String(data.count);
    } else {
      countEl.textContent = String(oldVal);
      console.warn('Clap failed:', data?.error || 'unknown');
    }
  } catch(err) {
    countEl.textContent = String(oldVal);
    console.error(err);
  }
});
</script>
</body>
</html>