<?php
session_start();
if (!isset($_SESSION["admin"]) || $_SESSION["admin"] !== true) {
    header("location:login.php");
    exit;
}
include('header.php');
require_once 'connection.php';

function addUser($conn, $name, $pass, $usertype) {
    // Check for duplication
    $checkQuery = "SELECT ID FROM userstbl WHERE username = ?";
    $stmt = $conn->prepare($checkQuery);
    $stmt->bind_param("s", $name);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        return "Username already exists.";
    }
    
    // Prepared statement to insert new user
    $hashed_pass = md5($pass); // For better security, consider using password_hash
    $insertQuery = "INSERT INTO userstbl (username, userpass, user_type) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($insertQuery);
    $stmt->bind_param("sss", $name, $hashed_pass, $usertype);
    
    if ($stmt->execute()) {
        return "User added successfully.";
    } else {
        return "Error adding user: " . $conn->error;
    }
}

function updateUser($conn, $id, $name, $pass, $usertype) {
    // Prepared statement to update user
    $hashed_pass = md5($pass); // For better security, consider using password_hash
    $updateQuery = "UPDATE userstbl SET username = ?, userpass = ?, user_type = ? WHERE ID = ?";
    $stmt = $conn->prepare($updateQuery);
    $stmt->bind_param("sssi", $name, $hashed_pass, $usertype, $id);
    
    if ($stmt->execute()) {
        return "User updated successfully.";
    } else {
        return "Error updating user: " . $conn->error;
    }
}

function deleteUser($conn, $id) {
    // Prepared statement to delete user
    $deleteQuery = "DELETE FROM userstbl WHERE ID = ?";
    $stmt = $conn->prepare($deleteQuery);
    $stmt->bind_param("i", $id);
    
    if ($stmt->execute()) {
        return "User deleted successfully.";
    } else {
        return "Error deleting user: " . $conn->error;
    }
}

$message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST["action"])) {
        $action = $_POST["action"];
        $name = trim($_POST["username"]);
        $pass = trim($_POST["userpass"]);
        $usertype = trim($_POST["user_type"]);

        if ($action == "add") {
            $message = addUser($conn, $name, $pass, $usertype);
        } elseif ($action == "update") {
            $id = trim($_POST["uid"]);
            $message = updateUser($conn, $id, $name, $pass, $usertype);
        } elseif ($action == "delete") {
            $id = trim($_POST["uid"]);
            $message = deleteUser($conn, $id);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management</title>
    <style>
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: #333;
        }

        li {
            float: left;
        }

        li a {
            display: block;
            color: white;
            border-radius: 13px;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
        }

        li a:hover:not(.active) {
            background-color: #111;
        }

        .active {
            background-color: #04AA6D;
        }

        table {
            width: 98%;
            text-align: center;
            border: 1px solid navy;
            margin-top: 20px;
        }

        th, td {
            padding: 10px;
        }

        th {
            background-color: darkgreen;
            color: white;
        }

        td {
            border-bottom: 0.5px solid black;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
        }

        .btn {
            background-color: navy;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
        }

        .btn:hover {
            background-color: #0056b3;
        }

        .message {
            text-align: center;
            color: red;
        }
    </style>
</head>
<body>
    <?php if ($message) : ?>
        <p class="message"><?php echo htmlspecialchars($message); ?></p>
    <?php endif; ?>
    
    <div class="center">
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <h4>Add or Update User</h4><br>
            <input type="hidden" name="uid" id="uid">
            <input type="text" name="username" id="username" placeholder="User Name" class="form-control" required><br>
            <input type="password" name="userpass" id="userpass" placeholder="Password" class="form-control" required><br>
            <input type="text" name="user_type" id="user_type" placeholder="User Type (admin/official)" class="form-control" required><br>
            <input type="submit" name="action" value="add" class="btn">
            <input type="submit" name="action" value="update" class="btn">
            <button type="reset" class="btn" onclick="resetForm()">Reset</button>
        </form>
    </div>
    
    <table>
        <tr>
            <th>User Name</th>
            <th>Password</th>
            <th>Type</th>
            <th>Update</th>
            <th>Delete</th>
        </tr>

        <?php
        $q1 = "SELECT * FROM userstbl";
        $result = $conn->query($q1);
        if (!empty($result) && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo '<tr>';
                echo '<td>' . htmlspecialchars($row["username"]) . '</td>';
                echo '<td>' . htmlspecialchars($row["userpass"]) . '</td>';
                echo '<td>' . htmlspecialchars($row["user_type"]) . '</td>';
                echo '<td>';
                echo '<button type="button" class="btn" onclick="fillForm(\'' . htmlspecialchars($row["ID"]) . '\', \'' . htmlspecialchars($row["username"]) . '\', \'' . htmlspecialchars($row["userpass"]) . '\', \'' . htmlspecialchars($row["user_type"]) . '\')">Edit</button>';
                echo '</td>';
                echo '<td>';
                echo '<form style="display:inline-block;" action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '" method="post">';
                echo '<input type="hidden" name="uid" value="' . htmlspecialchars($row["ID"]) . '">';
                echo '<input type="submit" name="action" value="delete" class="btn">';
                echo '</form>';
                echo '</td>';
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="5">No users found.</td></tr>';
        }

        $conn->close();
        ?>
    </table>

    <script>
        function fillForm(id, username, userpass, usertype) {
            document.getElementById("uid").value = id;
            document.getElementById("username").value = username;
            document.getElementById("userpass").value = userpass;
            document.getElementById("user_type").value = usertype;
        }

        function resetForm() {
            document.getElementById("uid").value = "";
            document.getElementById("username").value = "";
            document.getElementById("userpass").value = "";
            document.getElementById("user_type").value = "";
        }
    </script>
</body>
</html>
