<?php
// activate_pp/null_facility.php
// KZNHEALTH PAYMENTPACK - Fix Null Fields
// Displays users with null/empty fields and allows editing

session_start();

// --- Database Configuration ---
$dbHost = '127.0.0.1';
$dbUser = 'root';
$dbPass = '';
$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>');
}

// --- Fetch districts from district table ---
$districts = [];
$districtResult = $conn->query("SELECT id_district, district FROM district ORDER BY district");
if ($districtResult) {
    while ($row = $districtResult->fetch_assoc()) {
        $districts[] = $row;
    }
    $districtResult->free();
}

// --- Fetch delivery points from del_point ---
$delPoints = [];
$delPointResult = $conn->query("SELECT del_point_id, del_point, dem_name FROM del_point ORDER BY dem_name");
if ($delPointResult) {
    while ($row = $delPointResult->fetch_assoc()) {
        $delPoints[] = $row;
    }
    $delPointResult->free();
}

// --- Fetch positions from position table ---
$positions = [];
$positionResult = $conn->query("SELECT id_position, position FROM position ORDER BY position");
if ($positionResult) {
    while ($row = $positionResult->fetch_assoc()) {
        $positions[] = $row;
    }
    $positionResult->free();
}

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

// --- Process Update ---
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_user') {
    $id_user = intval($_POST['id_user'] ?? 0);
    $facility = trim($_POST['facility'] ?? '');
    $district = trim($_POST['district'] ?? '');
    $del_point = trim($_POST['del_point'] ?? '');
    $position = trim($_POST['position'] ?? '');
    $active = intval($_POST['active'] ?? 0);

    if ($id_user > 0) {
        $stmt = $conn->prepare("UPDATE users SET facility = ?, district = ?, del_point = ?, position = ?, active = ? WHERE id_user = ?");
        $stmt->bind_param("ssssii", $facility, $district, $del_point, $position, $active, $id_user);

        if ($stmt->execute()) {
            $message = '✅ User updated successfully!';
            $messageType = 'success';
        } else {
            $message = '❌ Update failed: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    } else {
        $message = '❌ Invalid user ID.';
        $messageType = 'danger';
    }
}

