<link rel="icon" href="logo.jpg" type="image/jpg">
<?php
// File: users.php
// Page for the main administrator to manage other user accounts with profile pictures.
require_once "db.php";
check_login();

// Security: Only the user with ID 1 (the main admin) can access this page.
if ($_SESSION['user_id'] != 1) {
    header("Location: dashboard.php");
    exit;
}

$page_title = "User Management";
$error_message = '';
$success_message = '';
$user_to_edit = null;

// Function to handle image upload
function upload_profile_image($file) {
    $target_dir = "uploads/";
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0755, true);
    }
    // Create a unique filename to avoid overwriting
    $filename = uniqid() . '_' . basename($file["name"]);
    $target_file = $target_dir . $filename;
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if image file is a actual image or fake image
    $check = getimagesize($file["tmp_name"]);
    if($check === false) {
        return ['error' => "File is not an image."];
    }

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        return ['error' => "Sorry, only JPG, JPEG, PNG & GIF files are allowed."];
    }

    // Attempt to upload file
    if (move_uploaded_file($file["tmp_name"], $target_file)) {
        return ['filename' => $filename];
    } else {
        return ['error' => "Sorry, there was an error uploading your file."];
    }
}


// Handle ADDING a new user
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_user'])) {
    $name = trim($_POST['name']);
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $profile_image_name = 'default.png';

    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
        $upload_result = upload_profile_image($_FILES['profile_image']);
        if (isset($upload_result['filename'])) {
            $profile_image_name = $upload_result['filename'];
        } else {
            $error_message = $upload_result['error'];
        }
    }

    if (empty($name) || empty($username) || empty($password)) {
        $error_message = "All fields are required.";
    } elseif (empty($error_message)) {
        // Continue with user creation
        $stmt_check = $conn->prepare("SELECT id FROM users WHERE username = ?");
        $stmt_check->bind_param("s", $username);
        $stmt_check->execute();
        $stmt_check->store_result();
        if ($stmt_check->num_rows > 0) {
            $error_message = "Error: This username already exists.";
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt_add = $conn->prepare("INSERT INTO users (name, username, password, profile_image) VALUES (?, ?, ?, ?)");
            $stmt_add->bind_param("ssss", $name, $username, $hashed_password, $profile_image_name);
            if ($stmt_add->execute()) {
                $success_message = "New user added successfully!";
            } else {
                $error_message = "Error adding user: " . $stmt_add->error;
            }
            $stmt_add->close();
        }
        $stmt_check->close();
    }
}

// Handle UPDATING a user
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_user'])) {
    $user_id = $_POST['user_id'];
    $name = trim($_POST['name']);
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $profile_image_name = $_POST['current_image']; // Keep old image by default

    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
        $upload_result = upload_profile_image($_FILES['profile_image']);
        if (isset($upload_result['filename'])) {
            $profile_image_name = $upload_result['filename'];
            // Optional: delete old image if it's not the default one
            if ($_POST['current_image'] != 'default.png' && file_exists('uploads/' . $_POST['current_image'])) {
                unlink('uploads/' . $_POST['current_image']);
            }
        } else {
            $error_message = $upload_result['error'];
        }
    }
    
    if (empty($error_message)) {
        if (!empty($password)) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt_update = $conn->prepare("UPDATE users SET name = ?, username = ?, password = ?, profile_image = ? WHERE id = ?");
            $stmt_update->bind_param("ssssi", $name, $username, $hashed_password, $profile_image_name, $user_id);
        } else {
            $stmt_update = $conn->prepare("UPDATE users SET name = ?, username = ?, profile_image = ? WHERE id = ?");
            $stmt_update->bind_param("sssi", $name, $username, $profile_image_name, $user_id);
        }
        if ($stmt_update->execute()) {
            $success_message = "User updated successfully!";
            // Update session if editing self
            if ($user_id == $_SESSION['user_id']) {
                $_SESSION['name'] = $name;
                $_SESSION['profile_image'] = $profile_image_name;
            }
        } else {
            $error_message = "Error updating user.";
        }
        $stmt_update->close();
    }
}


// Handle DELETING a user (with password verification)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['confirm_delete'])) {
    $delete_id = $_POST['delete_id'];
    $admin_password = $_POST['admin_password'];

    $stmt_pass = $conn->prepare("SELECT password FROM users WHERE id = ?");
    $stmt_pass->bind_param("i", $_SESSION['user_id']);
    $stmt_pass->execute();
    $result_pass = $stmt_pass->get_result();
    $admin_user = $result_pass->fetch_assoc();

    if ($admin_user && password_verify($admin_password, $admin_user['password'])) {
        if ($delete_id == 1) {
            $error_message = "Error: The main administrator account cannot be deleted.";
        } else {
            $stmt_delete = $conn->prepare("DELETE FROM users WHERE id = ?");
            $stmt_delete->bind_param("i", $delete_id);
            if ($stmt_delete->execute()) {
                $success_message = "User has been deleted successfully.";
            } else {
                $error_message = "Error deleting user.";
            }
            $stmt_delete->close();
        }
    } else {
        $error_message = "Incorrect password. Deletion failed.";
    }
    $stmt_pass->close();
}


// Check if we are editing a user to pre-fill the form
if (isset($_GET['edit_id'])) {
    $edit_id = $_GET['edit_id'];
    $stmt_edit = $conn->prepare("SELECT id, name, username, profile_image FROM users WHERE id = ?");
    $stmt_edit->bind_param("i", $edit_id);
    $stmt_edit->execute();
    $result_edit = $stmt_edit->get_result();
    if ($result_edit->num_rows > 0) {
        $user_to_edit = $result_edit->fetch_assoc();
    }
    $stmt_edit->close();
}

