<?php
// activate_pp/edit.php
// KZNHEALTH PAYMENTPACK - Edit User Page with Dropdown Lists
// PERMANENT FIX: User not found issue - now uses session and multiple fallback methods

// --- Start session for better user data management ---
session_start();

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

// --- Get user ID from multiple sources (URL, POST, SESSION) ---
$id_user = 0;

// 1. Check URL parameter first
if (isset($_GET['id']) && !empty($_GET['id'])) {
    $id_user = intval($_GET['id']);
    $_SESSION['edit_user_id'] = $id_user; // Store in session as backup
}
// 2. Check POST data
else if (isset($_POST['id_user']) && !empty($_POST['id_user'])) {
    $id_user = intval($_POST['id_user']);
    $_SESSION['edit_user_id'] = $id_user;
}
// 3. Check session as last resort
else if (isset($_SESSION['edit_user_id']) && !empty($_SESSION['edit_user_id'])) {
    $id_user = intval($_SESSION['edit_user_id']);
}

// --- If still no ID, redirect to index ---
if ($id_user <= 0) {
    $_SESSION['error_message'] = 'No user ID provided. Please select a user to edit.';
    header('Location: index.php');
    exit;
}

$user = null;
$message = '';
$messageType = '';

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

// --- Fetch delivery points from paymentpack.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();
}

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

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

        if ($stmt->execute()) {
            $message = '✅ User updated successfully!';
            $messageType = 'success';
            $_SESSION['edit_user_id'] = $id_user; // Keep session updated
        } else {
            $message = '❌ Update failed: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    } else {
        $message = '❌ All fields are required.';
        $messageType = 'danger';
    }
}

// --- Process Reset Password ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reset_password') {
    $id_user = intval($_POST['id_user'] ?? 0);
    $defaultPassword = 'KZN@2026';
    $hashedPassword = password_hash($defaultPassword, PASSWORD_DEFAULT);

    if ($id_user > 0) {
        $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id_user = ?");
        $stmt->bind_param("si", $hashedPassword, $id_user);
        if ($stmt->execute()) {
            $message = '✅ Password reset to default: ' . $defaultPassword;
            $messageType = 'success';
            $_SESSION['edit_user_id'] = $id_user;
        } else {
            $message = '❌ Password reset failed: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    } else {
        $message = '❌ Invalid user ID.';
        $messageType = 'danger';
    }
}

// --- Fetch user data with multiple retry attempts ---
function fetchUserWithRetry($conn, $id_user, $maxRetries = 3) {
    $user = null;
    for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
        $stmt = $conn->prepare("SELECT * FROM users WHERE id_user = ?");
        if ($stmt) {
            $stmt->bind_param("i", $id_user);
            $stmt->execute();
            $result = $stmt->get_result();
            $user = $result->fetch_assoc();
            $stmt->close();
            if ($user) {
                break; // Success, exit loop
            }
        }
        // Wait a tiny bit before retry
        if ($attempt < $maxRetries) {
            usleep(100000); // 0.1 second delay
        }
    }
    return $user;
}

// --- Fetch user data with retry mechanism ---
if ($id_user > 0) {
    $user = fetchUserWithRetry($conn, $id_user);
}

// --- If user still not found, try to get from session or redirect ---
if (!$user) {
    // Check if we have a valid session user
    if (isset($_SESSION['edit_user_data']) && !empty($_SESSION['edit_user_data'])) {
        $user = $_SESSION['edit_user_data'];
        $message = '⚠️ Using cached user data. Please refresh if data seems outdated.';
        $messageType = 'warning';
    } else {
        // Store the ID in session error for display on index
        $_SESSION['error_message'] = 'User with ID ' . $id_user . ' not found in database.';
        header('Location: index.php');
        exit;
    }
} else {
    // Store user data in session as backup
    $_SESSION['edit_user_data'] = $user;
}

// --- Check if user was deleted or doesn't exist ---
if (!$user || empty($user['id_user'])) {
    $_SESSION['error_message'] = 'User record could not be retrieved. Please try again.';
    header('Location: index.php');
    exit;
}

// --- Process any error messages from index ---
if (isset($_SESSION['error_message'])) {
    $message = $_SESSION['error_message'];
    $messageType = 'danger';
    unset($_SESSION['error_message']);
}

