<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
requireAdmin();
$success = ''; $error = '';
$extra = [];
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

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

    if ($action === 'grant') {
        $id   = (int)($_POST['id'] ?? 0);
        $days = (int)($_POST['days'] ?? 30);
        if ($id) {
            if ($days > 0) {
                $stmt = $pdo->prepare("SELECT pro_expires_at, is_pro FROM users WHERE id=?");
                $stmt->execute([$id]); $row = $stmt->fetch();
                $base = (isset($row['pro_expires_at']) && $row['pro_expires_at'] && strtotime($row['pro_expires_at']) > time()) ? strtotime($row['pro_expires_at']) : time();
                $newExpiry = date('Y-m-d H:i:s', strtotime("+{$days} days", $base));
                $pdo->prepare("UPDATE users SET is_pro=1, pro_plan='admin_grant', pro_started_at=COALESCE(pro_started_at,NOW()), pro_expires_at=? WHERE id=?")->execute([$newExpiry, $id]);
                $extra = ['expires' => date('M j, Y', strtotime($newExpiry)), 'plan' => 'admin_grant'];
            } else {
                // 0/blank days = lifetime (no expiry)
                $pdo->prepare("UPDATE users SET is_pro=1, pro_plan='admin_grant', pro_started_at=COALESCE(pro_started_at,NOW()), pro_expires_at=NULL WHERE id=?")->execute([$id]);
                $extra = ['expires' => 'Lifetime', 'plan' => 'admin_grant'];
            }
            $success = 'Pro access granted.';
        } else {
            $error = 'Invalid user.';
        }
    }
    if ($action === 'revoke') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) {
            $pdo->prepare("UPDATE users SET is_pro=0, pro_plan=NULL, pro_expires_at=NULL WHERE id=?")->execute([$id]);
            $success = 'Pro access revoked.';
        } else {
            $error = 'Invalid user.';
        }
    }
    if ($action === 'save_pricing') {
        $monthly     = (float)($_POST['pro_price_monthly'] ?? 0);
        $yearly      = (float)($_POST['pro_price_yearly'] ?? 0);
        $aiLimit     = (int)($_POST['free_ai_daily_limit'] ?? 3);
        $subLimit    = (int)($_POST['free_subject_limit'] ?? FREE_SUBJECT_LIMIT_DEFAULT);
        $musicLimit  = (int)($_POST['free_music_search_daily_limit'] ?? FREE_MUSIC_SEARCH_DAILY_LIMIT_DEFAULT);
        foreach ([
            ['pro_price_monthly', $monthly],
            ['pro_price_yearly', $yearly],
            ['free_ai_daily_limit', $aiLimit],
            ['free_subject_limit', $subLimit],
            ['free_music_search_daily_limit', $musicLimit],
        ] as [$k,$v]) {
            $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$k,$v,$v]);
        }
        $success = 'Pricing & limits saved.';
    }
    if ($action === 'delete_payment') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) {
            $pdo->prepare("DELETE FROM payhere_payments WHERE id=?")->execute([$id]);
            $success = 'Payment record deleted.';
        } else {
            $error = 'Invalid record.';
        }
    }

    // ── AJAX response: return JSON popup message instead of reloading the page ──
    if ($isAjax) {
        jsonResponse(array_merge([
            'success' => $success !== '' ,
            'msg'     => $success !== '' ? $success : ($error !== '' ? $error : 'Unknown action.'),
        ], $extra));
    }
}

$search = trim($_GET['q'] ?? '');
$proUsers = [];
if ($search !== '') {
    $proUsersQ = $pdo->prepare("SELECT id,name,email,is_pro,pro_plan,pro_started_at,pro_expires_at FROM users WHERE (name LIKE ? OR email LIKE ?) ORDER BY is_pro DESC, pro_expires_at DESC LIMIT 100");
    $proUsersQ->execute(["%$search%", "%$search%"]);
    $proUsers = $proUsersQ->fetchAll();
}

$totalPro = $pdo->query("SELECT COUNT(*) FROM users WHERE is_pro=1")->fetchColumn();
$totalRevenueRow = $pdo->query("SELECT COALESCE(SUM(amount),0) as rev, COUNT(*) as cnt FROM payhere_payments WHERE status='completed'")->fetch();
$recentPayments = $pdo->query("SELECT p.*, u.name, u.email FROM payhere_payments p JOIN users u ON u.id=p.user_id ORDER BY p.created_at DESC LIMIT 20")->fetchAll();

