<?php
$walkAdminListMode = $walkAdminListMode ?? 'upcoming';
if ($walkAdminListMode === 'finished') $walkAdminListMode = 'closed'; // Backward-compatible legacy page.
$walkAdminListMode = in_array($walkAdminListMode, ['upcoming', 'open', 'closed', 'archived'], true) ? $walkAdminListMode : 'upcoming';
$showWalkScheduleForm = in_array($walkAdminListMode, ['upcoming', 'open'], true);
require __DIR__ . '/../_boot.php';
require __DIR__ . '/../partials/nav.php';
$canCreateWalks = $user && (\App\Core\Auth::hasPermission('walks.create', $user) || \App\Core\Auth::hasPermission('walks.manage', $user));
$canEditWalks = $user && (\App\Core\Auth::hasPermission('walks.edit', $user) || \App\Core\Auth::hasPermission('walks.manage', $user));
$canAssignWalkStaff = $user && (\App\Core\Auth::hasPermission('walks.assign_staff', $user) || \App\Core\Auth::hasPermission('walks.manage', $user));
$canViewAllWalks = $user && (\App\Core\Auth::hasPermission('walks.view_all', $user) || \App\Core\Auth::hasPermission('walks.manage', $user));
$canViewAssignedWalks = $user && (\App\Core\Auth::hasPermission('walks.view_assigned', $user) || $canViewAllWalks);
$canDeleteWalks = $user && \App\Core\Auth::hasPermission('walks.delete', $user);
$canUnregisterWalkMembers = $user && (\App\Core\Auth::hasPermission('walks.unregister', $user) || \App\Core\Auth::hasPermission('walks.manage', $user));
$canViewWalkRegistrants = $user && ($canCreateWalks || $canEditWalks || $canDeleteWalks || $canUnregisterWalkMembers || \App\Core\Auth::hasPermission('attendance.manage', $user));
$canManageWalkPhotos = $user && in_array((string)($user['role_name'] ?? ''), ['super_admin', 'event_manager'], true);
$hasAssignedWalks = false;
$hasCreatedOwnWalks = false;
if ($user) {
    try {
        $pdo = \App\Core\Database::connection();
        $tableCheck = $pdo->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'walk_staff_assignments'")->fetchColumn();
        if ((int)$tableCheck > 0) {
            $assignedStmt = $pdo->prepare('SELECT COUNT(*) FROM walk_staff_assignments WHERE user_id = ?');
            $assignedStmt->execute([(int)$user['id']]);
            $hasAssignedWalks = (int)$assignedStmt->fetchColumn() > 0;
        }
        $createdStmt = $pdo->prepare('SELECT COUNT(*) FROM walks WHERE created_by = ?');
        $createdStmt->execute([(int)$user['id']]);
        $hasCreatedOwnWalks = (int)$createdStmt->fetchColumn() > 0;
    } catch (Throwable $e) {
        $hasAssignedWalks = false;
$hasCreatedOwnWalks = false;
    }
}
$canViewWalkRegistrants = $canViewWalkRegistrants || $canViewAssignedWalks || $hasAssignedWalks || $hasCreatedOwnWalks;
if (!$user || (!$canCreateWalks && !$canEditWalks && !$canDeleteWalks && !$canViewWalkRegistrants && !$canViewAssignedWalks && !$hasAssignedWalks && !$hasCreatedOwnWalks)) { header('Location: dashboard.php'); exit; }

$walkWhatsAppConfig = (array)(($GLOBALS['config']['whatsapp'] ?? null) ?: []);
$walkWhatsAppDriver = strtolower((string)($walkWhatsAppConfig['driver'] ?? $walkWhatsAppConfig['provider'] ?? ''));
$walkUltraMsgConfig = (array)($walkWhatsAppConfig['ultramsg'] ?? []);
$walkWhatsAppConfigured = !empty($walkWhatsAppConfig['enabled'])
    && $walkWhatsAppDriver === 'ultramsg'
    && trim((string)($walkUltraMsgConfig['instance_id'] ?? '')) !== '';
