<?php
// This script is intended to be included within admin_dashboard.php,
// ensuring $conn (database connection) is available.

// Check if $conn exists. If not, try to include the database connection 
// using a path that works relative to the dashboard (assuming dashboard 
// is in the root and this file is in sections/).
if (!isset($conn)) {
    // Attempt to include the connection file one level up (where admin_dashboard.php is)
    // NOTE: This assumes admin_dashboard.php is in the root and is running this script.
    if (file_exists('config/db_connection.php')) {
        require_once 'config/db_connection.php';
    } else {
        // Fallback for debugging, if the path above still fails
        die("FATAL ERROR: Database connection configuration file not found at 'config/db_connection.php' (relative to admin_dashboard.php).");
    }
}


$message = '';
$message_class = '';

// 🔹 Step 4: Handle Password Update
if (isset($_POST['update_password'])) {
    $target_user_id = intval($_POST['target_user_id']);
    $new_password = $_POST['new_password'];
    $hashed = password_hash($new_password, PASSWORD_DEFAULT);

    $sql = "UPDATE users SET password=? WHERE user_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $hashed, $target_user_id);
    if ($stmt->execute()) {
        $message = "Password updated successfully for User ID {$target_user_id}.";
        $message_class = 'success';
    } else {
        $message = "Failed to update password.";
        $message_class = 'error';
    }
}









// --- 1. HANDLE USER CREATION SUBMISSION ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_user'])) {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? '';

    // Simple validation
    if (empty($username) || empty($password) || empty($role)) {
        $message = "Error: All fields are required.";
        $message_class = 'error';
    } else {
        // Hashing the password is CRUCIAL for security
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // --- Prevent duplicate usernames first ---
		$check = $conn->prepare("SELECT user_id FROM users WHERE username = ?");
		$check->bind_param("s", $username);
		$check->execute();
		$check->store_result();

		if ($check->num_rows > 0) {
			$message = "⚠️WARNING!!! Username '{$username}' already exists! Please choose a different username.";
			$message_class = 'error';
			$check->close();
		} else {
			$check->close();

			// SQL to insert the new user using a prepared statement
			$sql = "INSERT INTO users (username, password, role) VALUES (?, ?, ?)";

			// Disable exception temporarily to handle errors manually
			mysqli_report(MYSQLI_REPORT_OFF);

			if (isset($conn) && $stmt = $conn->prepare($sql)) {
				$stmt->bind_param("sss", $username, $hashed_password, $role);

				if ($stmt->execute()) {
					$message = "✅ Success: User '{$username}' created with role '{$role}'.";
					$message_class = 'success';
				} else {
					$message = "❌ Error creating user: " . htmlspecialchars($stmt->error);
					$message_class = 'error';
				}

				$stmt->close();
			}

			// Re-enable default MySQLi error reporting
			mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
		}
	}
}

// --- 2. FETCH ALL USERS FOR THE MODAL ---
$all_users = [];

if (isset($conn)) {
    // FIX: Changed 'id' to 'user_id' to match the database schema.
    $sql_fetch = "SELECT user_id, username, role, created_at FROM users ORDER BY user_id ASC";
    $result = $conn->query($sql_fetch);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $all_users[] = $row;
        }
    } else {
        // If table doesn't exist, display a setup error
        $message = "Error: Could not retrieve users. Ensure the 'users' table is created correctly in your database.";
        $message_class = 'error';
    }
} else {
    $message = "Error: Cannot display user list. Database connection failed.";
    $message_class = 'error';
}

// Define the available roles (must match the ENUM in your SQL table)
$roles = ['Admin', 'HR', 'Markeing Manager', 'SOC Engineer', 'Pentester', 'Supervisor', 'Manager', 'Employee'];
?>