$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 · Edit User</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: 30px 20px;
      color: #1d3b2f;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .container {
      max-width: 650px;
      width: 100%;
      background: rgba(255, 255, 255, 0.8);
      backdrop-filter: blur(12px);
      -webkit-backdrop-filter: blur(12px);
      border-radius: 48px;
      padding: 40px 36px;
      box-shadow: 0 30px 80px rgba(30, 70, 50, 0.15);
      border: 1px solid rgba(180, 210, 180, 0.25);
    }

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 32px;
      padding-bottom: 20px;
      border-bottom: 2px solid #eef5ee;
    }

    .header h1 {
      font-size: 1.6rem;
      font-weight: 700;
      color: #1b4f2b;
      display: flex;
      align-items: center;
      gap: 12px;
    }
    .header h1 i {
      color: #2a6e3a;
      font-size: 1.8rem;
    }

    .back-btn {
      background: #eef5ee;
      border: none;
      padding: 10px 20px;
      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;
    }
    .alert-warning {
      background: #fef9e7;
      color: #7d6608;
      border-left: 5px solid #f39c12;
    }

    .user-info {
      background: #f8fcf8;
      border-radius: 20px;
      padding: 16px 20px;
      margin-bottom: 28px;
      border: 1px solid #dcecdc;
    }
    .user-info .label {
      font-size: 0.7rem;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      color: #5d7d63;
      font-weight: 600;
    }
    .user-info .value {
      font-size: 0.95rem;
      font-weight: 500;
      color: #1b4f2b;
      margin-top: 2px;
    }

    .field {
      margin-bottom: 18px;
    }
    .field label {
      display: block;
      font-weight: 600;
      font-size: 0.75rem;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      color: #3f6b4c;
      margin-bottom: 6px;
    }
    .field input,
    .field select {
      width: 100%;
      border: 2px solid #dcecdc;
      border-radius: 30px;
      padding: 14px 20px;
      font-size: 0.95rem;
      font-family: 'Inter', sans-serif;
      background: #fafffa;
      transition: 0.2s;
    }
    .field input:focus,
    .field select:focus {
      outline: none;
      border-color: #2f7a45;
      box-shadow: 0 0 0 5px rgba(45, 120, 60, 0.1);
      background: white;
    }
    .field select {
      appearance: none;
      -webkit-appearance: none;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%233f6b4c' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-position: right 18px center;
      padding-right: 40px;
    }

    .field-row {
      display: flex;
      gap: 14px;
    }
    .field-row .field {
      flex: 1;
    }

    .btn-reset {
      background: #d9e8d9;
      border: none;
      border-radius: 40px;
      padding: 12px 24px;
      font-weight: 500;
      color: #1a4025;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 10px;
      transition: 0.15s;
      font-size: 0.85rem;
    }
    .btn-reset:hover {
      background: #c6ddc6;
      transform: scale(0.97);
    }

    .actions {
      display: flex;
      gap: 14px;
      margin-top: 30px;
      padding-top: 24px;
      border-top: 2px solid #eef5ee;
    }
    .actions .btn {
      padding: 14px 34px;
      border-radius: 60px;
      font-weight: 600;
      font-size: 0.9rem;
      border: none;
      cursor: pointer;
      transition: 0.15s;
      flex: 1;
    }
    .btn-secondary {
      background: #eef5ee;
      color: #1d3b2f;
    }
    .btn-secondary:hover {
      background: #ddecdd;
    }
    .btn-primary {
      background: #1f5430;
      color: white;
      box-shadow: 0 4px 16px rgba(30, 80, 40, 0.2);
    }
    .btn-primary:hover {
      background: #123e1e;
      transform: scale(0.97);
    }

    .text-muted {
      color: #6b8aa3;
      font-size: 0.7rem;
      margin-top: 4px;
      display: block;
    }

    .debug-info {
      background: #f8f9fa;
      border-radius: 12px;
      padding: 12px 16px;
      margin-top: 20px;
      border: 1px solid #e9ecef;
      font-size: 0.7rem;
      color: #6c757d;
    }

    @media (max-width: 640px) {
      .container { padding: 24px 20px; }
      .header { flex-direction: column; align-items: stretch; gap: 12px; }
      .field-row { flex-direction: column; }
      .actions { flex-direction: column-reverse; }
      .actions .btn { width: 100%; }
    }
  </style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1><i class="fas fa-user-edit"></i> Edit User</h1>
    <a href="index.php" class="back-btn"><i class="fas fa-arrow-left"></i> Back</a>
  </div>

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

  <!-- User Info -->
  <div class="user-info">
    <div style="display: flex; justify-content: space-between; flex-wrap: wrap; gap: 10px;">
      <div>
        <div class="label"><i class="far fa-user"></i> Full Name</div>
        <div class="value"><?php echo htmlspecialchars($user['firstname'] ?? '') . ' ' . htmlspecialchars($user['lastname'] ?? ''); ?></div>
      </div>
      <div>
        <div class="label"><i class="fas fa-envelope"></i> Email</div>
        <div class="value"><?php echo htmlspecialchars($user['email'] ?? ''); ?></div>
      </div>
      <div>
        <div class="label"><i class="fas fa-id-badge"></i> ID</div>
        <div class="value">#<?php echo $user['id_user'] ?? 'N/A'; ?></div>
      </div>
    </div>
  </div>

  <!-- Edit Form with Dropdowns -->
  <form method="POST" action="">
    <input type="hidden" name="action" value="update_user" />
    <input type="hidden" name="id_user" value="<?php echo $user['id_user'] ?? 0; ?>" />

    <div class="field">
      <label><i class="far fa-user"></i> Firstname</label>
      <input type="text" name="firstname" value="<?php echo htmlspecialchars($user['firstname'] ?? ''); ?>" required />
    </div>

    <div class="field-row">
      <div class="field">
        <label><i class="fas fa-building"></i> Facility</label>
        <select name="facility" required>
          <option value="">Select Facility</option>
          <?php foreach ($delPoints as $dp): ?>
            <option value="<?php echo htmlspecialchars($dp['dem_name']); ?>" 
              <?php echo (($user['facility'] ?? '') == $dp['dem_name']) ? 'selected' : ''; ?>>
              <?php echo htmlspecialchars($dp['dem_name']); ?>
            </option>
          <?php endforeach; ?>
        </select>
        <small class="text-muted">Select facility from delivery points</small>
      </div>
      <div class="field">
        <label><i class="fas fa-map-pin"></i> District</label>
        <select name="district" required>
          <option value="">Select District</option>
          <?php foreach ($districts as $d): ?>
            <option value="<?php echo htmlspecialchars($d['district_name']); ?>" 
              <?php echo (($user['district'] ?? '') == $d['district_name']) ? 'selected' : ''; ?>>
              <?php echo htmlspecialchars($d['district_name']); ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <div class="field">
      <label><i class="fas fa-location-dot"></i> Delivery Point</label>
      <select name="del_point">
        <option value="">Select Delivery Point</option>
        <?php foreach ($delPoints as $dp): ?>
          <option value="<?php echo htmlspecialchars($dp['del_point']); ?>" 
            <?php echo (($user['del_point'] ?? '') == $dp['del_point']) ? 'selected' : ''; ?>>
            <?php echo htmlspecialchars($dp['del_point'] . ' - ' . $dp['dem_name']); ?>
          </option>
        <?php endforeach; ?>
      </select>
      <small class="text-muted">Delivery point code (optional)</small>
    </div>

    <div class="field">
      <label><i class="fas fa-toggle-on"></i> Status</label>
      <select name="active">
        <option value="1" <?php echo ($user['active'] ?? 0) == 1 ? 'selected' : ''; ?>>Active</option>
        <option value="0" <?php echo ($user['active'] ?? 0) == 0 ? 'selected' : ''; ?>>Inactive</option>
      </select>
    </div>

    <div class="actions">
      <a href="index.php" class="btn btn-secondary">Cancel</a>
      <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Update User</button>
    </div>
  </form>

  <!-- Reset Password Section -->
  <div style="margin-top: 24px; padding-top: 20px; border-top: 2px solid #eef5ee;">
    <form method="POST" action="" onsubmit="return confirm('Reset password for this user to default (KZN@2026)?');">
      <input type="hidden" name="action" value="reset_password" />
      <input type="hidden" name="id_user" value="<?php echo $user['id_user'] ?? 0; ?>" />
      <button type="submit" class="btn-reset"><i class="fas fa-rotate-left"></i> Reset Password to Default</button>
    </form>
  </div>

  <!-- Debug Info (hidden by default, shows for troubleshooting) -->
  <div class="debug-info" style="display: none;">
    <strong>Debug Info:</strong><br />
    User ID: <?php echo $id_user; ?><br />
    Session ID: <?php echo $_SESSION['edit_user_id'] ?? 'None'; ?><br />
    User exists: <?php echo $user ? 'Yes' : 'No'; ?>
  </div>
</div>

<script>
  // Auto-hide success messages after 5 seconds
  document.addEventListener('DOMContentLoaded', function() {
    const alerts = document.querySelectorAll('.alert-success');
    alerts.forEach(function(alert) {
      setTimeout(function() {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(function() {
          alert.style.display = 'none';
        }, 500);
      }, 5000);
    });
  });
</script>
</body>
</html>