$walkWhatsAppMaxBatch = max(1, (int)($walkUltraMsgConfig['max_per_batch'] ?? 50));
$walkWhatsAppDailyLimit = max(1, (int)($walkUltraMsgConfig['max_per_day'] ?? 100));
$walkWhatsAppPerRun = max(1, (int)($walkUltraMsgConfig['messages_per_run'] ?? 5));

$walkAdminPageTitles = [
    'upcoming' => ['eyebrow' => 'Events', 'title' => 'Upcoming walks', 'subtitle' => 'Create future walks, manage invitations, and monitor registrations. Upcoming open walks also remain visible in Open.'],
    'open' => ['eyebrow' => 'Live operations', 'title' => 'Open walks', 'subtitle' => 'All walks still marked Open, including upcoming, today, and overdue walks awaiting closure.'],
    'closed' => ['eyebrow' => 'Events records', 'title' => 'Closed walks', 'subtitle' => 'Walks marked Closed or Completed are kept here as operational records.'],
    'archived' => ['eyebrow' => 'Events archive', 'title' => 'Archived walks', 'subtitle' => 'Review archived walks kept safely for records. Restore them when needed.'],
];
$walkAdminPage = $walkAdminPageTitles[$walkAdminListMode] ?? $walkAdminPageTitles['upcoming'];
$walkListHeading = $walkAdminPage['title'];
$walkListHelp = $walkAdminListMode === 'archived'
    ? 'Archived walks are hidden from the member portal and active admin schedule.'
    : ($walkAdminListMode === 'closed'
        ? 'Only walks explicitly marked Closed or Completed appear here.'
        : ($walkAdminListMode === 'open'
            ? 'A walk stays here regardless of date until its status is changed to Closed or Completed.'
            : 'Future walks appear here. Walks with status Open also appear in the Open section.'));
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Walks | Pyrk Admin</title>
  <link rel="stylesheet" href="../assets/css/app.css">
  <link rel="stylesheet" href="../assets/css/permissions_delete_actions.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_checkin_policy.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_edit_pro.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_invites_pro.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_bulk_invites_pro.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_group_smart_picker.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_buttons_pro_fix.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_unregister_pro.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_payment_model.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_archive_pro.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_notifications_pro.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_walk_whatsapp_notify.css?v=6-channel-presets-separated">
  <link rel="stylesheet" href="../assets/css/admin_walk_team_assignments.css?v=25-assigned-walkers-layout">
  <link rel="stylesheet" href="../assets/css/admin_walk_sections_pro.css?v=2-assigned-walkers-layout">
  <link rel="stylesheet" href="../assets/css/admin_walk_duplicate_pro.css?v=1">