<style>
    /* Basic styling for the section */
    .form-container, .user-list-container {
        max-width: 600px;
        margin: 20px auto;
        padding: 25px;
        border: 1px solid #ddd;
        border-radius: 8px;
        background-color: #f9f9f9;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .form-container h2, .user-list-container h2 {
        color: #333;
        margin-top: 0;
        border-bottom: 2px solid #ccc;
        padding-bottom: 10px;
        margin-bottom: 20px;
    }
    .form-group {
        margin-bottom: 15px;
    }
    .form-group label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
    }
    .form-group input, .form-group select {
        width: 100%;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box; /* Includes padding and border in the element's total width and height */
    }
    .btn {
        padding: 12px 25px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-weight: bold;
        transition: background-color 0.3s ease;
        margin-right: 10px;
		
    }
    .btn-primary {
        background-color: #4CAF50;
        color: white;
    }
    .btn-primary:hover {
        background-color: #45a049;
    }
    .btn-secondary {
        background-color: #4CAF50;
        color: white;
    }
    .btn-secondary:hover {
        background-color: #45a049;
    }
    .message {
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 4px;
        font-weight: bold;
    }
    .message.success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .message.error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    /* Modal Styling */
    .modal {
        display: none; /* Hidden by default */
        position: fixed; /* Stay in place */
        z-index: 10; /* Sit on top */
        left: 0;
        top: 0;
        width: 100%; /* Full width */
        height: 100%; /* Full height */
        overflow: auto; /* Enable scroll if needed */
        background-color: rgba(0,0,0,0.6); /* Black w/ opacity */
    }

    .modal-content {
        background-color: #fefefe;
        margin: 10% auto; /* 10% from the top and centered */
        padding: 20px;
        border: 1px solid #888;
        width: 80%; /* Could be more or less, depending on screen size */
        max-width: 800px;
        border-radius: 8px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.3);
    }
    .modal-content h3 {
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
    }
    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }
    .close:hover,
    .close:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
    }
    .user-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
    }
    .user-table th, .user-table td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    .user-table th {
        background-color: #e9e9e9;
    }
</style>

<div class="form-container">
    <h2>Create User and Assign Role</h2>
    
    <?php if ($message): ?>
        <div class="message <?php echo $message_class; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <!-- User Creation Form -->
    <form method="POST" action="admin_dashboard.php?page=manage_users">
        <input type="hidden" name="create_user" value="1">
        
        <div class="form-group">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required>
        </div>

        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
        </div>

        <div class="form-group">
            <label for="role">Role:</label>
            <select id="role" name="role" required>
                <option value="">-- Select Role --</option>
                <?php foreach ($roles as $r): ?>
                    <option value="<?php echo htmlspecialchars($r); ?>"><?php echo htmlspecialchars($r); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <button type="submit" class="btn btn-primary">Create User</button>
        <button type="button" class="btn btn-secondary" onclick="document.getElementById('userListModal').style.display='block'">
            <b>See List of Users<b/>
        </button>
    </form>
</div>

<!-- Modal Structure for User List -->
<div id="userListModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="document.getElementById('userListModal').style.display='none'">&times;</span>
        <h3>Current Users and Roles</h3>
        
        <?php if (!empty($all_users)): ?>
            <table class="user-table">
                <thead>
                    <tr>
                        <!-- FIX: Changed header to User ID -->
						<th>User ID</th>
						<th>Username</th>
						<th>Role</th>
						<th>Created At</th>
						<th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($all_users as $user): ?>
                        <tr>
                            <!-- FIX: Changed column reference to 'user_id' -->
                            <td><?php echo htmlspecialchars($user['user_id']); ?></td>
							<td><?php echo htmlspecialchars($user['username']); ?></td>
							<td><?php echo htmlspecialchars($user['role']); ?></td>
							<td><?php echo htmlspecialchars($user['created_at'] ?? 'N/A'); ?></td>	
							<td>
								<button class="change-pass-btn" data-id="<?php echo $user['user_id']; ?>" 
										style="background:#007bff;color:#fff;border:none;padding:5px 10px;border-radius:5px;cursor:pointer;">
									Change Password
								</button>
							</td>

                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p>No users found in the database, or a connection error occurred. Please verify your database connection and the existence of the 'users' table.</p>
        <?php endif; ?>
    </div>
</div>


<!-- 🔹 Step 2: Password Change Modal -->
<div id="passwordModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%;
background:rgba(0,0,0,0.5); align-items:center; justify-content:center;">
  <div style="background:#fff; padding:20px; border-radius:10px; width:300px; text-align:center;">
    <h3>Change Password</h3>
    <form method="post">
      <input type="hidden" name="target_user_id" id="target_user_id">
      <input type="password" name="new_password" placeholder="Enter new password" required style="width:100%;padding:8px;margin:10px 0;">
      <button type="submit" name="update_password" 
              style="background:#28a745;color:white;border:none;padding:8px 12px;border-radius:5px;cursor:pointer;">
        Update
      </button>
      <button type="button" onclick="document.getElementById('passwordModal').style.display='none'"
              style="background:#ccc;border:none;padding:8px 12px;border-radius:5px;margin-left:5px;cursor:pointer;">
        Cancel
      </button>
    </form>
  </div>
</div>
<!-- 🔹 End of Password Modal -->



<script>
    // Close the modal if the user clicks anywhere outside of it
    var modal = document.getElementById('userListModal');
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
	// 🔹 Step 3: Add click handler for "Change Password" buttons
	document.querySelectorAll('.change-pass-btn').forEach(btn => {
	  btn.addEventListener('click', function() {
		document.getElementById('target_user_id').value = this.dataset.id;
		document.getElementById('passwordModal').style.display = 'flex';
	  });
	});

</script>
