<?php
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/plugins.php';
require_admin();
$admin = current_user();

// --- Acciones ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $action = $_POST['action'] ?? '';

    if ($action === 'activate') {
        $orderId = (int)($_POST['order_id'] ?? 0);
        $st = db()->prepare("SELECT * FROM orders WHERE id=? AND status='pending'");
        $st->execute([$orderId]);
        $o = $st->fetch();
        if ($o) {
            // ¿ya tiene licencia de ese plugin? si no, crearla.
            if (!user_has_license((int)$o['user_id'], $o['plugin_slug'])) {
                // llave única (reintenta si choca)
                do {
                    $key = gen_license_key($o['plugin_slug']);
                    $c = db()->prepare('SELECT 1 FROM licenses WHERE license_key=?');
                    $c->execute([$key]);
                } while ($c->fetchColumn());
                $ins = db()->prepare(
                    'INSERT INTO licenses (user_id, plugin_slug, edition, license_key, status, activated_by)
                     VALUES (?, ?, "premium", ?, "active", ?)'
                );
                $ins->execute([$o['user_id'], $o['plugin_slug'], $key, $admin['id']]);
            }
            db()->prepare("UPDATE orders SET status='verified', verified_by=?, verified_at=NOW() WHERE id=?")
                ->execute([$admin['id'], $orderId]);
            flash_set('ok', 'Licencia activada para la orden #' . $orderId . '.');
        }
    } elseif ($action === 'reject') {
        $orderId = (int)($_POST['order_id'] ?? 0);
        db()->prepare("UPDATE orders SET status='rejected', verified_by=?, verified_at=NOW() WHERE id=? AND status='pending'")
            ->execute([$admin['id'], $orderId]);
        flash_set('info', 'Orden #' . $orderId . ' rechazada.');
    } elseif ($action === 'revoke') {
        $licId = (int)($_POST['license_id'] ?? 0);
        db()->prepare("UPDATE licenses SET status='revoked' WHERE id=?")->execute([$licId]);
        flash_set('info', 'Licencia revocada.');
    } elseif ($action === 'review_hide' || $action === 'review_show') {
        $rid = (int)($_POST['review_id'] ?? 0);
        $new = $action === 'review_hide' ? 'hidden' : 'visible';
        db()->prepare('UPDATE reviews SET status=? WHERE id=?')->execute([$new, $rid]);
        flash_set('ok', 'Reseña actualizada.');
    } elseif ($action === 'review_reply') {
        $rid = (int)($_POST['review_id'] ?? 0);
        $reply = trim($_POST['reply'] ?? '');
        try {
            if ($reply === '') {
                db()->prepare('UPDATE reviews SET admin_reply=NULL, admin_reply_at=NULL WHERE id=?')->execute([$rid]);
            } else {
                db()->prepare('UPDATE reviews SET admin_reply=?, admin_reply_at=NOW() WHERE id=?')->execute([$reply, $rid]);
            }
            flash_set('ok', 'Respuesta guardada.');
        } catch (Throwable $e) {
            flash_set('info', 'Falta la columna admin_reply en la BD — ejecuta el ALTER indicado en phpMyAdmin.');
        }
    }
    redirect(BASE . '/admin/');
}

// --- Datos ---
$pending = db()->query(
    "SELECT o.*, u.username FROM orders o JOIN users u ON u.id=o.user_id
     WHERE o.status='pending' ORDER BY o.created_at ASC"
)->fetchAll();

$lics = db()->query(
    "SELECT l.*, u.username FROM licenses l JOIN users u ON u.id=l.user_id
     WHERE l.status='active' ORDER BY l.created_at DESC LIMIT 30"
)->fetchAll();

$revs = db()->query(
    "SELECT r.*, u.username FROM reviews r JOIN users u ON u.id=r.user_id
     ORDER BY r.created_at DESC LIMIT 30"
)->fetchAll();

$counts = [
  'users'   => (int)db()->query('SELECT COUNT(*) FROM users')->fetchColumn(),
  'pending' => count($pending),
  'lics'    => (int)db()->query("SELECT COUNT(*) FROM licenses WHERE status='active'")->fetchColumn(),
];