$priceMonthly = getSiteSetting('pro_price_monthly', PRO_PRICE_MONTHLY_DEFAULT);
$priceYearly  = getSiteSetting('pro_price_yearly', PRO_PRICE_YEARLY_DEFAULT);
$freeLimit    = getSiteSetting('free_ai_daily_limit', FREE_AI_DAILY_LIMIT_DEFAULT);
$freeSubLimit = getSiteSetting('free_subject_limit', FREE_SUBJECT_LIMIT_DEFAULT);
$freeMusicLimit = getSiteSetting('free_music_search_daily_limit', FREE_MUSIC_SEARCH_DAILY_LIMIT_DEFAULT);

require_once 'includes/header.php';
renderAdminHeader('Pro Subscriptions', 'pro-subscriptions');
?>
<div id="toastContainer" style="position:fixed;top:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:10px;pointer-events:none"></div>

<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-bottom:18px;">
  <div class="card"><div style="font-size:26px;font-weight:800;"><?= (int)$totalPro ?></div><div style="color:var(--text-muted);font-size:13px;">Active Pro users</div></div>
  <div class="card"><div style="font-size:26px;font-weight:800;"><?= $priceMonthly ? htmlspecialchars(getSiteSetting('pro_currency','LKR')) : '' ?> <?= number_format((float)$totalRevenueRow['rev'],2) ?></div><div style="color:var(--text-muted);font-size:13px;">Total completed revenue</div></div>
  <div class="card"><div style="font-size:26px;font-weight:800;"><?= (int)$totalRevenueRow['cnt'] ?></div><div style="color:var(--text-muted);font-size:13px;">Completed payments</div></div>
</div>

<div class="card" style="margin-bottom:18px;">
  <div class="card-header"><div class="card-title">⚙️ Pricing &amp; Free-tier Limit</div></div>
  <form method="POST" onsubmit="return ajaxSubmit(event,this)" style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr 1fr auto;gap:12px;align-items:end;">
    <input type="hidden" name="action" value="save_pricing">
    <div class="form-group"><label class="form-label">Monthly price (LKR)</label><input type="number" step="0.01" name="pro_price_monthly" class="form-control" value="<?= htmlspecialchars($priceMonthly) ?>"></div>
    <div class="form-group"><label class="form-label">Yearly price (LKR)</label><input type="number" step="0.01" name="pro_price_yearly" class="form-control" value="<?= htmlspecialchars($priceYearly) ?>"></div>
    <div class="form-group"><label class="form-label">Free AI requests/day</label><input type="number" name="free_ai_daily_limit" class="form-control" value="<?= htmlspecialchars($freeLimit) ?>"></div>
    <div class="form-group"><label class="form-label">Free subject limit</label><input type="number" name="free_subject_limit" class="form-control" value="<?= htmlspecialchars($freeSubLimit) ?>"></div>
    <div class="form-group"><label class="form-label">Free music searches/day</label><input type="number" name="free_music_search_daily_limit" class="form-control" value="<?= htmlspecialchars($freeMusicLimit) ?>"></div>
    <button type="submit" class="btn btn-primary">Save</button>
  </form>
</div>

