<?php
include 'config.php';

// Handle adding new user
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'add_user') {
    $email = $_POST['email'];
    $category_id = $_POST['category_id'];

    if (!empty($email) && !empty($category_id)) {
        $sql = "INSERT INTO users (email, category_id, created_at) VALUES (?, ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $email, $category_id);

        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'User added successfully']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Error: ' . $stmt->error]);
        }

        $stmt->close();
    } else {
        echo json_encode(['status' => 'error', 'message' => 'All fields are required']);
    }
    exit;
}

// Handle adding new category
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'add_category') {
    $category_name = $_POST['category_name'];

    if (!empty($category_name)) {
        $sql = "INSERT INTO categories (category_name) VALUES (?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $category_name);

        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'Category added successfully']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Error: ' . $stmt->error]);
        }

        $stmt->close();
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Category name is required']);
    }
    exit;
}

// Fetch categories for the form dropdown
$sql_categories = "SELECT category_id, category_name FROM categories";
$result_categories = $conn->query($sql_categories);
$categories = [];
while ($row = $result_categories->fetch_assoc()) {
    $categories[] = $row;
}

// Pagination settings
$records_per_page = 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$start_from = ($page - 1) * $records_per_page;

// Handle search query
$search_query = isset($_GET['search']) ? $_GET['search'] : '';
$search_sql = '';
if (!empty($search_query)) {
    $search_sql = " WHERE email LIKE '%$search_query%' OR category_name LIKE '%$search_query%'";
}

// SQL query to fetch users with their categories and apply search query
$sql = "SELECT users.user_id, users.email, users.created_at, categories.category_name 
        FROM users 
        JOIN categories ON users.category_id = categories.category_id" . $search_sql . 
        " LIMIT $start_from, $records_per_page";
$result = $conn->query($sql);

// Get total number of records for pagination
$sql_total_records = "SELECT COUNT(*) FROM users JOIN categories ON users.category_id = categories.category_id" . $search_sql;
$result_total_records = $conn->query($sql_total_records);
$total_records = $result_total_records->fetch_row()[0];
$total_pages = ceil($total_records / $records_per_page);
?>