$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 · Fix Null Fields</title>
  <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" />
  <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-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);
    }

    .back-btn {
      background: #eef5ee;
      border: none;
      padding: 10px 24px;
      border-radius: 40px;
      font-weight: 500;
      color: #1d3b2f;
      cursor: pointer;
      transition: 0.15s;
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      gap: 8px;
      font-size: 0.85rem;
    }
    .back-btn:hover {
      background: #ddecdd;
      transform: scale(0.96);
    }

    .alert {
      padding: 14px 20px;
      border-radius: 16px;
      font-weight: 500;
      margin-bottom: 24px;
      display: flex;
      align-items: center;
      gap: 12px;
    }
    .alert-success {
      background: #d5f5e3;
      color: #1a6e3a;
      border-left: 5px solid #2ecc71;
    }
    .alert-danger {
      background: #fdedec;
      color: #922b21;
      border-left: 5px solid #e74c3c;
    }

    .stats-banner {
      background: #fcf8e8;
      border-radius: 20px;
      padding: 16px 24px;
      margin-bottom: 28px;
      border: 1px solid #f0e6c8;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
    }
    .stats-banner .stat-item {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 0.9rem;
    }
    .stats-banner .stat-item i {
      color: #c0392b;
      font-size: 1.2rem;
    }
    .stats-banner .stat-item .num {
      font-weight: 700;
      font-size: 1.4rem;
      color: #1b4f2b;
    }

    .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: 900px;
    }

    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);
      position: sticky;
      top: 0;
      z-index: 10;
    }

    td {
      padding: 10px 14px;
      vertical-align: middle;
      border-bottom: 1px solid #ddecdd;
      background: rgba(255,255,255,0.15);
    }
    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-missing {
      display: inline-block;
      padding: 2px 12px;
      border-radius: 40px;
      font-size: 0.6rem;
      font-weight: 600;
      background: #fdebd0;
      color: #a04000;
      margin: 0 2px;
    }

    .field-select {
      width: 100%;
      padding: 8px 12px;
      border: 2px solid #dcecdc;
      border-radius: 30px;
      font-size: 0.75rem;
      font-family: 'Inter', sans-serif;
      background: #fafffa;
      transition: 0.2s;
      min-width: 80px;
    }
    .field-select:focus {
      outline: none;
      border-color: #2f7a45;
      box-shadow: 0 0 0 4px rgba(45, 120, 60, 0.08);
      background: white;
    }
    .field-select.missing {
      border-color: #e74c3c;
      background: #fef9f8;
    }

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

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

    .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; }

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: #5f7f66;
    }
    .empty-state i {
      font-size: 3rem;
      color: #2a6e3a;
      opacity: 0.3;
      margin-bottom: 16px;
    }
    .empty-state h3 {
      font-weight: 500;
      color: #1b4f2b;
      margin-bottom: 8px;
    }

    @media (max-width: 768px) {
      .app-container { padding: 16px; }
      .header-row { flex-direction: column; align-items: stretch; gap: 10px; }
      .brand { flex-wrap: wrap; }
      .stats-banner { flex-direction: column; align-items: stretch; text-align: center; }
      
      table { font-size: 0.7rem; min-width: 700px; }
      td, th { padding: 8px 10px; }
      
      .field-select { font-size: 0.7rem; padding: 6px 10px; }
      .btn-save-row { font-size: 0.65rem; padding: 6px 12px; }
      
      .pagination-wrap { flex-direction: column; align-items: stretch; }
      .pagination { justify-content: center; }
    }

    @media (max-width: 480px) {
      .app-container { padding: 12px; border-radius: 24px; }
      table { min-width: 600px; font-size: 0.65rem; }
      td, th { padding: 6px 8px; }
      .field-select { font-size: 0.65rem; padding: 4px 8px; min-width: 60px; }
      .btn-save-row { font-size: 0.6rem; padding: 4px 10px; }
      .logo-kzn { font-size: 0.7rem; padding: 4px 14px; }
      .app-title { font-size: 1.1rem; }
      .badge-secure { font-size: 0.6rem; padding: 4px 14px; }
    }
  </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">
        Fix Null Fields <small>data cleanup</small>
      </div>
    </div>
    <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
      <span class="badge-secure"><i class="fas fa-shield-alt"></i> SECURE</span>
      <a href="index.php" class="back-btn"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
  </div>

  <!-- MESSAGES -->
  <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
      <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
      <?php echo htmlspecialchars($message); ?>
    </div>
  <?php endif; ?>

  <!-- STATS -->
  <div class="stats-banner" id="statsBanner">
    <div class="stat-item">
      <i class="fas fa-users"></i>
      <span>Total Users with Missing Data: </span>
      <span class="num" id="totalNull">0</span>
    </div>
    <div class="stat-item">
      <i class="fas fa-edit"></i>
      <span>Select values from dropdowns and click <strong>Update</strong> to fix.</span>
    </div>
  </div>

  <!-- TABLE -->
  <div class="table-wrapper">
    <table id="userTable">
      <thead>
        <tr>
          <th style="min-width:140px;">User</th>
          <th style="min-width:120px;">District</th>
          <th style="min-width:150px;">Facility</th>
          <th style="min-width:100px;">Del. Point</th>
          <th style="min-width:120px;">Position</th>
          <th style="min-width:80px;">Status</th>
          <th style="min-width:90px;">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 with missing data...</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';

    // ---------- DATA FROM PHP ----------
    const districts = <?php echo json_encode($districts); ?>;
    const delPoints = <?php echo json_encode($delPoints); ?>;
    const positions = <?php echo json_encode($positions); ?>;

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

    // DOM refs
    const tbody = document.getElementById('tableBody');
    const infoText = document.getElementById('infoText');
    const paginationControls = document.getElementById('paginationControls');
    const totalNull = document.getElementById('totalNull');

    // ---------- FETCH USERS WITH NULL FIELDS ----------
    function fetchUsers() {
      fetch(window.location.href, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=fetch_null_users'
      })
      .then(res => res.json())
      .then(data => {
        allUsers = data;
        filteredUsers = [...allUsers];
        totalNull.textContent = allUsers.length;
        renderTable();
      })
      .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">
            <div class="empty-state">
              <i class="fas fa-check-circle"></i>
              <h3>All users have complete data!</h3>
              <p style="color:#5f7f66;">No null or empty fields found in the database.</p>
              <a href="index.php" class="back-btn" style="margin-top:16px; display:inline-flex;">
                <i class="fas fa-arrow-left"></i> Return to Dashboard
              </a>
            </div>
          </td></tr>
        `;
        infoText.textContent = '0 users';
        renderPagination(1, 1);
        return;
      }

      let html = '';
      pageData.forEach(u => {
        const isMissing = (field) => !field || field === '';
        
        const districtMissing = isMissing(u.district);
        const facilityMissing = isMissing(u.facility);
        const delPointMissing = isMissing(u.del_point);
        const positionMissing = isMissing(u.position);
        
        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';

        html += `
          <tr>
            <td>
              <div class="user-cell">
                <span class="name"><i class="fas fa-user-circle" style="color:#2a6e3a;margin-right:4px;"></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>
                <div style="margin-top:4px;">
                  ${districtMissing ? '<span class="badge-missing"><i class="fas fa-exclamation-circle"></i> District</span>' : ''}
                  ${facilityMissing ? '<span class="badge-missing"><i class="fas fa-exclamation-circle"></i> Facility</span>' : ''}
                  ${delPointMissing ? '<span class="badge-missing"><i class="fas fa-exclamation-circle"></i> Del Point</span>' : ''}
                  ${positionMissing ? '<span class="badge-missing"><i class="fas fa-exclamation-circle"></i> Position</span>' : ''}
                </div>
              </div>
            </td>
            <td>
              <select class="field-select ${districtMissing ? 'missing' : ''}" name="district_${u.id_user}" id="district_${u.id_user}">
                <option value="">Select District</option>
                ${districts.map(d => `<option value="${escHtml(d.district)}" ${u.district === d.district ? 'selected' : ''}>${escHtml(d.district)}</option>`).join('')}
              </select>
            </td>
            <td>
              <select class="field-select ${facilityMissing ? 'missing' : ''}" name="facility_${u.id_user}" id="facility_${u.id_user}">
                <option value="">Select Facility</option>
                ${delPoints.map(dp => `<option value="${escHtml(dp.dem_name)}" ${u.facility === dp.dem_name ? 'selected' : ''}>${escHtml(dp.dem_name)}</option>`).join('')}
              </select>
            </td>
            <td>
              <select class="field-select ${delPointMissing ? 'missing' : ''}" name="del_point_${u.id_user}" id="del_point_${u.id_user}">
                <option value="">Select Del Point</option>
                ${delPoints.map(dp => `<option value="${escHtml(dp.del_point)}" ${u.del_point === dp.del_point ? 'selected' : ''}>${escHtml(dp.del_point)}</option>`).join('')}
              </select>
            </td>
            <td>
              <select class="field-select ${positionMissing ? 'missing' : ''}" name="position_${u.id_user}" id="position_${u.id_user}">
                <option value="">Select Position</option>
                ${positions.map(p => `<option value="${escHtml(p.position)}" ${u.position === p.position ? 'selected' : ''}>${escHtml(p.position)}</option>`).join('')}
              </select>
            </td>
            <td>
              <select class="field-select" name="active_${u.id_user}" id="active_${u.id_user}">
                <option value="1" ${u.active == 1 ? 'selected' : ''}>Active</option>
                <option value="0" ${u.active == 0 ? 'selected' : ''}>Inactive</option>
              </select>
            </td>
            <td>
              <button class="btn-save-row" onclick="updateUser(${u.id_user})">
                <i class="fas fa-save"></i> Update
              </button>
            </td>
          </tr>
        `;
      });
      tbody.innerHTML = html;
      infoText.textContent = `Showing ${start+1}–${Math.min(start+rowsPerPage, total)} of ${total} users needing updates`;
      renderPagination(currentPage, totalPages);
    }

    // ---------- PAGINATION ----------
    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();
          }
        });
      });
    }

    // ---------- UPDATE USER ----------
    window.updateUser = function(userId) {
      const district = document.getElementById(`district_${userId}`).value;
      const facility = document.getElementById(`facility_${userId}`).value;
      const del_point = document.getElementById(`del_point_${userId}`).value;
      const position = document.getElementById(`position_${userId}`).value;
      const active = document.getElementById(`active_${userId}`).value;

      // Validate
      if (!district || !facility || !del_point || !position) {
        alert('Please select values for District, Facility, Delivery Point, and Position before updating.');
        return;
      }

      // Show loading state
      const btn = document.querySelector(`button[onclick="updateUser(${userId})"]`);
      const originalText = btn.innerHTML;
      btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
      btn.disabled = true;

      const formData = new FormData();
      formData.append('action', 'update_user');
      formData.append('id_user', userId);
      formData.append('district', district);
      formData.append('facility', facility);
      formData.append('del_point', del_point);
      formData.append('position', position);
      formData.append('active', active);

      fetch(window.location.href, {
        method: 'POST',
        body: formData
      })
      .then(response => response.text())
      .then(html => {
        // Reload the page to reflect changes
        window.location.reload();
      })
      .catch(err => {
        console.error('Error updating user:', err);
        alert('Failed to update user. Please try again.');
        btn.innerHTML = originalText;
        btn.disabled = false;
      });
    };

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

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