<?php
require __DIR__ . '/../_boot.php';
require __DIR__ . '/../partials/nav.php';
$canView = $user && (\App\Core\Auth::hasPermission('members.view', $user) || \App\Core\Auth::hasPermission('members.manage', $user) || \App\Core\Auth::hasPermission('members.delete', $user));
$canEdit = $user && \App\Core\Auth::hasPermission('members.manage', $user);
$canDeleteMembers = $user && \App\Core\Auth::hasPermission('members.delete', $user);
$canManageUserPrivileges = $user && (\App\Core\Auth::hasPermission('users.manage', $user) || (($user['role_name'] ?? '') === 'super_admin'));
if (!$user || !$canView) { 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>Members CRM | Pyrk Admin</title>
  <link rel="stylesheet" href="../assets/css/app.css">
  <link rel="stylesheet" href="../assets/css/admin_member_system_link.css?v=member-user-privileges-v1">
  <link rel="stylesheet" href="../assets/css/permissions_delete_actions.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_members_form_pro.css?v=3">
  <link rel="stylesheet" href="../assets/css/admin_members_bulk_status_pro.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_member_waivers_profile.css?v=1">
</head>
<body>
<?php pyrk_render_nav('admin'); ?>
<main class="container enterprise-page member-crm-container">
  <section class="page-hero admin-hero dashboard-hero enterprise-hero">
    <div>
      <p class="eyebrow">Client CRM</p>
      <h1>Members</h1>
      <p class="muted">Manage walking-club clients, emergency data, medical notes, activity, routes attended, photos, loyalty and badges.</p>
    </div>
    <div class="hero-actions">
      <?php if ($canEdit): ?><button class="btn" type="button" id="openNewMemberModal">+ Add new member</button><?php endif; ?>
      <?php if ($user['role_name'] === 'super_admin'): ?><a class="btn btn-light" href="security.php">Security center</a><a class="btn btn-light" href="users.php">System users</a><?php endif; ?>
    </div>
  </section>

  <section class="grid four compact-stats" id="memberStats">
    <div class="stat stat-pro"><span>Total members</span><strong id="totalMembers">0</strong></div>
    <div class="stat stat-pro"><span>Active members</span><strong id="totalActiveMembers">0</strong></div>
    <div class="stat stat-pro"><span>Total KM</span><strong id="totalMemberKm">0</strong></div>
    <div class="stat stat-pro"><span>Loyalty points</span><strong id="totalMemberPoints">0</strong></div>
  </section>

  <section class="panel enterprise-table-panel crm-wide-panel">
    <div class="section-head crm-section-head">
      <div>
        <p class="eyebrow">Directory</p>
        <h2>Club members</h2>
        <p class="muted small">Click a member row or the Profile button to see routes, walks, photos and badges.</p>
      </div>
      <div class="inline-controls search-controls">
        <input id="memberSearch" placeholder="Search name, email, mobile, emergency">
        <select id="memberStatusFilter"><option value="">All status</option><option value="active">Active</option><option value="inactive">Inactive</option><option value="blocked">Blocked</option></select>
        <select id="memberViewMode"><option value="table">Table view</option><option value="cards">Card view</option></select>
        <?php if ($canEdit): ?><button class="btn btn-small" type="button" id="openNewMemberModalSmall">Add member</button><?php endif; ?>
      </div>
    </div>

    <?php if ($canEdit): ?>
    <div class="member-bulk-status-bar" id="memberBulkStatusBar">
      <div class="member-bulk-status-main">
        <label class="member-bulk-check">
          <input type="checkbox" id="memberBulkSelectShown">
          <span>Select shown inactive members</span>
        </label>
        <span class="member-bulk-counter" id="memberBulkCounter">0 selected</span>
      </div>
      <div class="member-bulk-actions">
        <button class="btn btn-light btn-small" type="button" id="memberBulkSelectInactive">Select inactive</button>
        <button class="btn btn-small" type="button" id="memberBulkActivate" disabled>Activate selected</button>
      </div>
      <p class="muted small member-bulk-help">Bulk action only changes inactive members to active. Blocked members are never unblocked from this tool.</p>
    </div>
    <?php endif; ?>

    <div id="membersTableWrap" class="table-wrap pro-table-wrap crm-table-wrap members-compact-wrap">
      <table class="pro-table members-pro-table">
        <thead>
          <tr>
            <?php if ($canEdit): ?><th class="member-select-head"><span class="sr-only">Select</span></th><?php endif; ?>
            <th>Member</th>
            <th>Contact</th>
            <th>Activity</th>
            <th>Status</th>
            <th class="members-actions-head">Actions</th>
          </tr>
        </thead>
        <tbody id="membersTableBody"></tbody>
      </table>
    </div>
    <div id="membersGrid" class="member-grid enterprise-card-grid" hidden></div>
  </section>
</main>

<?php if ($canEdit): ?>
<div class="modal-backdrop" id="memberFormModal" hidden>
  <div class="modal-card modal-large" role="dialog" aria-modal="true" aria-labelledby="memberFormTitle">
    <div class="modal-head">
      <div>
        <p class="eyebrow">Create / edit</p>
        <h2 id="memberFormTitle">Create member</h2>
      </div>
      <button class="icon-btn" type="button" data-close-modal="memberFormModal">×</button>
    </div>
    <form id="memberForm" class="stack-form" enctype="multipart/form-data">
      <input type="hidden" name="id" id="memberId">
      <div class="profile-upload-box">
        <div class="avatar-preview xl" id="memberAvatarPreview">M</div>
        <label class="upload-trigger">Member picture
          <input name="profile_photo" id="memberProfilePhoto" type="file" accept="image/*">
        </label>
        <small class="muted">Useful for check-in, safety and admin verification.</small>
      </div>

      <?php if ($canManageUserPrivileges): ?>
      <section class="member-system-privileges-card" id="memberSystemPrivilegesCard">
        <div class="privilege-head">
          <div>
            <strong>System / user privileges</strong>
            <span>Use this when this member should also login as Manager, Leader, Admin or another system user.</span>
          </div>
          <label class="pro-switch privilege-switch">
            <input type="checkbox" id="memberSystemAccessEnabled" name="system_access_enabled" value="1">
            <span><b></b></span>
            <em>Enable user privileges</em>
          </label>
        </div>

        <div class="form-grid two privilege-role-row" id="memberSystemRoleRow" hidden>
          <label>System role
            <select name="system_role_id" id="memberSystemRoleId">
              <option value="">Choose role</option>
            </select>
          </label>
          <label>Permission search
            <input id="memberPermissionSearch" type="search" placeholder="Search permission...">
          </label>
        </div>

        <div id="memberPermissionTools" class="member-permission-tools" hidden>
          <button class="btn btn-light btn-small" type="button" id="memberPermissionsRoleDefault">Role default</button>
          <button class="btn btn-light btn-small" type="button" id="memberPermissionsSelectAll">Select all</button>
          <button class="btn btn-light btn-small" type="button" id="memberPermissionsClear">Clear</button>
          <small class="muted" id="memberPermissionsCounter">0 permissions selected</small>
        </div>

        <div id="memberPermissionsList" class="member-permissions-list" hidden></div>
        <small class="muted">This does not link to another user. It upgrades this same member account with system role and permissions.</small>
      </section>
      <?php endif; ?>

<div class="form-grid two member-form-grid-pro">
        <label>First Name<input name="first_name" id="firstName" required placeholder="First Name" autocomplete="given-name"></label>
        <label>Last Name<input name="last_name" id="lastName" required placeholder="Last Name" autocomplete="family-name"></label>
        <input type="hidden" name="full_name" id="fullName">
        <label>Email<input name="email" id="email" type="email" required placeholder="name@example.com"></label>

        <label class="phone-label-pro">Mobile
          <input type="hidden" name="mobile" id="mobile">
          <div class="phone-field-pro phone-select-wrap" data-phone-widget="mobile" data-code="+961" data-name="Lebanon">
            <div class="country-select-pro">
              <button class="country-select-btn" type="button" data-country-button="mobile" aria-haspopup="listbox" aria-expanded="false">
                <span id="mobileCountryLabel">Lebanon +961</span><b>▾</b>
              </button>
              <div class="country-dropdown-pro" data-country-menu="mobile" hidden>
                <input class="country-search-pro" type="search" data-country-search="mobile" placeholder="Search country or code">
                <div class="country-options-pro" data-country-options="mobile" role="listbox"></div>
              </div>
            </div>
            <input id="mobileNumber" class="phone-number-input" inputmode="tel" placeholder="Mobile number">
          </div>
          <small class="muted">Type country name or code, then enter the number.</small>
        </label>

        <label>Status<select name="status" id="status"><option value="active">Active</option><option value="inactive">Inactive</option><option value="blocked">Blocked</option></select></label>

        <label>Self-profile editing<select name="can_edit_own_profile" id="memberCanEditOwnProfile"><option value="1">Allowed on web and mobile</option><option value="0">Disabled on web and mobile</option></select><small class="muted">A user-account control; it does not grant member-management permission.</small></label>

        <label>Date of birth
          <div class="date-field-pro">
            <input name="date_of_birth" id="dateOfBirth" type="text" inputmode="numeric" placeholder="dd/mm/yyyy" pattern="\d{2}/\d{2}/\d{4}">
            <input id="dateOfBirthPicker" class="native-date-pro" type="date" tabindex="-1" aria-hidden="true">
            <button class="field-icon-btn" type="button" id="dateOfBirthCalendarBtn" aria-label="Open calendar" title="Open calendar">
              <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 2a1 1 0 0 1 1 1v1h8V3a1 1 0 1 1 2 0v1h1.5A2.5 2.5 0 0 1 22 6.5v12A2.5 2.5 0 0 1 19.5 21h-15A2.5 2.5 0 0 1 2 18.5v-12A2.5 2.5 0 0 1 4.5 4H6V3a1 1 0 0 1 1-1Zm12.5 8h-15v8.5a.5.5 0 0 0 .5.5h14a.5.5 0 0 0 .5-.5V10ZM5 6a1 1 0 0 0-1 1v1h16V7a1 1 0 0 0-1-1H5Z"/></svg>
            </button>
          </div>
        </label>

        <label>Gender<select name="gender" id="gender"><option value="">Select gender</option><option value="female">Female</option><option value="male">Male</option><option value="other">Other</option><option value="prefer_not_to_say">Prefer not to say</option></select></label>
        <label>Emergency contact<input name="emergency_contact_name" id="emergencyContactName" placeholder="Emergency contact"></label>

        <label class="phone-label-pro">Emergency mobile
          <input type="hidden" name="emergency_contact_mobile" id="emergencyContactMobile">
          <div class="phone-field-pro phone-select-wrap" data-phone-widget="emergency" data-code="+961" data-name="Lebanon">
            <div class="country-select-pro">
              <button class="country-select-btn" type="button" data-country-button="emergency" aria-haspopup="listbox" aria-expanded="false">
                <span id="emergencyCountryLabel">Lebanon +961</span><b>▾</b>
              </button>
              <div class="country-dropdown-pro" data-country-menu="emergency" hidden>
                <input class="country-search-pro" type="search" data-country-search="emergency" placeholder="Search country or code">
                <div class="country-options-pro" data-country-options="emergency" role="listbox"></div>
              </div>
            </div>
            <input id="emergencyMobileNumber" class="phone-number-input" inputmode="tel" placeholder="Emergency mobile number">
          </div>
        </label>

        <label>Password
          <div class="password-field-member-pro">
            <input name="password" id="password" type="password" placeholder="Default password is password" autocomplete="new-password">
            <button class="field-icon-btn password-eye-member" type="button" id="toggleMemberPassword" aria-label="Show password" title="Show password">
              <svg class="eye-open" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5c5.5 0 9.5 5.2 9.5 7s-4 7-9.5 7-9.5-5.2-9.5-7S6.5 5 12 5Zm0 2C7.9 7 4.8 10.6 4.5 12c.3 1.4 3.4 5 7.5 5s7.2-3.6 7.5-5C19.2 10.6 16.1 7 12 7Zm0 2.2A2.8 2.8 0 1 1 12 14.8 2.8 2.8 0 0 1 12 9.2Z"/></svg>
              <svg class="eye-closed" viewBox="0 0 24 24" aria-hidden="true"><path d="M3.3 2 22 20.7 20.7 22l-3.2-3.2A10.4 10.4 0 0 1 12 20C6.5 20 2.5 14.8 2.5 12c0-1.2 1-2.8 2.6-4.1L2 4.7 3.3 2Zm3.2 7.3C5.3 10.3 4.7 11.4 4.5 12c.3 1.4 3.4 5 7.5 5 1.4 0 2.6-.4 3.8-1l-1.9-1.9A2.8 2.8 0 0 1 9.9 10L6.5 9.3ZM12 4c5.5 0 9.5 5.2 9.5 8 0 .9-.5 2-1.5 3.1l-2.2-2.2c.9-.9 1.5-1.7 1.7-2-.3-1.4-3.4-5-7.5-5-1 0-2 .2-2.9.6L7.5 4.9A10.7 10.7 0 0 1 12 4Z"/></svg>
            </button>
          </div>
        </label>
      </div>
      <label>Medical conditions<textarea name="medical_conditions" id="medicalConditions" placeholder="Allergies, asthma, medication, injuries..."></textarea></label>

      <section class="member-groups-editor-card" id="memberGroupsEditor">
        <div class="mini-section-head">
          <div>
            <strong>Member groups</strong>
            <span>Add this member to one or more groups. Used for invitations and closed photo voting permissions.</span>
          </div>
          <div class="member-groups-actions">
            <button class="btn btn-light btn-small" type="button" id="selectAllMemberGroupsBtn">Select all</button>
            <button class="btn btn-light btn-small" type="button" id="clearMemberGroupsBtn">Clear</button>
          </div>
        </div>
        <input id="memberGroupSearch" class="full-input member-group-search" placeholder="Search groups...">
        <div id="memberGroupsSelected" class="member-group-selected-zone"></div>
        <div id="memberGroupsChecklist" class="member-groups-checklist"></div>
      </section>

      <label class="check"><input type="checkbox" name="photo_consent" id="photoConsent" value="1"> Photo consent approved</label>
      <div class="modal-actions">
        <button class="btn btn-light" type="button" data-close-modal="memberFormModal">Cancel</button>
        <button class="btn" type="submit" id="saveMemberBtn">Save member</button>
      </div>
      <p id="memberMsg" class="notice"></p>
    </form>
  </div>
</div>
<?php endif; ?>

<div class="modal-backdrop" id="memberProfileModal" hidden>
  <div class="modal-card member-profile-modal" role="dialog" aria-modal="true" aria-labelledby="profileMemberName">
    <div class="modal-head">
      <div>
        <p class="eyebrow">Member profile</p>
        <h2 id="profileMemberName">Member profile</h2>
      </div>
      <button class="icon-btn" type="button" data-close-modal="memberProfileModal">×</button>
    </div>
    <div id="memberProfileContent" class="member-profile-content">
      <p class="muted">Loading profile...</p>
    </div>
  </div>
</div>

<script>
window.PYRK_API_BASE='../../api';
window.PYRK_CSRF='<?= htmlspecialchars($csrf) ?>';
window.PYRK_CAN_EDIT_MEMBERS=<?= $canEdit ? 'true' : 'false' ?>;
window.PYRK_CAN_DELETE_MEMBERS=<?= $canDeleteMembers ? 'true' : 'false' ?>; window.PYRK_CAN_MANAGE_USER_PRIVILEGES=<?= $canManageUserPrivileges ? 'true' : 'false' ?>;
window.PYRK_PUBLIC_BASE='../';
</script>
<script src="../assets/js/api.js?v=4"></script>
<script src="../assets/js/admin_members.js?v=member-waivers-v1"></script>
</body>
</html>
