<?php
require __DIR__ . '/../_boot.php';
require __DIR__ . '/../partials/nav.php';

if (!$user || !\App\Core\Auth::hasPermission('notifications.manage', $user)) {
    header('Location: dashboard.php');
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Push Notifications | Pyrk Admin</title>
  <link rel="stylesheet" href="../assets/css/app.css">
  <link rel="stylesheet" href="../assets/css/admin_manual_notifications.css?v=push-presets-pro-v1">
</head>
<body>
<?php pyrk_render_nav('admin'); ?>

<main class="container enterprise-page push-admin-page">
  <section class="page-hero admin-hero enterprise-hero push-hero">
    <div>
      <p class="eyebrow">Member communication</p>
      <h1>Push notifications</h1>
      <p class="muted">Send manual announcements to all members, selected teams, or selected members by web notification, native phone push, email and WhatsApp.</p>
    </div>
    <div class="hero-actions">
      <button class="btn btn-light" type="button" id="previewPushBtn">Preview notification</button>
      <button class="btn" type="button" id="sendPushBtn">Send notification</button>
    </div>
  </section>

  <section class="grid four compact-stats push-stats-grid">
    <div class="stat stat-pro"><span>Active members</span><strong id="pushMemberCount">0</strong></div>
    <div class="stat stat-pro"><span>Teams / groups</span><strong id="pushGroupCount">0</strong></div>
    <div class="stat stat-pro"><span>App-ready members</span><strong id="pushNativeMemberCount">0</strong></div>
    <div class="stat stat-pro"><span>Recent sends</span><strong id="pushBatchCount">0</strong></div>
  </section>

  <section class="grid push-layout">
    <section class="panel push-compose-panel">
      <div class="section-head">
        <div>
          <p class="eyebrow">Compose</p>
          <h2>Message details</h2>
        </div>
      </div>

      <form id="pushForm" class="stack-form">
        <section class="push-message-setup" aria-labelledby="deliveryHeading">
          <div class="push-block-heading">
            <span class="push-step-number">1</span>
            <div>
              <p class="eyebrow">Delivery</p>
              <h3 id="deliveryHeading">Choose how members receive it</h3>
              <p class="muted small">Select one or more independent channels. A channel is used only when its checkbox is selected.</p>
            </div>
          </div>

          <fieldset class="push-channel-fieldset">
            <legend class="sr-only">Notification delivery channels</legend>
            <div class="push-channel-grid">
              <label class="push-channel-card is-selected" data-push-channel-card>
                <input type="checkbox" id="deliveryWeb" checked>
                <span class="push-channel-check" aria-hidden="true">✓</span>
                <span class="push-channel-icon" aria-hidden="true">▣</span>
                <span class="push-channel-copy">
                  <strong>Web notification</strong>
                  <small>Appears in the member notification center.</small>
                  <span class="push-channel-status is-ready">Ready</span>
                </span>
              </label>

              <label class="push-channel-card native-push-channel-row" data-push-channel-card id="nativePushChannelCard">
                <input type="checkbox" id="deliveryNative">
                <span class="push-channel-check" aria-hidden="true">✓</span>
                <span class="push-channel-icon" aria-hidden="true">◉</span>
                <span class="push-channel-copy">
                  <strong>Phone push</strong>
                  <small id="nativePushHint">Checking Firebase, APNs and registered app devices…</small>
                  <span class="push-platform-statuses" aria-label="Phone push readiness">
                    <span id="nativeAndroidStatus" class="push-channel-status is-warning">Android: checking</span>
                    <span id="nativeIosStatus" class="push-channel-status is-warning">iOS: checking</span>
                    <span id="nativeDeviceStatus" class="push-channel-status">0 app members</span>
                  </span>
                </span>
              </label>

              <label class="push-channel-card" data-push-channel-card>
                <input type="checkbox" id="deliveryEmail">
                <span class="push-channel-check" aria-hidden="true">✓</span>
                <span class="push-channel-icon" aria-hidden="true">✉</span>
                <span class="push-channel-copy">
                  <strong>Email</strong>
                  <small>Sends the formatted message and attachment links.</small>
                  <span class="push-channel-status is-ready">Available</span>
                </span>
              </label>

              <label class="push-channel-card whatsapp-channel-card" data-push-channel-card id="whatsappChannelCard">
                <input type="checkbox" id="deliveryWhatsapp">
                <span class="push-channel-check" aria-hidden="true">✓</span>
                <span class="push-channel-icon" aria-hidden="true">◌</span>
                <span class="push-channel-copy">
                  <strong>WhatsApp via UltraMsg</strong>
                  <small id="whatsappProviderHint">Checking the safe queue and UltraMsg configuration…</small>
                  <span class="push-platform-statuses" aria-label="WhatsApp readiness">
                    <span id="whatsappProviderStatus" class="push-channel-status is-warning">Provider: checking</span>
                    <span id="whatsappQueueStatus" class="push-channel-status is-warning">Queue: checking</span>
                    <span id="whatsappDailyStatus" class="push-channel-status">Daily limit</span>
                  </span>
                  <button class="btn btn-light btn-small whatsapp-test-btn" type="button" id="testWhatsAppConnectionBtn">Test connection</button>
                </span>
              </label>
            </div>
          </fieldset>

          <section class="whatsapp-safety-card" id="whatsappSafetyPanel" hidden>
            <div>
              <p class="eyebrow">Safe bulk queue</p>
              <h3>WhatsApp protection controls</h3>
              <p class="muted small" id="whatsappSafetyHint">Messages are queued and released gradually by the cPanel cron worker. They are not blasted from this page.</p>
            </div>
            <div class="whatsapp-safety-grid">
              <div><span>Per batch</span><strong id="whatsappBatchLimit">50 maximum</strong></div>
              <div><span>Per day</span><strong id="whatsappRemainingToday">Checking…</strong></div>
              <div><span>Worker pace</span><strong id="whatsappWorkerPace">5 per cron run</strong></div>
              <div><span>Duplicate guard</span><strong id="whatsappDuplicateWindow">24 hours</strong></div>
            </div>
            <label class="check whatsapp-consent-check">
              <input type="checkbox" id="whatsappConsentConfirmed" value="1">
              <span>I confirm these members consented to receive this operational WhatsApp message.</span>
            </label>
            <p class="muted small">A fresh recipient preview is mandatory before queueing. Duplicate numbers and repeated identical messages are skipped automatically.</p>
          </section>
        </section>

        <section class="push-message-setup" aria-labelledby="audienceHeading">
          <div class="push-block-heading">
            <span class="push-step-number">2</span>
            <div>
              <p class="eyebrow">Audience</p>
              <h3 id="audienceHeading">Choose the recipients</h3>
              <p class="muted small">Preview the resolved recipients before sending.</p>
            </div>
          </div>
          <label class="push-audience-field" for="pushTargetScope">
            <span>Recipient group</span>
            <select id="pushTargetScope">
              <option value="all_members">All active members</option>
              <option value="selected_groups">Selected teams / groups</option>
              <option value="selected_members">Selected members</option>
              <option value="walk_registrants">Walk registrants / reminder</option>
            </select>
            <small id="pushAudienceInlineHint">All active members are currently selected.</small>
          </label>
        </section>

        <section class="walk-reminder-card push-preset-picker-card">
          <div class="section-head mini-head">
            <div>
              <p class="eyebrow">Reusable content</p>
              <h3>Push notification preset</h3>
              <p class="muted small">Choose an active Push preset. Push presets are managed separately from WhatsApp presets.</p>
            </div>
            <a class="btn btn-light btn-small" href="push_notification_presets.php">Manage Push presets</a>
          </div>
          <div class="form-grid two">
            <label>Walk context
              <select id="pushWalkId"><option value="">No walk selected</option></select>
              <small>Required only when the preset uses walk variables.</small>
            </label>
            <label>Push preset
              <select id="pushPreset"><option value="">Loading active presets…</option></select>
              <input type="hidden" id="pushPresetId" value="">
            </label>
          </div>
          <div class="inline-controls">
            <button class="btn btn-light btn-small" type="button" id="applyWalkPresetBtn">Apply preset</button>
            <button class="btn btn-light btn-small" type="button" id="useWalkAudienceBtn">Use selected walk registrants</button>
          </div>
          <small id="pushPresetHelp" class="muted">Loading Push presets…</small>
        </section>

        <label>Subject
          <input id="pushSubject" maxlength="180" placeholder="Example: Sunday walk update" required>
        </label>

        <label class="rich-editor-label">Message
          <input type="hidden" id="pushMessage">
          <input type="hidden" id="pushMessageHtml">
          <div class="rich-editor-card">
            <div class="rich-editor-toolbar" aria-label="Message formatting toolbar">
              <button type="button" data-rich-command="bold"><strong>B</strong></button>
              <button type="button" data-rich-command="italic"><em>I</em></button>
              <button type="button" data-rich-command="underline"><u>U</u></button>
              <span class="toolbar-separator"></span>
              <button type="button" data-rich-command="insertUnorderedList">• List</button>
              <button type="button" data-rich-command="insertOrderedList">1. List</button>
              <button type="button" data-rich-block="h3">Heading</button>
              <button type="button" data-rich-block="blockquote">Quote</button>
              <span class="toolbar-separator"></span>
              <button type="button" data-rich-link>Link</button>
              <button type="button" data-rich-command="removeFormat">Clear</button>
            </div>
            <div id="pushRichEditor" class="rich-editor-area" contenteditable="true" role="textbox" aria-multiline="true" data-placeholder="Write the notification message..."></div>
          </div>
          <small class="muted rich-editor-help">Supports bold, italic, underline, lists, headings, quotes and links. The formatted message is used for web notifications and email; a clean text version is used for phone push and WhatsApp.</small>
        </label>

        <section class="push-preset-variable-tools" aria-label="Notification variables">
          <div><strong>Insert approved variable</strong><small>Unknown or unresolved variables are rejected before preview or send.</small></div>
          <div id="pushPresetVariableChips" class="push-preset-variable-chips"></div>
        </section>

        <label class="attachment-upload-box">Attachments
          <input id="pushAttachments" name="attachments[]" type="file" multiple accept=".pdf,.png,.jpg,.jpeg,.webp,.gif,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv">
          <small class="muted">Optional. Up to 5 files, 8MB each. Attachments are linked in web notifications and emails; WhatsApp receives attachment links. Phone push opens the matching Pyrk page in the app.</small>
          <div id="pushAttachmentList" class="attachment-list"></div>
        </label>

        <div class="push-message-actions">
          <button class="btn btn-light" type="button" id="previewPushBtnBottom">Preview notification</button>
          <button class="btn" type="button" id="sendPushBtnBottom">Send notification</button>
        </div>

        <p id="pushMsg" class="notice"></p>
      </form>
    </section>

    <aside class="panel push-target-panel">
      <div class="section-head">
        <div>
          <p class="eyebrow">Recipients</p>
          <h2>Audience selector</h2>
          <p class="muted small" id="pushAudienceHint">All active members will receive this notification.</p>
        </div>
      </div>

      <div id="pushWalkSelector" class="push-selector" hidden>
        <div class="inline-controls push-selector-actions">
          <input id="pushWalkSearch" placeholder="Search walks">
        </div>
        <div id="pushWalkList" class="push-recipient-list"></div>
      </div>

      <div id="pushGroupSelector" class="push-selector" hidden>
        <div class="inline-controls push-selector-actions">
          <input id="pushGroupSearch" placeholder="Search teams / groups">
          <button class="btn btn-light btn-small" type="button" id="selectAllPushGroups">Select all</button>
          <button class="btn btn-light btn-small" type="button" id="clearPushGroups">Clear</button>
        </div>
        <div id="pushGroupList" class="push-recipient-list"></div>
      </div>

      <div id="pushMemberSelector" class="push-selector" hidden>
        <div class="inline-controls push-selector-actions">
          <input id="pushMemberSearch" placeholder="Search member name, email, mobile">
          <button class="btn btn-light btn-small" type="button" id="selectAllPushMembers">Select all</button>
          <button class="btn btn-light btn-small" type="button" id="clearPushMembers">Clear</button>
        </div>
        <div id="pushMemberList" class="push-recipient-list"></div>
      </div>

      <div id="pushPreviewBox" class="push-preview-box">
        <strong>Preview recipients before sending.</strong>
        <span class="muted">The preview will show the total number, email-ready count, and sample recipients.</span>
      </div>
    </aside>
  </section>

  <section class="panel">
    <div class="section-head">
      <div>
        <p class="eyebrow">History</p>
        <h2>Recent manual notifications</h2>
      </div>
    </div>
    <div class="push-history-filters" id="pushHistoryFilters">
      <input id="pushHistorySearch" placeholder="Search subject, message, sender or walk">
      <select id="pushHistoryChannel">
        <option value="">All delivery channels</option>
        <option value="web">Web notification</option>
        <option value="email">Email</option>
        <option value="whatsapp">WhatsApp</option>
        <option value="native">Phone push</option>
      </select>
      <select id="pushHistoryAudience">
        <option value="">All audiences</option>
        <option value="all_members">All members</option>
        <option value="selected_groups">Selected groups</option>
        <option value="selected_members">Selected members</option>
        <option value="walk_registrants">Walk registrants</option>
      </select>
      <select id="pushHistoryWalk"><option value="">All walks</option></select>
      <input id="pushHistoryFrom" type="date" title="From date">
      <input id="pushHistoryTo" type="date" title="To date">
      <button class="btn btn-light btn-small" type="button" id="refreshPushHistory">Refresh</button>
    </div>

    <div id="pushHistoryDetail" class="push-history-detail" hidden></div>

    <div class="table-wrap">
      <table class="pro-table push-history-table">
        <thead>
          <tr><th>Notification</th><th>Walk</th><th>Audience</th><th>Delivery</th><th>Recipients</th><th>Results</th><th>Sent by</th><th>Time</th><th></th></tr>
        </thead>
        <tbody id="pushHistoryBody"></tbody>
      </table>
    </div>
  </section>
</main>

<script>
window.PYRK_API_BASE='../../api';
window.PYRK_CSRF='<?= htmlspecialchars($csrf) ?>';
</script>
<script src="../assets/js/api.js"></script>
<script src="../assets/js/admin_manual_notifications.js?v=push-presets-pro-v1"></script>
</body>
</html>
