<?php
require __DIR__ . '/../_boot.php';
require __DIR__ . '/../partials/nav.php';
if (!$user || !in_array($user['role_name'], ['super_admin','event_manager','walk_leader'], true)) { header('Location: dashboard.php'); exit; }
$canManage = in_array($user['role_name'], ['super_admin','event_manager'], true);
$memberId = (int)($_GET['member_id'] ?? 0);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Loyalty Points | Pyrk Admin</title>
  <link rel="stylesheet" href="../assets/css/app.css">
  <link rel="stylesheet" href="../assets/css/loyalty_settings_pro.css?v=2">
</head>
<body>
<?php pyrk_render_nav('admin'); ?>
<main class="container enterprise-page loyalty-admin-container rewards-suite-page">
  <section class="page-hero admin-hero enterprise-hero rewards-suite-hero">
    <div>
      <p class="eyebrow">Points ledger</p>
      <h1>⭐ Loyalty Points</h1>
      <p class="muted">Review the points ledger, add or deduct points, and open the dedicated badges or prizes pages.</p>
    </div>
    <div class="hero-actions">
      <a class="btn btn-light" href="badges.php">Manage badges</a>
      <a class="btn btn-light" href="prizes.php">Manage prizes</a>
      <a class="btn btn-light" href="members.php">Members CRM</a>
    </div>
  </section>

  <section class="grid four compact-stats" id="loyaltyStats">
    <div class="stat stat-pro"><span>Total members</span><strong id="loyaltyMemberCount">0</strong></div>
    <div class="stat stat-pro"><span>Total points</span><strong id="loyaltyPointTotal">0</strong></div>
    <div class="stat stat-pro"><span>Active badges</span><strong id="activeBadgeCount">0</strong></div>
    <div class="stat stat-pro"><span>Transactions</span><strong id="transactionCount">0</strong></div>
  </section>

  <section class="grid rewards-suite-grid">
    <article class="panel enterprise-table-panel">
      <div class="section-head crm-section-head">
        <div>
          <p class="eyebrow">Ledger</p>
          <h2>Loyalty transactions</h2>
          <p class="muted small">A complete log of point changes from walks, badges, winners, claims and manual adjustments.</p>
        </div>
        <div class="inline-controls search-controls">
          <input id="loyaltySearch" placeholder="Search member, type, reason">
          <select id="transactionMemberFilter"><option value="">All members</option></select>
        </div>
      </div>
      <div class="table-wrap pro-table-wrap loyalty-table-wrap">
        <table class="pro-table loyalty-pro-table">
          <thead><tr><th>Date</th><th>Member</th><th>Type</th><th>Description</th><th>Walk</th><th>Points</th></tr></thead>
          <tbody id="transactionsBody"></tbody>
        </table>
      </div>
    </article>

    <aside class="panel enterprise-form-panel sticky-panel rewards-side-panel">

      <div class="loyalty-settings-card">
        <div class="section-head compact">
          <div>
            <p class="eyebrow">Automatic rules</p>
            <h2>Points per KM</h2>
            <p class="muted small">Controls how many points members earn when a walk is finished. Applies to future completions.</p>
          </div>
        </div>
        <?php if ($canManage): ?>
        <form id="loyaltySettingsForm" class="stack-form loyalty-settings-form">
          <label>Points per KM
            <input name="points_per_km" id="pointsPerKmInput" type="number" step="0.01" min="0" placeholder="10">
          </label>
          <label>Walk completion bonus
            <input name="walk_completion_bonus" id="walkCompletionBonusInput" type="number" step="1" min="0" placeholder="25">
          </label>
          <label>Photo winner points
            <input name="photo_winner_points" id="photoWinnerPointsInput" type="number" step="1" min="0" placeholder="200">
          </label>
          <div class="loyalty-formula-preview" id="loyaltyFormulaPreview">Formula loading...</div>
          <button class="btn" type="submit">Save loyalty rules</button>
          <p id="loyaltySettingsMsg" class="notice"></p>
        </form>
        <?php else: ?>
        <div id="loyaltyFormulaPreview" class="loyalty-formula-preview">Walk leaders can view the rules. Super Admin and Event Manager can change them.</div>
        <?php endif; ?>
      </div>

      <?php if ($canManage): ?>
      <div class="loyalty-repair-card">
        <div>
          <p class="eyebrow">Repair tool</p>
          <h2>Recalculate completed walks</h2>
          <p class="muted small">Use this once if completed walks were saved with 0 points. It recalculates finished walks using the current rules and keeps manual adjustments untouched.</p>
        </div>
        <button class="btn btn-light" id="repairWalkPointsBtn" type="button">Fix completed-walk points</button>
        <p id="repairWalkPointsMsg" class="notice"></p>
      </div>
      <?php endif; ?>

      <div class="section-head"><div><p class="eyebrow">Member points</p><h2>Adjust points</h2></div></div>
      <div class="loyalty-member-focus" id="selectedMemberCard"></div>
      <?php if ($canManage): ?>
      <form id="pointsForm" class="stack-form loyalty-action-form">
        <label>Member<select name="member_id" id="pointsMember" required></select></label>
        <label>Points change<input name="points" id="pointsChange" type="number" required placeholder="Example: 100 or -25"></label>
        <label>Reason<input name="description" id="pointsReason" placeholder="Example: Event reward"></label>
        <button class="btn" type="submit">Save points adjustment</button>
        <p id="pointsMsg" class="notice"></p>
      </form>
      <?php else: ?>
      <p class="muted">Walk leaders can view loyalty data. Super Admin and Event Manager can adjust points.</p>
      <?php endif; ?>
    </aside>
  </section>
</main>
<script>
window.PYRK_API_BASE='../../api';
window.PYRK_CSRF='<?= htmlspecialchars($csrf) ?>';
window.PYRK_CAN_MANAGE_LOYALTY=<?= $canManage ? 'true' : 'false' ?>;
window.PYRK_PUBLIC_BASE='../';
window.PYRK_SELECTED_MEMBER_ID=<?= $memberId ?>;
</script>
<script src="../assets/js/api.js"></script>
<script src="../assets/js/admin_loyalty.js?v=3"></script>
</body>
</html>