</head>
<body>
<?php pyrk_render_nav('admin'); ?>
<main class="container enterprise-page admin-walks-container">
  <section class="page-hero admin-hero enterprise-hero">
    <div>
      <p class="eyebrow"><?= htmlspecialchars($walkAdminPage['eyebrow']) ?></p>
      <h1><?= htmlspecialchars($walkAdminPage['title']) ?></h1>
      <p class="muted"><?= htmlspecialchars($walkAdminPage['subtitle']) ?></p>
    </div>
    <div class="hero-actions walk-section-links"><a class="btn <?= $walkAdminListMode === 'upcoming' ? '' : 'btn-light' ?>" href="walks.php">Upcoming</a><a class="btn <?= $walkAdminListMode === 'open' ? '' : 'btn-light' ?>" href="walks_open.php">Open</a><a class="btn <?= $walkAdminListMode === 'closed' ? '' : 'btn-light' ?>" href="walks_closed.php">Closed</a><a class="btn <?= $walkAdminListMode === 'archived' ? '' : 'btn-light' ?>" href="walks_archived.php">Archived</a><a class="btn btn-light" href="groups.php">Manage groups</a><a class="btn" href="attendance.php">Open attendance</a></div>
  </section>

  <section class="<?= $showWalkScheduleForm ? 'grid two walks-admin-grid' : 'walks-admin-single' ?>">
    <?php if ($showWalkScheduleForm): ?>
    <div class="panel schedule-panel">
      <div class="section-head">
        <div>
          <p class="eyebrow" id="walkFormEyebrow">Create</p>
          <h2 id="walkFormTitle">Schedule walk</h2>
        </div>
      </div>
      <?php if ($canCreateWalks || $canEditWalks): ?>
      <form id="walkForm" class="stack-form">
        <input type="hidden" name="id" id="walkId" value="">
        <label class="route-search-field">Route
          <input type="hidden" name="route_id" id="routeSelect" value="">
          <input type="text" id="routeSearchInput" autocomplete="off" placeholder="Type route name, KM, difficulty..." required>
          <div id="routeSearchResults" class="pro-search-dropdown" hidden></div>
        </label>
        <label>Walk title<input name="title" placeholder="Walk title" required></label>
        <label>Description<textarea name="description" placeholder="Description"></textarea></label>
        <div class="form-grid two">
          <label>Date<input name="walk_date" id="walkDateInput" type="text" inputmode="numeric" placeholder="dd/mm/yyyy" autocomplete="off" required><small class="field-hint">Always dd/mm/yyyy. Click field to open calendar.</small></label>
          <label>Start time<input name="start_time" type="time" required></label>
          <label>Expected finish<input name="expected_finish_time" type="time" required></label>
          <label>Capacity<input name="capacity" type="number" placeholder="Capacity" value="100"></label>
          <label>Registration deadline<input name="registration_deadline" id="registrationDeadlineInput" type="text" inputmode="numeric" placeholder="dd/mm/yyyy hh:mm" autocomplete="off"><small class="field-hint">Always dd/mm/yyyy hh:mm. Click field to open calendar.</small></label>
          <label>Voting deadline<input name="voting_deadline" id="votingDeadlineInput" type="text" inputmode="numeric" placeholder="dd/mm/yyyy hh:mm" autocomplete="off"><small class="field-hint">Always dd/mm/yyyy hh:mm. Click field to open calendar.</small></label>
          <label>Status<select name="status"><option value="open">Open</option><option value="draft">Draft</option><option value="closed">Closed</option><option value="completed">Completed</option></select></label>
          <label>Access<select name="access_type" id="walkAccessType"><option value="open">Open registration</option><option value="invitation_only">Invitation only</option></select></label>
        </div>


        <section class="walk-payment-card" id="walkPaymentCard">
          <div>
            <p class="eyebrow">Payment model</p>
            <h3>Walk fee</h3>
            <p class="muted small">Choose whether this walk is free or paid. Pyrk records the amount for members and accounting.</p>
          </div>
          <div class="form-grid three payment-grid">
            <label>Model
              <select name="payment_model" id="walkPaymentModel">
                <option value="free">Free walk</option>
                <option value="paid">Paid walk</option>
              </select>
            </label>
            <label>Amount
              <input name="payment_amount" id="walkPaymentAmount" type="number" step="0.01" min="0" value="0">
            </label>
            <label>Currency
              <select name="payment_currency" id="walkPaymentCurrency">
                <option value="LBP">LBP</option>
                <option value="USD">USD</option>
                <option value="EUR">EUR</option>
              </select>
            </label>
          </div>
          <p class="payment-preview" id="walkPaymentPreview">Free walk</p>
        </section>

        <section class="walk-permission-card">
          <div>
            <p class="eyebrow">Check-in permission</p>
            <h3>Member self check-in</h3>
            <p class="muted small">Default is OFF. When OFF, only admin / walk leader QR or manual check-in is allowed.</p>
          </div>
          <label class="pro-switch">
            <input type="checkbox" name="allow_self_checkin" id="createAllowSelfCheckin" value="1">
            <span><b></b></span>
            <strong>Allow self check-in for this walk</strong>
          </label>
        </section>
        <div class="invite-builder enterprise-invite-builder" id="createInviteBuilder">
          <div class="invite-builder-head">
            <div><strong>Invitations</strong><span>Use live searchable dropdowns to choose specific members or groups for invitation-only walks.</span></div>
            <input id="createInviteCountPreview" readonly value="0 selected" class="invite-count-field">
          </div>
          <label>Invite note<textarea name="invite_note" placeholder="Optional note shown internally for this invite list"></textarea></label>
          <section class="invite-delivery-card">
            <div>
              <p class="eyebrow">Delivery</p>
              <h3>Email invitations</h3>
              <p class="muted small">When you add members or groups, send the invitation email only to the newly added invitees.</p>
            </div>
            <label class="check invite-send-check"><input type="checkbox" name="notify_new_invitees" id="createNotifyNewInvitees" value="1" checked> Send email to newly invited members</label>
          </section>
          <section class="walk-notification-card-pro" id="walkNotificationCard">
            <div class="walk-notification-head-pro">
              <div>
                <p class="eyebrow">General notification</p>
                <h3>Notify members after saving this walk</h3>
                <p class="muted small">Choose who should receive this optional notification. Email invitations remain separate.</p>
              </div>
              <label class="pro-switch compact-switch">
                <input type="checkbox" name="walk_notify_enabled" id="walkNotifyEnabled" value="1">
                <span><b></b></span>
                <strong>Send notification</strong>
              </label>
            </div>
            <div class="walk-notification-fields-pro" id="walkNotificationFields" hidden>
              <div class="walk-preset-picker-pro">
                <label>Push notification preset
                  <select id="walkNotifyPreset">
                    <option value="">Loading Push presets…</option>
                  </select>
                  <input type="hidden" name="walk_notify_push_preset_id" id="walkNotifyPresetId" value="">
                </label>
                <div class="walk-preset-picker-actions">
                  <button class="btn btn-light btn-small" type="button" id="walkNotifyApplyPreset">Apply Push preset</button>
                  <a class="btn btn-light btn-small" href="push_notification_presets.php">Manage Push presets</a>
                </div>
                <small id="walkNotifyPresetHelp">Choose a saved Push preset or keep editing the message manually. WhatsApp presets remain separate.</small>
              </div>
              <div class="form-grid two">
                <label>Notification recipients
                  <select name="walk_notify_audience" id="walkNotifyAudience">
                    <option value="" selected disabled>Choose notification recipients</option>
                    <option value="all">All active members</option>
                    <option value="invited">Invited members only</option>
                  </select>
                </label>
                <label>Subject
                  <input name="walk_notify_subject" id="walkNotifySubject" maxlength="180" placeholder="New walk is open">
                </label>
              </div>
              <label>Message
                <textarea name="walk_notify_message" id="walkNotifyMessage" rows="12" placeholder="Write the message members will see in their notification center"></textarea>
              </label>

              <section class="walk-notification-template-tools" aria-labelledby="walkNotificationVariablesTitle">
                <div class="walk-notification-template-head">
                  <div>
                    <p class="eyebrow">Personalization</p>
                    <h4 id="walkNotificationVariablesTitle">Member and walk variables</h4>
                    <p>Click a variable to insert it at the cursor. Pyrk replaces it separately for every recipient after the walk is saved.</p>
                  </div>
                  <button class="btn btn-light btn-small" type="button" id="walkNotifyUseProTemplate">Restore selected preset</button>
                </div>
                <div class="walk-notification-variable-chips" role="group" aria-label="Notification variables">
                  <button type="button" data-walk-notify-token="{first_name}" title="Recipient first name">First name</button>
                  <button type="button" data-walk-notify-token="{last_name}" title="Recipient last name">Last name</button>
                  <button type="button" data-walk-notify-token="{full_name}" title="Recipient full name">Full name</button>
                  <button type="button" data-walk-notify-token="{walk_title}" title="Current walk title">Walk title</button>
                  <button type="button" data-walk-notify-token="{walk_date}" title="Current walk date">Walk date</button>
                  <button type="button" data-walk-notify-token="{walk_time}" title="Current walk start time">Walk time</button>
                  <button type="button" data-walk-notify-token="{route_name}" title="Selected route name">Route</button>
                  <button type="button" data-walk-notify-token="{distance_km}" title="Selected route distance">Distance</button>
                  <button type="button" data-walk-notify-token="{walk_link}" title="Direct link to this walk">Walk link</button>
                </div>
                <p class="walk-notification-variable-note"><strong>{walk_link}</strong> is resolved after saving and always opens the current walk. The professional message already includes it.</p>
              </section>

              <section class="walk-whatsapp-create-card <?= $walkWhatsAppConfigured ? 'is-ready' : 'is-disabled' ?>" id="walkWhatsAppCreateCard">
                <div class="walk-whatsapp-create-copy">
                  <div class="walk-whatsapp-create-icon" aria-hidden="true">◉</div>
                  <div>
                    <div class="walk-whatsapp-create-title-row">
                      <h4>WhatsApp via UltraMsg</h4>
                      <span class="walk-whatsapp-status <?= $walkWhatsAppConfigured ? 'ready' : 'setup' ?>"><?= $walkWhatsAppConfigured ? 'Configured' : 'Setup required' ?></span>
                    </div>
                    <p id="walkWhatsAppCreateDescription">Queue a separate WhatsApp preset after saving the walk. It is not blasted instantly: the cron sends a controlled batch gradually.</p>
                    <div class="walk-whatsapp-safety-badges">
                      <span>Max <?= (int)$walkWhatsAppMaxBatch ?> per walk</span>
                      <span><?= (int)$walkWhatsAppDailyLimit ?> per day</span>
                      <span><?= (int)$walkWhatsAppPerRun ?> per cron run</span>
                    </div>
                  </div>
                </div>
                <label class="walk-whatsapp-create-toggle">
                  <input type="checkbox" name="walk_notify_whatsapp" id="walkNotifyWhatsApp" value="1" data-configured="<?= $walkWhatsAppConfigured ? '1' : '0' ?>" <?= $walkWhatsAppConfigured ? '' : 'disabled' ?>>
                  <span id="walkNotifyWhatsAppLabel">Also send by WhatsApp</span>
                </label>
                <div class="walk-whatsapp-preset-picker" id="walkWhatsAppPresetPicker">
                  <label>WhatsApp message preset
                    <select id="walkNotifyWhatsAppPreset">
                      <option value="">Loading WhatsApp presets…</option>
                    </select>
                    <input type="hidden" name="walk_notify_whatsapp_preset_id" id="walkNotifyWhatsAppPresetId" value="">
                  </label>
                  <a class="btn btn-light btn-small" href="whatsapp_presets.php">Manage WhatsApp presets</a>
                  <small id="walkNotifyWhatsAppPresetHelp">WhatsApp uses its own preset library and remains separate from Push notifications.</small>
                </div>
                <p class="walk-whatsapp-create-note" id="walkWhatsAppCreateNote"><?= $walkWhatsAppConfigured ? 'Available for new walks. Draft walks are never sent.' : 'Complete the UltraMsg instance/token setup before enabling this option.' ?></p>
                <label class="walk-whatsapp-repeat-override" id="walkWhatsAppRepeatOverride" hidden>
                  <input type="checkbox" name="walk_notify_whatsapp_repeat" id="walkNotifyWhatsAppRepeat" value="1">
                  <span><strong>Send another update anyway</strong><small>Use only when a second WhatsApp broadcast within 60 minutes is intentional.</small></span>
                </label>
              </section>

              <p class="muted small" id="walkNotifyHint">Choose exactly who should receive this notification.</p>
            </div>
          </section>
          <div class="grid two invite-modal-grid create-invite-grid">
            <div>
              <div class="section-head mini-head"><div><p class="eyebrow">Groups</p><h3>Invite groups</h3></div></div>
              <input id="createInviteGroupSearch" placeholder="Search and select groups" class="full-input pro-typeahead-input">
              <div id="createInviteGroupsList" class="invite-check-list invite-check-list-compact"></div>
            </div>
            <div>
              <div class="section-head mini-head"><div><p class="eyebrow">Members</p><h3>Invite members</h3></div></div>
              <div class="invite-bulk-actions">
                <button class="btn btn-small" type="button" data-invite-bulk="create" data-bulk-action="all-members">Invite all active members</button>
                <button class="btn btn-light btn-small" type="button" data-invite-bulk="create" data-bulk-action="clear-members">Clear members</button>
              </div>
              <input id="createInviteMemberSearch" placeholder="Search and select members" class="full-input pro-typeahead-input">
              <div id="createInviteMembersList" class="invite-check-list invite-check-list-compact"></div>
            </div>
          </div>
          <div id="createGroupMemberAssistant" class="group-member-assistant"></div>
          <p class="muted small">Professional invite lists: type to search, select results from the dropdown, review selected chips, then save the walk.</p>
        </div>
        <label class="check"><input type="checkbox" name="waiver_required" checked> Waiver required</label>
        <div class="inline-controls walk-edit-actions"><button class="btn" type="submit" id="saveWalkBtn">Create walk</button><button class="btn btn-light" type="button" id="cancelWalkEditBtn" hidden>Cancel edit</button></div>
        <p id="walkMsg" class="notice"></p>
      </form>
      <?php else: ?><div class="notice bad">You can view walks but do not have permission to create or edit walks.</div><?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="panel walks-list-panel <?= !$showWalkScheduleForm ? 'walks-list-panel-wide' : '' ?>">
      <div class="section-head">
        <div>
          <p class="eyebrow"><?= in_array($walkAdminListMode, ['upcoming', 'open'], true) ? 'Registered attendees' : 'Records' ?></p>
          <h2><?= htmlspecialchars($walkListHeading) ?></h2>
          <p class="muted small"><?= htmlspecialchars($walkListHelp) ?></p>
        </div>
        <div class="inline-controls search-controls walk-archive-toolbar">
          <div class="segmented-tabs walk-archive-tabs walk-section-tabs" aria-label="Walk list sections">
            <a class="segmented-tab <?= $walkAdminListMode === 'upcoming' ? 'active' : '' ?>" href="walks.php">Upcoming</a>
            <a class="segmented-tab <?= $walkAdminListMode === 'open' ? 'active' : '' ?>" href="walks_open.php">Open</a>
            <a class="segmented-tab <?= $walkAdminListMode === 'closed' ? 'active' : '' ?>" href="walks_closed.php">Closed</a>
            <a class="segmented-tab <?= $walkAdminListMode === 'archived' ? 'active' : '' ?>" href="walks_archived.php">Archived</a>
          </div>
          <input id="walkSearch" placeholder="Search walk or route">
        </div>
      </div>
      <div id="walkArchiveNotice" class="notice archive-notice" hidden></div>
      <div id="walksList" class="walk-admin-list"></div>
    </div>
  </section>