<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">
    <title>Users</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function () {
            const topics = <?= json_encode($topics); ?>;
            $('#category_id_question').change(function () {
                const categoryId = $(this).val();
                const filteredTopics = topics.filter(topic => topic.category_id == categoryId);
                $('#topic_id').empty().append('<option value="">Select Topic</option>');
                filteredTopics.forEach(topic => {
                    $('#topic_id').append(`<option value="${topic.topic_id}">${topic.topic_name}</option>`);
                });
            });
        });
    </script>
    <script src="https://unpkg.com/@dotlottie/player-component@latest/dist/dotlottie-player.mjs" type="module"></script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="Responsive Admin &amp; Dashboard Template based on Bootstrap 5">
    <meta name="author" content="AdminKit">
    <meta name="keywords"
        content="adminkit, bootstrap, bootstrap 5, admin, dashboard, template, responsive, css, sass, html, theme, front-end, ui kit, web">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="shortcut icon" href="img/icons/icon-48x48.png" />

    <link rel="canonical" href="https://demo-basic.adminkit.io/" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

    <title>kijani quizes</title>

    <link href="css/app.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap" rel="stylesheet">

    <style>
        @keyframes spin {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }

        .fa-spin {
            animation: spin 2s infinite linear;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <nav id="sidebar" class="sidebar js-sidebar">
            <div class="sidebar-content js-simplebar">
                <a class="sidebar-brand" href="index.php">
                    <span class="align-middle">Kijani Admin</span>
                </a>

                <ul class="sidebar-nav">
                    <li class="sidebar-header">
                        Pages
                    </li>

                    <li class="sidebar-item  ">
                        <a class="sidebar-link" href="index.php">
                            <i class="align-middle" data-feather="sliders"></i> <span
                                class="align-middle">Dashboard</span>
                        </a>
                    </li>

                    <li class="sidebar-item  ">
                        <a class="sidebar-link" href="create_questions.php">
                            <i class="align-middle" data-feather="book"></i> <span class="align-middle">create
                                questions</span>
                        </a>
                    </li>
					<li class="sidebar-item">
                        <a class="sidebar-link" href="view_results.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">view quiz Results</span>
                        </a>
                    </li>
                    
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="edit_questions.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">Edit Quiz</span>
                        </a>
                    </li>
                    <li class="sidebar-item active">
                        <a class="sidebar-link" href="users.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">Users</span>
                        </a>
                    </li>
                    <li class="sidebar-item  ">
                        <a class="sidebar-link" href="bulk_upload.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">Bulk upload</span>
                        </a>
                    </li>

            
                </ul>


            </div>
        </nav>

        <div class="main">
            <nav class="navbar navbar-expand navbar-light navbar-bg">
                <a class="sidebar-toggle js-sidebar-toggle">
                    <i class="hamburger align-self-center"></i>
                </a>

                <div class="navbar-collapse collapse">
                    <ul class="navbar-nav navbar-align">
                         
                        <li class="nav-item dropdown">
                            <a class="nav-icon dropdown-toggle d-inline-block d-sm-none" href="#"
                                data-bs-toggle="dropdown">
                                <i class="align-middle" data-feather="settings"></i>
                            </a>

                            <a class="nav-link dropdown-toggle d-none d-sm-inline-block" href="#"
                                data-bs-toggle="dropdown">
                                <img src="img/avatars/avatar.jpg" class="avatar img-fluid rounded me-1"
                                    alt="Charles Hall" /> <span class="text-dark">user</span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-end">
                                <a class="dropdown-item" href="pages-profile.html"><i class="align-middle me-1"
                                        data-feather="user"></i> Profile</a>
                                <a class="dropdown-item" href="#"><i class="align-middle me-1"
                                        data-feather="pie-chart"></i> Analytics</a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="index.html"><i class="align-middle me-1"
                                        data-feather="settings"></i> Settings & Privacy</a>
                                <a class="dropdown-item" href="#"><i class="align-middle me-1"
                                        data-feather="help-circle"></i> Help Center</a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="#">Log out</a>
                            </div>
                        </li>
                    </ul>
                </div>
            </nav>

            <main class="content">

                <div class="container-fluid p-0">

				
                <div class="container mt-1">
    <h1 class="card-header mb-4">Manage Users and Categories</h1>

    <!-- Form for adding new user -->
   <!-- Button to trigger modal -->


<!-- Modal structure -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addUserModalLabel">Add New User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="card mb-3">
          <div class="card-body">
            <form id="add-user-form">
              <div class="form-group mb-3">
                <label for="email">Email</label>
                <input type="email" class="form-control" id="email" name="email" required>
              </div>
              <div class="form-group mb-3">
                <label for="category_id">Category</label>
                <select class="form-control" id="category_id" name="category_id" required>
                  <option value="">Select a category</option>
                  <?php foreach ($categories as $category): ?>
                      <option value="<?php echo $category['category_id']; ?>"><?php echo $category['category_name']; ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <button type="submit" class="btn btn-info">Add User</button>
            </form>
            <div id="add-user-message"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Include Bootstrap JS and dependencies (Popper.js) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js"></script>


    <!-- Form for adding new category -->
     
    <!-- Button to trigger the Add Category modal -->


<!-- Modal structure for Add Category -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" aria-labelledby="addCategoryModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addCategoryModalLabel">Add New Category</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="card mb-3">
          <div class="card-body">
            <form id="add-category-form">
              <div class="form-group mb-3">
                <label for="category_name">Category Name</label>
                <input type="text" class="form-control" id="category_name" name="category_name" required>
              </div>
              <button type="submit" class="btn btn-info">Add Category</button>
            </form>
            <div id="add-category-message"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Include Bootstrap JS and dependencies (Popper.js) if not already included -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js"></script>


    <!-- Display users with their categories -->
   <div class="card mb-3">
        <div class="card-header">
            <h2 class="card-title">Users</h2>
        </div>
        <div class= "row p-3 mb-2">
            <div class="col-md-4">
        <button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#addUserModal"><i class="fas fa-user"></i>
  Open Add User Form
</button></div>
<div class="col-md-4">
<button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#addCategoryModal"><i class="fas fa-folder"></i>
  Open Add Category Form
</button></div>
</div>
        <div class="card-body">
        <form method="get" action="" class="form-inline mb-3 ">
                <input type="text" class="form-control mr-2" name="search" placeholder="Search users" value="<?php echo $search_query; ?>">
                <button type="submit" class="btn btn-info"><i class="fas fa-search"></i>Search</button>
            </form>
    <table class="table   table-striped table-hover">
        <thead>
            <tr>
                <th>User ID</th>
                <th>Email</th>
                <th>Category</th>
                <th>Created At</th>
            </tr>
        </thead>
        <?php $user_number = 1; ?>
        <tbody id="user-table">
                    <?php if ($result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo $row['user_id'] ?></td>
                                <td><?php echo $row['email']; ?></td>
                                <td><?php echo $row['category_name']; ?></td>
                                <td><?php echo $row['created_at']; ?></td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="4">No users found</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
    </table>
  <!-- Pagination -->
  <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center ">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php if ($i == $page) echo 'active'; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo $search_query; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
</div></div>
</div>
                         
                    </div>
            </main>

            <footer class="footer">
                <div class="container-fluid">
                    <div class="row text-muted">
                        <div class="col-6 text-start">
                            <p class="mb-0">
                                <a class="text-muted" href="https://adminkit.io/" target="_blank"><strong>kijani
                                        forestry</strong></a> - <a class="text-muted" href="https://adminkit.io/"
                                    target="_blank"><strong>jonathan</strong></a> &copy;
                            </p>
                        </div>
                        <div class="col-6 text-end">
                            <ul class="list-inline">
                                <li class="list-inline-item">
                                    <a class="text-muted" href="https://adminkit.io/" target="_blank">Support</a>
                                </li>
                                <li class="list-inline-item">
                                    <a class="text-muted" href="https://adminkit.io/" target="_blank">Help Center</a>
                                </li>
                                <li class="list-inline-item">
                                    <a class="text-muted" href="https://adminkit.io/" target="_blank">Privacy</a>
                                </li>
                                <li class="list-inline-item">
                                    <a class="text-muted" href="https://adminkit.io/" target="_blank">Terms</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </footer>
        </div>
    </div>

    <script src="js/app.js"></script>
 
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            var date = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000);
            var defaultDate = date.getUTCFullYear() + "-" + (date.getUTCMonth() + 1) + "-" + date.getUTCDate();
            document.getElementById("datetimepicker-dashboard").flatpickr({
                inline: true,
                prevArrow: "<span title=\"Previous month\">&laquo;</span>",
                nextArrow: "<span title=\"Next month\">&raquo;</span>",
                defaultDate: defaultDate
            });
        });
    </script>
    <script>
$(document).ready(function() {
    $('#add-user-form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: '',
            type: 'post',
            data: $(this).serialize() + '&action=add_user',
            success: function(response) {
                const res = JSON.parse(response);
                $('#add-user-message').html('<div class="alert alert-' + (res.status == 'success' ? 'success' : 'danger') + '">' + res.message + '</div>');
            }
        });
    });

    $('#add-category-form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: '',
            type: 'post',
            data: $(this).serialize() + '&action=add_category',
            success: function(response) {
                const res = JSON.parse(response);
                $('#add-category-message').html('<div class="alert alert-' + (res.status == 'success' ? 'success' : 'danger') + '">' + res.message + '</div>');
            }
        });
    });
});
</script>

</body>

</html>