<?php
// Initialize message variables
$message = "";
$status = "";
$edit_user_data = null;

// Database credentials
$servername = "localhost";
$username = "wintelsoft_vinod";
$password = "vinodbhaskar69*";
$dbname = "wintelsoft_svf";

// Create a new database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check if the connection was successful
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Function to safely fetch user data for editing
function fetch_user_for_edit($conn, $user_id) {
    $stmt = $conn->prepare("SELECT user_id, password, mobile_no, user_rights FROM users WHERE user_id = ?");
    $stmt->bind_param("s", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user_data = $result->fetch_assoc();
    $stmt->close();
    return $user_data;
}

// Handle form submission for updating a user
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update'])) {
    // Sanitize and validate user input
    $original_user_id = trim($_POST['original_user_id']);
    $new_user_id = trim($_POST['user_id']);
    $mobile_no = trim($_POST['mobile_no']);
    $password = trim($_POST['password']);
    $user_rights = trim($_POST['user_rights']);

    // Check if any fields are empty
    if (empty($new_user_id) || empty($password) || empty($mobile_no) || empty($user_rights)) {
        $status = "error";
        $message = "All fields are required.";
    } else {
        // Use a prepared statement to prevent SQL injection
        $stmt = $conn->prepare("UPDATE users SET user_id = ?, password = ?, mobile_no = ?, user_rights = ? WHERE user_id = ?");
        
        if ($stmt === false) {
            $status = "error";
            $message = "Prepare failed: " . htmlspecialchars($conn->error);
        } else {
            // Bind parameters and execute the query
            $stmt->bind_param("sssss", $new_user_id, $password, $mobile_no, $user_rights, $original_user_id);
            
            if ($stmt->execute()) {
                $status = "success";
                $message = "User updated successfully!";
                // Update the original user ID in case it was changed
                $original_user_id = $new_user_id;
            } else {
                $status = "error";
                if ($conn->errno == 1062) {
                    $message = "User ID already exists. Please choose a different one.";
                } else {
                    $message = "Error: " . $stmt->error;
                }
            }
            $stmt->close();
        }
    }
}

// Handle delete request
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['delete_id'])) {
    $user_id_to_delete = $_GET['delete_id'];
    $stmt = $conn->prepare("DELETE FROM users WHERE user_id = ?");
    $stmt->bind_param("s", $user_id_to_delete);
    if ($stmt->execute()) {
        $status = "success";
        $message = "User deleted successfully!";
    } else {
        $status = "error";
        $message = "Error deleting user: " . $stmt->error;
    }
    $stmt->close();
}

// Handle view/edit request
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['edit_id'])) {
    $edit_user_data = fetch_user_for_edit($conn, $_GET['edit_id']);
    if (!$edit_user_data) {
        $status = "error";
        $message = "User not found.";
    }
}

// Fetch all users to display
$users_result = $conn->query("SELECT user_id, mobile_no, user_rights FROM users ORDER BY user_id ASC");
$users = [];
if ($users_result && $users_result->num_rows > 0) {
    while ($row = $users_result->fetch_assoc()) {
        $users[] = $row;
    }
}