</main>

<div class="modal-backdrop" id="walkRegistrantsModal" hidden>
  <div class="modal-card modal-large walk-registrants-modal" role="dialog" aria-modal="true" aria-labelledby="registrantsTitle">
    <div class="modal-head">
      <div>
        <p class="eyebrow">Walk registrations</p>
        <h2 id="registrantsTitle">Registered members</h2>
        <p id="registrantsSubTitle" class="muted small"></p>
      </div>
      <button class="icon-btn" type="button" data-close-modal="walkRegistrantsModal">×</button>
    </div>
    <div class="grid four compact-stats registrant-stats">
      <div class="stat stat-pro"><span>Registered</span><strong id="regTotal">0</strong></div>
      <div class="stat stat-pro"><span>Checked in</span><strong id="regCheckedIn">0</strong></div>
      <div class="stat stat-pro"><span>Finished</span><strong id="regFinished">0</strong></div>
      <div class="stat stat-pro"><span>Route KM</span><strong id="regKm">0</strong></div>
    </div>
    <div class="table-wrap pro-table-wrap crm-table-wrap">
      <table class="pro-table registrants-table">
        <thead><tr><th>Member</th><th>Mobile</th><th>Emergency</th><th>Registration</th><th>Waiver</th><th>Attendance</th><th>Check-in</th><th>Finish</th></tr></thead>
        <tbody id="registrantsTableBody"></tbody>
      </table>
    </div>
  </div>