$page_title = 'Admin';
require __DIR__ . '/../includes/header.php';
?>
<div class="wrap" style="padding:26px 20px 60px">
  <div class="eyebrow">Panel de control</div>
  <h1 style="font-size:28px;font-weight:800;margin:8px 0 20px">Admin</h1>

  <div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(150px,1fr));margin-bottom:26px">
    <div class="card" style="padding:16px"><div style="font:600 11px/1 var(--mono);color:var(--muted2);text-transform:uppercase;letter-spacing:.1em">Usuarios</div><div style="font-size:26px;font-weight:900;margin-top:6px"><?= $counts['users'] ?></div></div>
    <div class="card" style="padding:16px"><div style="font:600 11px/1 var(--mono);color:var(--muted2);text-transform:uppercase;letter-spacing:.1em">Pagos pendientes</div><div style="font-size:26px;font-weight:900;margin-top:6px;color:<?= $counts['pending']?'var(--gold)':'inherit' ?>"><?= $counts['pending'] ?></div></div>
    <div class="card" style="padding:16px"><div style="font:600 11px/1 var(--mono);color:var(--muted2);text-transform:uppercase;letter-spacing:.1em">Licencias activas</div><div style="font-size:26px;font-weight:900;margin-top:6px"><?= $counts['lics'] ?></div></div>
  </div>

  <!-- PAGOS PENDIENTES -->
  <h3 class="sub" style="margin-top:0">💳 Pagos por verificar</h3>
  <?php if ($pending): ?>
    <div class="card" style="padding:6px 4px">
      <?php foreach ($pending as $o): $p = plugin_get($o['plugin_slug']); ?>
        <div class="brow">
          <span style="font-size:20px"><?= $p['icon'] ?? '🎮' ?></span>
          <div style="min-width:0">
            <b><?= e($o['username']) ?></b> · <?= e($p['name'] ?? $o['plugin_slug']) ?> Premium
            <div style="font-size:12px;color:var(--muted2)">PayPal: <span class="mono"><?= e($o['paypal_email']) ?></span><?php if ($o['paypal_txn']): ?> · txn <span class="mono"><?= e($o['paypal_txn']) ?></span><?php endif; ?> · $<?= e(number_format((float)$o['amount'],2)) ?> · <?= e(date('d M H:i', strtotime($o['created_at']))) ?></div>
          </div>
          <span class="sp">
            <form method="post" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="activate"><input type="hidden" name="order_id" value="<?= (int)$o['id'] ?>"><button class="btn primary sm" type="submit">✓ Activar licencia</button></form>
            <form method="post" style="display:inline" onsubmit="return confirm('¿Rechazar esta orden?')"><?= csrf_field() ?><input type="hidden" name="action" value="reject"><input type="hidden" name="order_id" value="<?= (int)$o['id'] ?>"><button class="btn danger sm" type="submit">Rechazar</button></form>
          </span>
        </div>
      <?php endforeach; ?>
    </div>
  <?php else: ?>
    <div class="alert alert-info">No hay pagos pendientes. 🎉</div>
  <?php endif; ?>

  <!-- LICENCIAS -->
  <h3 class="sub">🔑 Licencias activas</h3>
  <div class="card" style="padding:6px 4px">
    <?php if ($lics): foreach ($lics as $l): $p = plugin_get($l['plugin_slug']); ?>
      <div class="brow">
        <span style="font-size:18px"><?= $p['icon'] ?? '🎮' ?></span>
        <div><b><?= e($l['username']) ?></b> · <span class="mono" style="font-size:12px;color:var(--gold)"><?= e($l['license_key']) ?></span>
          <div style="font-size:12px;color:var(--muted2)"><?= e($p['name'] ?? $l['plugin_slug']) ?> · <?= e(date('d M Y', strtotime($l['created_at']))) ?></div></div>
        <span class="sp"><form method="post" onsubmit="return confirm('¿Revocar esta licencia?')"><?= csrf_field() ?><input type="hidden" name="action" value="revoke"><input type="hidden" name="license_id" value="<?= (int)$l['id'] ?>"><button class="btn danger sm" type="submit">Revocar</button></form></span>
      </div>
    <?php endforeach; else: ?><div class="brow" style="color:var(--muted2)">Sin licencias todavía.</div><?php endif; ?>
  </div>

  <!-- RESEÑAS -->
  <h3 class="sub">⭐ Reseñas</h3>
  <div class="card" style="padding:6px 4px">
    <?php if ($revs): foreach ($revs as $r): ?>
      <div class="brow">
        <span class="stars" style="min-width:70px"><?= stars_html((int)$r['rating']) ?></span>
        <div style="min-width:0"><b><?= e($r['username']) ?></b> <span style="font-size:12px;color:var(--muted2)">· <?= e($r['plugin_slug']) ?> · <?= e(date('d M', strtotime($r['created_at']))) ?><?php if ($r['status']==='hidden'): ?> · <span class="b-red badge">Oculta</span><?php endif; ?></span>
          <div style="font-size:13px;color:var(--muted)"><?= e(mb_strimwidth($r['comment'],0,90,'…')) ?></div></div>
        <span class="sp">
          <?php $act = $r['status']==='visible' ? 'review_hide' : 'review_show'; $lbl = $r['status']==='visible' ? 'Ocultar' : 'Mostrar'; ?>
          <form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="<?= $act ?>"><input type="hidden" name="review_id" value="<?= (int)$r['id'] ?>"><button class="btn ghost sm" type="submit"><?= $lbl ?></button></form>
        </span>
      </div>
      <form method="post" style="display:flex;gap:8px;align-items:flex-start;padding:0 12px 12px 82px">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="review_reply">
        <input type="hidden" name="review_id" value="<?= (int)$r['id'] ?>">
        <textarea name="reply" maxlength="1000" placeholder="Responder como 👑 ADMIN… (vacío = borrar)" style="flex:1;min-height:36px;background:var(--panel2,#211a3d);border:1px solid var(--line2,rgba(255,255,255,.14));border-radius:9px;color:var(--text,#fff);padding:8px 10px;font-family:inherit;font-size:13px;resize:vertical"><?= htmlspecialchars($r['admin_reply'] ?? '', ENT_QUOTES) ?></textarea>
        <button class="btn primary sm" type="submit">Responder</button>
      </form>
    <?php endforeach; else: ?><div class="brow" style="color:var(--muted2)">Sin reseñas todavía.</div><?php endif; ?>
  </div>
</div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