// Close the database connection
// Note: We close the connection only after all database operations are complete.
if (isset($conn) && $conn->ping()) {
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Users</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f2f5;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            min-height: 100vh;
            margin: 0;
            padding: 40px 20px;
            box-sizing: border-box;
        }
        .container {
            background-color: #ffffff;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 900px;
            text-align: center;
        }
        h2 {
            margin-bottom: 24px;
            color: #333;
        }
        .message {
            margin-bottom: 20px;
            padding: 10px;
            border-radius: 8px;
            font-size: 14px;
        }
        .error {
            background-color: #ffe5e5;
            color: #e53935;
            border: 1px solid #e53935;
        }
        .success {
            background-color: #e5ffe5;
            color: #388e3c;
            border: 1px solid #388e3c;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
            color: #555;
            font-weight: bold;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .actions a {
            margin-right: 10px;
            text-decoration: none;
            padding: 5px 10px;
            border-radius: 5px;
            color: #fff;
            transition: background-color 0.3s ease;
        }
        .actions .edit-btn {
            background-color: #28a745;
        }
        .actions .edit-btn:hover {
            background-color: #218838;
        }
        .actions .delete-btn {
            background-color: #dc3545;
        }
        .actions .delete-btn:hover {
            background-color: #c82333;
        }
        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }
        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: bold;
        }
        input[type="text"],
        input[type="password"],
        select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ccc;
            border-radius: 8px;
            box-sizing: border-box;
            font-size: 16px;
        }
        .update-form {
            margin-top: 40px;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 12px;
            background-color: #f8f8f8;
            text-align: left;
        }
        button {
            width: 100%;
            padding: 12px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        button:hover {
            background-color: #0056b3;
        }
        .back-link {
            display: block;
            margin-top: 20px;
            text-align: center;
        }
        .back-link a {
            color: #007bff;
            text-decoration: none;
            font-weight: bold;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>Manage Users</h2>
    
    <?php if (!empty($message)): ?>
        <div class='message <?php echo $status; ?>'><?php echo $message; ?></div>
    <?php endif; ?>

    <h3>Existing Users</h3>
    <?php if (count($users) > 0): ?>
        <table>
            <thead>
                <tr>
                    <th>User ID</th>
                    <th>Mobile Number</th>
                    <th>User Rights</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $user): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user['user_id']); ?></td>
                        <td><?php echo htmlspecialchars($user['mobile_no']); ?></td>
                        <td><?php echo htmlspecialchars($user['user_rights']); ?></td>
                        <td class="actions">
                            <a href="?edit_id=<?php echo urlencode($user['user_id']); ?>" class="edit-btn">Edit</a>
                            <a href="?delete_id=<?php echo urlencode($user['user_id']); ?>" class="delete-btn" onclick="return confirm('Are you sure you want to delete this user?');">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>No users found.</p>
    <?php endif; ?>

    <?php if ($edit_user_data): ?>
        <div class="update-form">
            <h3>Edit User: <?php echo htmlspecialchars($edit_user_data['user_id']); ?></h3>
            <form action="" method="post">
                <input type="hidden" name="update" value="1">
                <input type="hidden" name="original_user_id" value="<?php echo htmlspecialchars($edit_user_data['user_id']); ?>">
                <div class="form-group">
                    <label for="user_id">User ID:</label>
                    <input type="text" id="user_id" name="user_id" value="<?php echo htmlspecialchars($edit_user_data['user_id']); ?>" required>
                </div>
                <div class="form-group">
                    <label for="password">Password:</label>
                    <input type="password" id="password" name="password" value="<?php echo htmlspecialchars($edit_user_data['password']); ?>" required>
                </div>
                <div class="form-group">
                    <label for="mobile_no">Mobile Number:</label>
                    <input type="text" id="mobile_no" name="mobile_no" value="<?php echo htmlspecialchars($edit_user_data['mobile_no']); ?>" required>
                </div>
                <div class="form-group">
                    <label for="user_rights">User Rights:</label>
                    <select id="user_rights" name="user_rights" required>
                        <option value="Admin" <?php echo ($edit_user_data['user_rights'] == 'Admin') ? 'selected' : ''; ?>>Admin</option>
                        <option value="Super_user" <?php echo ($edit_user_data['user_rights'] == 'Super_user') ? 'selected' : ''; ?>>Super_user</option>
                        <option value="User" <?php echo ($edit_user_data['user_rights'] == 'User') ? 'selected' : ''; ?>>User</option>
                    </select>
                </div>
                <button type="submit">Update User</button>
            </form>
        </div>
    <?php endif; ?>

    <div class="back-link">
        <a href="user_add.php">Go to User Registration</a>
    </div>
</div>

</body>
</html>