<div class="card" style="margin-bottom:18px;">
  <div class="card-header"><div class="card-title">👥 Users &amp; Pro Status</div></div>
  <form method="GET" style="margin-bottom:14px;"><input type="text" name="q" class="form-control" placeholder="Search by name or email to find a user…" value="<?= htmlspecialchars($search) ?>" autofocus></form>
  <?php if ($search === ''): ?>
    <div style="text-align:center;color:var(--text-muted);padding:24px 10px;font-size:13px;">🔍 Search for a user by name or email to view or manage their Pro status.</div>
  <?php else: ?>
  <div style="overflow-x:auto;" class="table-wrapper">
  <table style="width:100%;">
    <thead><tr><th>Name</th><th>Email</th><th>Status</th><th>Plan</th><th>Expires</th><th>Action</th></tr></thead>
    <tbody>
    <?php foreach ($proUsers as $u):
      $isPro = (int)$u['is_pro'] === 1 && (empty($u['pro_expires_at']) || strtotime($u['pro_expires_at']) > time());
    ?>
      <tr id="pro-row-<?= $u['id'] ?>">
        <td><?= htmlspecialchars($u['name']) ?></td>
        <td><?= htmlspecialchars($u['email']) ?></td>
        <td data-cell="status"><?php if ($isPro): ?><span class="badge badge-green">⚡ Pro</span><?php else: ?><span class="badge" style="background:var(--bg-secondary);color:var(--text-muted);">Free</span><?php endif; ?></td>
        <td data-cell="plan"><?= htmlspecialchars($u['pro_plan'] ?? '—') ?></td>
        <td data-cell="expires"><?= $u['pro_expires_at'] ? date('M j, Y', strtotime($u['pro_expires_at'])) : ($isPro ? 'Lifetime' : '—') ?></td>
        <td data-cell="actions" style="display:flex;gap:6px;">
          <form method="POST" onsubmit="return ajaxGrantRevoke(event,this,<?= $u['id'] ?>,'grant')" style="display:flex;gap:4px;">
            <input type="hidden" name="action" value="grant">
            <input type="hidden" name="id" value="<?= $u['id'] ?>">
            <select name="days" class="form-control" style="width:110px;padding:6px;font-size:12px;">
              <option value="30">+30 days</option>
              <option value="365">+365 days</option>
              <option value="0">Lifetime</option>
            </select>
            <button type="submit" class="btn btn-secondary btn-sm">Grant</button>
          </form>
          <?php if ($isPro): ?>
          <form method="POST" onsubmit="return confirm('Revoke Pro for this user?') && ajaxGrantRevoke(event,this,<?= $u['id'] ?>,'revoke')">
            <input type="hidden" name="action" value="revoke">
            <input type="hidden" name="id" value="<?= $u['id'] ?>">
            <button type="submit" class="btn btn-danger btn-sm">Revoke</button>
          </form>
          <?php endif; ?>
        </td>
      </tr>
    <?php endforeach; ?>
    <?php if (!$proUsers): ?><tr><td colspan="6" style="text-align:center;color:var(--text-muted);">No users found for "<?= htmlspecialchars($search) ?>".</td></tr><?php endif; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>

<div class="card">
  <div class="card-header"><div class="card-title">💳 Recent Payments</div></div>
  <div style="overflow-x:auto;" class="table-wrapper">
  <table style="width:100%;">
    <thead><tr><th>Date</th><th>User</th><th>Plan</th><th>Amount</th><th>Status</th><th>Order ID</th><th>Action</th></tr></thead>
    <tbody>
    <?php foreach ($recentPayments as $p): ?>
      <tr id="payment-row-<?= $p['id'] ?>">
        <td><?= date('M j, Y H:i', strtotime($p['created_at'])) ?></td>
        <td><?= htmlspecialchars($p['name']) ?> <span style="color:var(--text-muted);font-size:12px;">(<?= htmlspecialchars($p['email']) ?>)</span></td>
        <td><?= htmlspecialchars($p['plan']) ?></td>
        <td><?= htmlspecialchars($p['currency']) ?> <?= number_format((float)$p['amount'],2) ?></td>
        <td>
          <?php $statusColor = ['completed'=>'badge-green','pending'=>'badge-yellow','failed'=>'badge-red','canceled'=>'','chargedback'=>'badge-red'][$p['status']] ?? ''; ?>
          <span class="badge <?= $statusColor ?>"><?= htmlspecialchars($p['status']) ?></span>
        </td>
        <td style="font-size:11px;color:var(--text-muted);"><?= htmlspecialchars($p['order_id']) ?></td>
        <td>
          <form method="POST" onsubmit="return confirm('Delete this payment record? This cannot be undone.') && ajaxDeletePayment(event,this,<?= $p['id'] ?>)">
            <input type="hidden" name="action" value="delete_payment">
            <input type="hidden" name="id" value="<?= $p['id'] ?>">
            <button type="submit" class="btn btn-danger btn-sm">🗑️ Delete</button>
          </form>
        </td>
      </tr>
    <?php endforeach; ?>
    <?php if (!$recentPayments): ?><tr><td colspan="7" style="text-align:center;color:var(--text-muted);">No payments yet.</td></tr><?php endif; ?>
    </tbody>
  </table>
  </div>
</div>