</div>



<div class="modal-backdrop walk-duplicate-backdrop" id="walkDuplicateModal" hidden>
  <div class="modal-card walk-duplicate-modal" role="dialog" aria-modal="true" aria-labelledby="walkDuplicateTitle">
    <div class="modal-head">
      <div>
        <p class="eyebrow">Safe walk copy</p>
        <h2 id="walkDuplicateTitle">Duplicate walk</h2>
        <p class="muted">Reuse the walk setup for a new date without touching the original event.</p>
      </div>
      <button class="icon-btn" id="closeWalkDuplicateBtn" type="button" aria-label="Close duplicate walk dialog">×</button>
    </div>

    <form id="walkDuplicateForm" class="stack-form">
      <input type="hidden" id="walkDuplicateSourceId" value="">

      <div class="walk-duplicate-source-card">
        <span class="walk-duplicate-icon" aria-hidden="true">⧉</span>
        <div>
          <small>Copying from</small>
          <strong id="walkDuplicateSourceName">Walk</strong>
          <span id="walkDuplicateSourceMeta">Route and scheduling details will be copied.</span>
        </div>
      </div>

      <div class="form-grid two walk-duplicate-main-fields">
        <label>New walk title
          <input id="walkDuplicateName" maxlength="180" autocomplete="off" required>
        </label>
        <label>New walk date
          <input id="walkDuplicateDate" type="date" required>
        </label>
      </div>

      <div class="form-grid three walk-duplicate-time-fields">
        <label>Start time
          <input id="walkDuplicateStartTime" type="time" required>
        </label>
        <label>Expected finish
          <input id="walkDuplicateFinishTime" type="time" required>
        </label>
        <label>New status
          <select id="walkDuplicateStatus">
            <option value="draft">Draft — review first</option>
            <option value="open">Open for registration</option>
          </select>
        </label>
      </div>

      <div class="walk-duplicate-copy-options">
        <label class="walk-duplicate-option">
          <input id="walkDuplicateCopyDeadlines" type="checkbox" checked>
          <span><strong>Keep relative deadlines</strong><small>Registration and voting deadlines move by the same interval to the new date.</small></span>
        </label>
        <label class="walk-duplicate-option">
          <input id="walkDuplicateCopyTeam" type="checkbox" checked>
          <span><strong>Copy assigned team</strong><small id="walkDuplicateTeamHint">Manager, head walker, and walkers can be copied.</small></span>
        </label>
        <label class="walk-duplicate-option">
          <input id="walkDuplicateCopyInvitations" type="checkbox">
          <span><strong>Copy invitation list</strong><small id="walkDuplicateInviteHint">Optional. Invitation emails will not be sent automatically.</small></span>
        </label>
      </div>

      <div class="walk-duplicate-safety-grid">
        <div><strong>Setup copied</strong><span>Route, description, capacity, access, waiver, self check-in, and fee settings.</span></div>
        <div><strong>Fresh operations</strong><span>No registrants, attendance, check-ins, payments, waivers, photos, or voting results.</span></div>
        <div><strong>No notifications</strong><span>The duplicate is created silently. Review it before notifying or inviting members.</span></div>
      </div>

      <p id="walkDuplicateMsg" class="notice" hidden></p>
      <div class="modal-actions">
        <button class="btn btn-light" id="cancelWalkDuplicateBtn" type="button">Cancel</button>
        <button class="btn" id="confirmWalkDuplicateBtn" type="submit">Duplicate &amp; review</button>
      </div>
    </form>
  </div>