include 'header.php';
?>

<div class="main-content">
    <div class="page-header">
        <h1>User Management</h1>
        <p>Add, edit, or remove administrator accounts.</p>
    </div>

    <!-- Add/Edit User Form in a Card -->
    <div class="card form-container">
        <h2 class="card-title"><?php echo $user_to_edit ? 'Edit User' : 'Add New User'; ?></h2>

        <?php if($error_message): ?><div class="alert alert-danger"><?php echo $error_message; ?></div><?php endif; ?>
        <?php if($success_message): ?><div class="alert alert-success"><?php echo $success_message; ?></div><?php endif; ?>

        <form action="users.php" method="post" enctype="multipart/form-data">
            <?php if ($user_to_edit): ?>
                <input type="hidden" name="user_id" value="<?php echo $user_to_edit['id']; ?>">
                <input type="hidden" name="current_image" value="<?php echo htmlspecialchars($user_to_edit['profile_image']); ?>">
            <?php endif; ?>

            <div class="form-grid">
                <div class="form-group">
                    <label for="name">Full Name</label>
                    <input type="text" id="name" name="name" class="form-control" value="<?php echo htmlspecialchars($user_to_edit['name'] ?? ''); ?>" required>
                </div>
                <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" id="username" name="username" class="form-control" value="<?php echo htmlspecialchars($user_to_edit['username'] ?? ''); ?>" required>
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" id="password" name="password" class="form-control" <?php echo $user_to_edit ? '' : 'required'; ?>>
                    <?php if ($user_to_edit): ?>
                        <small style="color: #6c757d;">Leave blank to keep the current password.</small>
                    <?php endif; ?>
                </div>
                <div class="form-group">
                    <label for="profile_image">Profile Picture</label>
                    <input type="file" id="profile_image" name="profile_image" class="form-control">
                    <?php if ($user_to_edit && $user_to_edit['profile_image']): ?>
                        <div style="margin-top: 10px;">
                            <img src="uploads/<?php echo htmlspecialchars($user_to_edit['profile_image']); ?>" alt="Current Profile Picture" class="profile-pic-preview">
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="form-actions">
                <?php if ($user_to_edit): ?>
                    <button type="submit" name="update_user" class="btn btn-primary">Update User</button>
                    <a href="users.php" class="btn btn-secondary">Cancel Edit</a>
                <?php else: ?>
                    <button type="submit" name="add_user" class="btn btn-primary">Add User</button>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- User List in a Card -->
    <div class="card">
        <h2 class="card-title">Admin Accounts</h2>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Profile</th>
                        <th>Name</th>
                        <th>Username</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                        $result = $conn->query("SELECT id, name, username, profile_image FROM users ORDER BY name ASC");
                        if ($result->num_rows > 0) {
                            while($row = $result->fetch_assoc()) {
                                $profile_pic_path = 'uploads/' . htmlspecialchars($row['profile_image']);
                                echo "<tr>";
                                echo "<td><img src='{$profile_pic_path}' alt='Profile' class='profile-pic-table'></td>";
                                echo "<td>" . htmlspecialchars($row['name']) . "</td>";
                                echo "<td>" . htmlspecialchars($row['username']) . "</td>";
                                echo "<td>";
                                if ($row['id'] == 1) {
                                    echo "<a href='users.php?edit_id=" . $row['id'] . "' class='btn btn-secondary btn-sm'><i class='fas fa-edit'></i> Edit</a> ";
                                    echo "<span class='btn btn-sm' style='cursor: not-allowed; background-color: #eee; color: #999;' title='Main admin cannot be deleted.'><i class='fas fa-trash'></i> Delete</span>";
                                } else {
                                    echo "<a href='users.php?edit_id=" . $row['id'] . "' class='btn btn-secondary btn-sm'><i class='fas fa-edit'></i> Edit</a> ";
                                    echo "<button type='button' class='btn btn-danger btn-sm delete-btn' data-id='" . $row['id'] . "' data-name='" . htmlspecialchars($row['name']) . "'><i class='fas fa-trash'></i> Delete</button>";
                                }
                                echo "</td>";
                                echo "</tr>";
                            }
                        }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>Confirm Deletion</h2>
        </div>
        <form action="users.php" method="post">
            <div class="modal-body">
                <p>Are you sure you want to delete the user <strong id="deleteUserName"></strong>? This action requires you to enter your password.</p>
                <input type="hidden" name="delete_id" id="deleteUserId">
                <div class="form-group">
                    <label for="admin_password_delete">Your Password</label>
                    <input type="password" name="admin_password" id="admin_password_delete" class="form-control" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeDeleteModal()">Cancel</button>
                <button type="submit" name="confirm_delete" class="btn btn-danger">Confirm Delete</button>
            </div>
        </form>
    </div>
</div>

<script>
    const deleteModal = document.getElementById('deleteModal');
    const deleteUserName = document.getElementById('deleteUserName');
    const deleteUserId = document.getElementById('deleteUserId');

    document.querySelectorAll('.delete-btn').forEach(button => {
        button.addEventListener('click', function() {
            const userId = this.getAttribute('data-id');
            const userName = this.getAttribute('data-name');
            
            deleteUserName.textContent = userName;
            deleteUserId.value = userId;
            deleteModal.style.display = 'block';
        });
    });

    function closeDeleteModal() {
        deleteModal.style.display = 'none';
    }

    window.onclick = function(event) {
        if (event.target == deleteModal) {
            closeDeleteModal();
        }
    }
</script>

<?php include 'footer.php'; ?>