<style>
@keyframes slideInRight  { from{opacity:0;transform:translateX(20px)} to{opacity:1;transform:translateX(0)} }
@keyframes slideOutRight { from{opacity:1;transform:translateX(0)} to{opacity:0;transform:translateX(20px)} }
</style>
<script>
// ── Toast popup system (replaces the old "reload page to see message" alert) ──
function showToast(msg, type) {
  var tc = document.getElementById('toastContainer');
  var t  = document.createElement('div');
  var bg = type === 'success' ? 'rgba(16,185,129,.95)' : 'rgba(239,68,68,.95)';
  t.style.cssText = "background:" + bg + ";color:#fff;padding:13px 20px;border-radius:10px;font-size:14px;font-weight:600;box-shadow:0 8px 32px rgba(0,0,0,.4);pointer-events:auto;display:flex;align-items:center;gap:10px;min-width:240px;animation:slideInRight .25s ease";
  t.innerHTML = '<span>' + (type === 'success' ? '✅ ' : '⚠️ ') + msg + '</span><button onclick="this.parentElement.remove()" style="background:none;border:none;color:#fff;cursor:pointer;margin-left:auto;font-size:18px;line-height:1;opacity:.7">×</button>';
  tc.appendChild(t);
  setTimeout(function(){ t.style.animation = 'slideOutRight .3s ease forwards'; setTimeout(function(){ t.remove(); }, 300); }, 3500);
}

function ajaxPost(form) {
  var fd = new FormData(form);
  return fetch(window.location.href, {
    method: 'POST',
    body: new URLSearchParams(fd),
    headers: {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded'}
  }).then(function(r){ return r.json(); });
}

// Pricing / limits form — no DOM change needed, just popup the result
function ajaxSubmit(evt, form) {
  evt.preventDefault();
  var btn = form.querySelector('button[type=submit]');
  if (btn) btn.disabled = true;
  ajaxPost(form).then(function(d){
    showToast(d.msg, d.success ? 'success' : 'error');
  }).catch(function(){
    showToast('Network error. Please try again.', 'error');
  }).finally(function(){
    if (btn) btn.disabled = false;
  });
  return false;
}

// Grant / Revoke — update that user's row in place
function ajaxGrantRevoke(evt, form, userId, kind) {
  evt.preventDefault();
  var btn = form.querySelector('button[type=submit]');
  if (btn) btn.disabled = true;
  ajaxPost(form).then(function(d){
    showToast(d.msg, d.success ? 'success' : 'error');
    if (d.success) {
      var row = document.getElementById('pro-row-' + userId);
      if (!row) return;
      var statusCell = row.querySelector('[data-cell="status"]');
      var planCell   = row.querySelector('[data-cell="plan"]');
      var expiresCell= row.querySelector('[data-cell="expires"]');
      var actionsCell= row.querySelector('[data-cell="actions"]');
      if (kind === 'grant') {
        statusCell.innerHTML = '<span class="badge badge-green">⚡ Pro</span>';
        planCell.textContent = d.plan || 'admin_grant';
        expiresCell.textContent = d.expires || 'Lifetime';
        if (!actionsCell.querySelector('.btn-danger')) {
          var revokeForm = document.createElement('form');
          revokeForm.method = 'POST';
          revokeForm.setAttribute('onsubmit', "return confirm('Revoke Pro for this user?') && ajaxGrantRevoke(event,this," + userId + ",'revoke')");
          revokeForm.innerHTML = '<input type="hidden" name="action" value="revoke"><input type="hidden" name="id" value="' + userId + '"><button type="submit" class="btn btn-danger btn-sm">Revoke</button>';
          actionsCell.appendChild(revokeForm);
        }
      } else {
        statusCell.innerHTML = '<span class="badge" style="background:var(--bg-secondary);color:var(--text-muted);">Free</span>';
        planCell.textContent = '—';
        expiresCell.textContent = '—';
        var revokeBtnForm = form; // the form that was just submitted (revoke form)
        revokeBtnForm.remove();
      }
    }
  }).catch(function(){
    showToast('Network error. Please try again.', 'error');
  }).finally(function(){
    if (btn) btn.disabled = false;
  });
  return false;
}

// Delete payment — remove the row from the table
function ajaxDeletePayment(evt, form, paymentId) {
  evt.preventDefault();
  ajaxPost(form).then(function(d){
    showToast(d.msg, d.success ? 'success' : 'error');
    if (d.success) {
      var row = document.getElementById('payment-row-' + paymentId);
      if (row) row.remove();
    }
  }).catch(function(){
    showToast('Network error. Please try again.', 'error');
  });
  return false;
}
</script>
<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