</div>


<div class="modal-backdrop" id="walkInvitationsModal" hidden>
  <div class="modal-card modal-large walk-invites-modal" role="dialog" aria-modal="true" aria-labelledby="invitationsTitle">
    <div class="modal-head">
      <div>
        <p class="eyebrow">Walk access</p>
        <h2 id="invitationsTitle">Manage invitations</h2>
        <p id="invitationsSubTitle" class="muted small"></p>
      </div>
      <button class="icon-btn" type="button" data-close-modal="walkInvitationsModal">×</button>
    </div>
    <form id="walkInvitationsForm" class="stack-form">
      <input type="hidden" name="walk_id" id="inviteWalkId">
      <div class="form-grid two">
        <label>Access type<select name="access_type" id="inviteAccessType"><option value="open">Open registration</option><option value="invitation_only">Invitation only</option></select></label>
        <label>Current invitations<input id="inviteCountPreview" readonly value="0 selected"></label>
      </div>

      <section class="walk-permission-card compact">
        <div>
          <p class="eyebrow">Per-walk permission</p>
          <h3>Member self check-in</h3>
          <p class="muted small">Turn on only when you want members to check themselves in from the client portal.</p>
        </div>
        <label class="pro-switch">
          <input type="checkbox" id="inviteAllowSelfCheckin" value="1">
          <span><b></b></span>
          <strong>Allow self check-in</strong>
        </label>
      </section>
      <label>Invite note<textarea name="invite_note" id="inviteNote" placeholder="Internal note about who should join this walk"></textarea></label>
      <section class="invite-delivery-card compact">
        <div>
          <p class="eyebrow">Delivery</p>
          <h3>Send invitation email</h3>
          <p class="muted small">Only newly added members receive email. Existing invitees are not emailed again.</p>
        </div>
        <label class="check invite-send-check"><input type="checkbox" id="modalNotifyNewInvitees" value="1" checked> Email newly invited members now</label>
      </section>
      <div class="grid two invite-modal-grid">
        <div>
          <div class="section-head mini-head"><div><p class="eyebrow">Groups</p><h3>Invite member groups</h3></div></div>
          <input id="inviteGroupSearch" placeholder="Search and select groups" class="full-input pro-typeahead-input">
          <div id="inviteGroupsList" class="invite-check-list"></div>
        </div>
        <div>
          <div class="section-head mini-head"><div><p class="eyebrow">Members</p><h3>Invite specific members</h3></div></div>
          <div class="invite-bulk-actions">
            <button class="btn btn-small" type="button" data-invite-bulk="modal" data-bulk-action="all-members">Invite all active members</button>
            <button class="btn btn-light btn-small" type="button" data-invite-bulk="modal" data-bulk-action="clear-members">Clear members</button>
          </div>
          <input id="inviteMemberSearch" placeholder="Search and select members" class="full-input pro-typeahead-input">
          <div id="inviteMembersList" class="invite-check-list"></div>
        </div>
      </div>
      <div id="modalGroupMemberAssistant" class="group-member-assistant"></div>
      <div class="modal-actions">
        <button class="btn btn-light" type="button" data-close-modal="walkInvitationsModal">Cancel</button>
        <button class="btn" type="submit">Save invitations</button>
      </div>
      <p id="inviteMsg" class="notice"></p>
    </form>
  </div>
