<?php
// activate_pp/index.php
// KZNHEALTH PAYMENTPACK - Premium User Administration
// Main page listing users with Edit button linking to edit.php

// --- Database Configuration ---
$dbHost = '127.0.0.1';
$dbUser = 'root';        // Change as needed
$dbPass = '';            // Change as needed
$dbName = 'paymentpack';

// Create connection
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbName);

// Check connection
if ($conn->connect_error) {
    die('<div class="alert alert-danger">Database connection failed: ' . $conn->connect_error . '</div>');
}

// --- Process AJAX / POST requests for fetch_users ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'fetch_users') {
    $result = $conn->query("SELECT id_user, firstname, lastname, email, address, del_point, facility, district, province, contactno, position, active, date_user_created, last_log, log_count, access, logged_in FROM users ORDER BY id_user DESC");
    $users = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
        $result->free();
    }
    header('Content-Type: application/json');
    echo json_encode($users);
    exit;
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes" />
  <title>KZNHEALTH · PAYMENTPACK · Admin</title>
  <!-- Font & Icons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
  <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,400;14..32,500;14..32,600;14..32,700&display=swap" rel="stylesheet" />
  <!-- html2pdf for PDF export -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
      background: #eef5ee;
      padding: 24px 20px 40px;
      color: #1d3b2f;
      min-height: 100vh;
      display: flex;
      align-items: flex-start;
      justify-content: center;
    }

    .app-container {
      max-width: 1440px;
      width: 100%;
      background: rgba(255, 255, 255, 0.6);
      backdrop-filter: blur(12px);
      -webkit-backdrop-filter: blur(12px);
      border-radius: 48px;
      padding: 28px 28px 32px;
      box-shadow: 0 20px 60px rgba(30, 70, 50, 0.10);
      border: 1px solid rgba(180, 210, 180, 0.25);
    }

    /* HEADER */
    .header-row {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 18px;
      gap: 14px;
    }

    .brand {
      display: flex;
      align-items: center;
      gap: 14px;
      flex-wrap: wrap;
    }

    .logo-kzn {
      background: #d4e8d4;
      padding: 6px 20px 6px 16px;
      border-radius: 60px;
      display: flex;
      align-items: center;
      gap: 10px;
      border: 1px solid rgba(60, 130, 80, 0.2);
      box-shadow: inset 0 1px 4px rgba(255,255,255,0.7);
      font-weight: 600;
      color: #1a4a2a;
    }
    .logo-kzn i { font-size: 1.6rem; color: #2a6e3a; }
    .logo-kzn span { font-size: 0.9rem; letter-spacing: -0.2px; }

    .app-title {
      font-weight: 600;
      font-size: 1.4rem;
      color: #1b4f2b;
      letter-spacing: -0.3px;
    }
    .app-title small {
      font-weight: 400;
      font-size: 0.7rem;
      color: #3f6b4c;
      margin-left: 6px;
      opacity: 0.7;
    }

    .badge-secure {
      background: #1f5430;
      color: white;
      padding: 6px 22px;
      border-radius: 60px;
      font-size: 0.7rem;
      font-weight: 500;
      letter-spacing: 0.5px;
      display: flex;
      align-items: center;
      gap: 8px;
      box-shadow: 0 4px 12px rgba(30, 80, 40, 0.12);
    }

    /* ppsd.png banner */
    .ppsd-banner {
      display: flex;
      justify-content: center;
      margin: 6px 0 24px 0;
    }
    .ppsd-placeholder {
      background: #dcecdc;
      padding: 8px 36px;
      border-radius: 80px;
      font-weight: 500;
      color: #1f4a2a;
      font-size: 0.9rem;
      border: 1px solid #b6d2b6;
      display: inline-flex;
      align-items: center;
      gap: 14px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.02);
    }
    .ppsd-placeholder i { color: #2d7540; font-size: 1.3rem; }

    /* TOOLBAR */
    .toolbar {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 14px 18px;
      margin-bottom: 28px;
      justify-content: space-between;
    }

    .search-box {
      display: flex;
      align-items: center;
      background: white;
      border-radius: 60px;
      padding: 3px 3px 3px 20px;
      border: 1px solid #caddca;
      flex: 1 1 280px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.02);
      transition: 0.2s;
    }
    .search-box:focus-within { border-color: #2f7a45; box-shadow: 0 0 0 4px rgba(45, 120, 60, 0.08); }
    .search-box i { color: #4d7a5a; opacity: 0.5; }
    .search-box input {
      border: none;
      padding: 12px 14px;
      font-size: 0.9rem;
      width: 100%;
      background: transparent;
      outline: none;
      font-family: 'Inter', sans-serif;
      color: #1f3f2a;
    }
    .search-box input::placeholder { color: #90b094; }
    .search-box button {
      background: #1f5430;
      border: none;
      color: white;
      padding: 8px 24px;
      border-radius: 60px;
      font-weight: 500;
      font-size: 0.8rem;
      cursor: pointer;
      transition: 0.15s;
    }
    .search-box button:hover { background: #123e1e; }

    .filter-group {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 8px;
    }
    .filter-group select {
      background: white;
      border: 1px solid #caddca;
      border-radius: 60px;
      padding: 10px 20px;
      font-family: 'Inter', sans-serif;
      font-size: 0.8rem;
      color: #1d3b2f;
      outline: none;
      cursor: pointer;
      transition: 0.15s;
    }
    .filter-group select:focus { border-color: #2f7a45; }

    .btn-pdf {
      background: #2a7040;
      color: white;
      border: none;
      padding: 10px 28px;
      border-radius: 60px;
      font-weight: 500;
      font-size: 0.8rem;
      display: inline-flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      transition: 0.15s;
      box-shadow: 0 4px 12px rgba(30, 80, 40, 0.10);
    }
    .btn-pdf:hover { background: #1b542e; transform: scale(0.97); }

    .btn-null {
      background: #c0392b;
      color: white;
      border: none;
      padding: 10px 28px;
      border-radius: 60px;
      font-weight: 500;
      font-size: 0.8rem;
      display: inline-flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      transition: 0.15s;
      text-decoration: none;
      box-shadow: 0 4px 12px rgba(192, 57, 43, 0.2);
    }
    .btn-null:hover { background: #a93226; transform: scale(0.97); }

    /* TABLE */
    .table-wrapper {
      overflow-x: auto;
      -webkit-overflow-scrolling: touch;
      border-radius: 28px;
      background: rgba(255,255,255,0.5);
      backdrop-filter: blur(4px);
      padding: 4px 2px;
      margin-bottom: 24px;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      font-size: 0.8rem;
      min-width: 800px;
    }

    th {
      text-align: left;
      padding: 18px 14px 14px 14px;
      color: #2a5a38;
      font-weight: 600;
      font-size: 0.7rem;
      letter-spacing: 0.5px;
      text-transform: uppercase;
      border-bottom: 2px solid #d0e2d0;
      background: rgba(235, 246, 235, 0.2);
    }

    td {
      padding: 14px 14px;
      vertical-align: middle;
      border-bottom: 1px solid #ddecdd;
      background: rgba(255,255,255,0.15);
      backdrop-filter: blur(2px);
    }
    tr:last-child td { border-bottom: none; }

    .user-cell .name { font-weight: 600; color: #1b3f26; }
    .user-cell .email { font-size: 0.7rem; color: #4c7a5a; }
    .user-cell .id-tag { font-size: 0.65rem; color: #5d7d63; }

    .badge-status {
      display: inline-block;
      padding: 4px 16px;
      border-radius: 40px;
      font-size: 0.7rem;
      font-weight: 600;
      background: #d8ecd8;
      color: #1b582a;
    }
    .badge-status.inactive {
      background: #ececec;
      color: #5a5a5a;
    }

    .badge-null {
      display: inline-block;
      padding: 3px 12px;
      border-radius: 40px;
      font-size: 0.6rem;
      font-weight: 600;
      background: #fdebd0;
      color: #a04000;
    }

    .btn-edit {
      background: #2a6e40;
      border: none;
      color: white;
      padding: 8px 20px;
      border-radius: 40px;
      font-weight: 500;
      font-size: 0.75rem;
      cursor: pointer;
      transition: 0.1s;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      box-shadow: 0 2px 8px rgba(30, 80, 40, 0.08);
      text-decoration: none;
    }
    .btn-edit:hover { 
      background: #1a4f2a; 
      transform: scale(0.96);
    }

    /* PAGINATION */
    .pagination-wrap {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
    }
    .pagination {
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
    }
    .pagination button {
      background: white;
      border: 1px solid #cbdfcb;
      padding: 8px 18px;
      border-radius: 40px;
      font-weight: 500;
      color: #1f452a;
      cursor: pointer;
      transition: 0.1s;
      font-size: 0.75rem;
    }
    .pagination button.active {
      background: #1f5430;
      color: white;
      border-color: #1f5430;
    }
    .pagination button:disabled { opacity: 0.3; pointer-events: none; }
    .info-text { color: #477a52; font-size: 0.8rem; font-weight: 500; }

    .null-count {
      background: #c0392b;
      color: white;
      border-radius: 40px;
      padding: 2px 12px;
      font-size: 0.7rem;
      font-weight: 600;
      margin-left: 6px;
    }

    @media (max-width: 640px) {
      .app-container { padding: 16px; }
      .header-row { flex-direction: column; align-items: stretch; gap: 10px; }
      .brand { flex-wrap: wrap; }
      .toolbar { flex-direction: column; align-items: stretch; }
      .search-box { flex: 1; }
      .filter-group { justify-content: space-between; }
      .filter-group select { flex: 1; min-width: 80px; }
    }
  </style>
</head>
<body>

<div class="app-container" id="appContainer">

  <!-- HEADER -->
  <div class="header-row">
    <div class="brand">
      <div class="logo-kzn">
        <i class="fas fa-heartbeat"></i>
        <span>KZNHEALTH</span>
        <span style="font-weight:300; font-size:0.7rem; opacity:0.5; margin-left:2px;">·</span>
        <span style="font-weight:400; font-size:0.75rem; color:#2f6a3f;">logo.png</span>
      </div>
      <div class="app-title">
        PAYMENTPACK <small>admin</small>
      </div>
    </div>
    <div class="badge-secure">
      <i class="fas fa-shield-alt"></i> SECURE · <?php echo date('Y'); ?>
    </div>
  </div>

  <!-- ppsd.png -->
  <div class="ppsd-banner">
    <div class="ppsd-placeholder">
      <i class="fas fa-file-image"></i> ppsd.png
      <span style="font-weight:300; font-size:0.7rem; color:#3f6a4a;">(KZN Health)</span>
    </div>
  </div>

  <!-- TOOLBAR -->
  <div class="toolbar">
    <div class="search-box">
      <i class="fas fa-search"></i>
      <input type="text" id="searchInput" placeholder="Search name, email, facility..." />
      <button id="searchBtn"><i class="fas fa-arrow-right"></i></button>
    </div>
    <div class="filter-group">
      <select id="filterDistrict">
        <option value="">All Districts</option>
      </select>
      <select id="filterStatus">
        <option value="">All Status</option>
        <option value="1">Active</option>
        <option value="0">Inactive</option>
      </select>
      <a href="null_facility.php" class="btn-null" id="nullBtn">
        <i class="fas fa-exclamation-triangle"></i> Fix Null Fields
        <span class="null-count" id="nullCount">0</span>
      </a>
      <button class="btn-pdf" id="exportPdfBtn"><i class="fas fa-file-pdf"></i> PDF</button>
    </div>
  </div>

  <!-- TABLE -->
  <div class="table-wrapper">
    <table id="userTable">
      <thead>
        <tr>
          <th>User</th>
          <th>District</th>
          <th>Facility</th>
          <th>Del. Point</th>
          <th>Position</th>
          <th>Status</th>
          <th style="min-width:140px;">Action</th>
        </tr>
      </thead>
      <tbody id="tableBody">
        <tr><td colspan="7" style="text-align:center; padding:40px; color:#5f7f66;"><i class="fas fa-spinner fa-spin"></i> Loading users...</td></tr>
      </tbody>
    </table>
  </div>

  <!-- PAGINATION -->
  <div class="pagination-wrap">
    <div class="info-text" id="infoText">0 users</div>
    <div class="pagination" id="paginationControls"></div>
  </div>
</div>

<script>
  (function() {
    'use strict';

    // ---------- STATE ----------
    let allUsers = [];
    let filteredUsers = [];
    let currentPage = 1;
    const rowsPerPage = 6;

    // DOM refs
    const tbody = document.getElementById('tableBody');
    const infoText = document.getElementById('infoText');
    const paginationControls = document.getElementById('paginationControls');
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const filterDistrict = document.getElementById('filterDistrict');
    const filterStatus = document.getElementById('filterStatus');
    const exportPdfBtn = document.getElementById('exportPdfBtn');
    const nullCount = document.getElementById('nullCount');

    // ---------- FETCH USERS FROM DB ----------
    function fetchUsers() {
      fetch(window.location.href, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=fetch_users'
      })
      .then(res => res.json())
      .then(data => {
        allUsers = data;
        // Populate district filter options
        const districts = [...new Set(allUsers.map(u => u.district).filter(Boolean))];
        const districtSelect = filterDistrict;
        districtSelect.innerHTML = '<option value="">All Districts</option>';
        districts.forEach(d => {
          const opt = document.createElement('option');
          opt.value = d;
          opt.textContent = d;
          districtSelect.appendChild(opt);
        });
        
        // Count users with null fields
        const nullUsers = allUsers.filter(u => 
          !u.del_point || u.del_point === '' || 
          !u.facility || u.facility === '' || 
          !u.district || u.district === '' || 
          !u.position || u.position === ''
        );
        nullCount.textContent = nullUsers.length;
        
        applyFilters();
      })
      .catch(err => {
        console.error('Error fetching users:', err);
        tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; padding:40px; color:#c0392b;">Failed to load users. Please refresh.</td></tr>`;
      });
    }

    // ---------- RENDER TABLE ----------
    function renderTable() {
      const start = (currentPage - 1) * rowsPerPage;
      const pageData = filteredUsers.slice(start, start + rowsPerPage);
      const total = filteredUsers.length;
      const totalPages = Math.ceil(total / rowsPerPage) || 1;

      if (pageData.length === 0) {
        tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; padding:36px; color:#5f7f66;">No users found</td></tr>`;
        infoText.textContent = '0 users';
        renderPagination(1, 1);
        return;
      }

      let html = '';
      pageData.forEach(u => {
        const statusClass = u.active == 1 ? 'badge-status' : 'badge-status inactive';
        const statusIcon = u.active == 1 ? 'fa-check-circle' : 'fa-circle';
        const statusText = u.active == 1 ? 'Active' : 'Inactive';
        
        // Check for null fields
        const hasNull = !u.del_point || u.del_point === '' || 
                        !u.facility || u.facility === '' || 
                        !u.district || u.district === '' ||
                        !u.position || u.position === '';
        
        html += `
          <tr>
            <td>
              <div class="user-cell">
                <span class="name"><i class="fas fa-user-circle" style="color:#2a6e3a;margin-right:6px;"></i>${escHtml(u.firstname)} ${escHtml(u.lastname)}</span>
                <span class="email"><i class="fas fa-envelope" style="margin-right:4px;"></i>${escHtml(u.email)}</span>
                <span class="id-tag">ID: ${u.id_user}</span>
                ${hasNull ? ' <span class="badge-null"><i class="fas fa-exclamation-circle"></i> Missing Data</span>' : ''}
              </div>
            </td>
            <td>${escHtml(u.district) || '<span style="color:#c0392b;">—</span>'}</td>
            <td>${escHtml(u.facility) || '<span style="color:#c0392b;">—</span>'}</td>
            <td>${escHtml(u.del_point) || '<span style="color:#c0392b;">—</span>'}</td>
            <td>${escHtml(u.position) || '<span style="color:#c0392b;">—</span>'}</td>
            <td><span class="${statusClass}"><i class="fas ${statusIcon}" style="margin-right:4px;"></i>${statusText}</span></td>
            <td>
              <a href="edit.php?id=${u.id_user}" class="btn-edit" target="_self"><i class="fas fa-pen"></i> Edit</a>
            </td>
          </tr>
        `;
      });
      tbody.innerHTML = html;
      infoText.textContent = `Showing ${start+1}–${Math.min(start+rowsPerPage, total)} of ${total} users`;
      renderPagination(currentPage, totalPages);
    }

    function renderPagination(active, totalPages) {
      let html = `<button class="${active===1?'active':''}" data-page="1" ${active===1?'disabled':''}>1</button>`;
      for (let i = 2; i <= totalPages; i++) {
        html += `<button class="${i===active?'active':''}" data-page="${i}">${i}</button>`;
      }
      paginationControls.innerHTML = html;
      paginationControls.querySelectorAll('button').forEach(btn => {
        btn.addEventListener('click', function() {
          const page = parseInt(this.dataset.page);
          if (page && page !== currentPage) {
            currentPage = page;
            renderTable();
          }
        });
      });
    }

    // ---------- FILTERS ----------
    function applyFilters() {
      const term = searchInput.value.toLowerCase().trim();
      const districtVal = filterDistrict.value;
      const statusVal = filterStatus.value;

      filteredUsers = allUsers.filter(u => {
        const matchSearch = !term ||
          (u.firstname && u.firstname.toLowerCase().includes(term)) ||
          (u.lastname && u.lastname.toLowerCase().includes(term)) ||
          (u.email && u.email.toLowerCase().includes(term)) ||
          (u.facility && u.facility.toLowerCase().includes(term)) ||
          (u.district && u.district.toLowerCase().includes(term));
        const matchDistrict = !districtVal || u.district === districtVal;
        const matchStatus = statusVal === '' || String(u.active) === statusVal;
        return matchSearch && matchDistrict && matchStatus;
      });
      currentPage = 1;
      renderTable();
    }

    // ---------- PDF EXPORT ----------
    exportPdfBtn.addEventListener('click', function() {
      const element = document.getElementById('appContainer');
      html2pdf().set({
        margin: 0.5,
        filename: 'KZN_PAYMENTPACK_USERS.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2, letterRendering: true },
        jsPDF: { unit: 'in', format: 'a4', orientation: 'landscape' }
      }).from(element).save();
    });

    // ---------- HELPERS ----------
    function escHtml(str) {
      if (!str) return '';
      return String(str).replace(/[&<>"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'})[m] || m);
    }

    // ---------- EVENT BINDING ----------
    searchBtn.addEventListener('click', applyFilters);
    searchInput.addEventListener('keyup', function(e) { 
      if (e.key === 'Enter') applyFilters(); 
    });
    filterDistrict.addEventListener('change', applyFilters);
    filterStatus.addEventListener('change', applyFilters);

    // ---------- INIT ----------
    fetchUsers();
  })();
</script>
</body>
</html>