</div>


<script>window.PYRK_API_BASE='../../api'; window.PYRK_CSRF='<?= htmlspecialchars($csrf) ?>'; window.PYRK_WALK_LIST_MODE='<?= htmlspecialchars($walkAdminListMode) ?>'; window.PYRK_PUBLIC_BASE='../'; window.PYRK_CAN_CREATE_WALKS=<?= $canCreateWalks ? 'true' : 'false' ?>; window.PYRK_CAN_EDIT_WALKS=<?= $canEditWalks ? 'true' : 'false' ?>; window.PYRK_CAN_DELETE_WALKS=<?= $canDeleteWalks ? 'true' : 'false' ?>; window.PYRK_CAN_VIEW_WALK_REGISTRANTS=<?= $canViewWalkRegistrants ? 'true' : 'false' ?>; window.PYRK_CAN_ASSIGN_WALK_STAFF=<?= $canAssignWalkStaff ? 'true' : 'false' ?>; window.PYRK_CAN_VIEW_ALL_WALKS=<?= $canViewAllWalks ? 'true' : 'false' ?>; window.PYRK_CAN_VIEW_ASSIGNED_WALKS=<?= $canViewAssignedWalks ? 'true' : 'false' ?>; window.PYRK_HAS_ASSIGNED_WALKS=<?= $hasAssignedWalks ? 'true' : 'false' ?>; window.PYRK_CAN_UNREGISTER_WALK_MEMBERS=<?= $canUnregisterWalkMembers ? 'true' : 'false' ?>; window.PYRK_CAN_MANAGE_WALK_PHOTOS=<?= $canManageWalkPhotos ? 'true' : 'false' ?>;</script>
<script src="../assets/js/api.js"></script>
<script src="../assets/js/admin_walks.js?v=38-walk-sections"></script>
<script src="../assets/js/admin_walk_duplicate_pro.js?v=1"></script>
</body>
</html>
