<?php
include 'db.php'; // Database connection

// Handle single user addition
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_user'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = password_hash('2025', PASSWORD_BCRYPT); // Set default password "2024"
    $category_id = $_POST['category_id'];

    $stmt = $pdo->prepare("INSERT INTO users (name, email, password, category_id) VALUES (?, ?, ?, ?)");
    if ($stmt->execute([$name, $email, $password, $category_id])) {
        $successMessage = "User added successfully!";
    } else {
        $errorMessage = "Error adding user.";
    }
}

// Handle bulk upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['bulk_upload'])) {
    // Check if the file was uploaded
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
        // Open the file
        $file = fopen($_FILES['csv_file']['tmp_name'], 'r');
        
        // Check if the file was successfully opened
        if ($file !== false) {
            // Read and insert each row
            $successCount = 0;
            $errorCount = 0;
            $errorRows = [];

            while (($line = fgetcsv($file)) !== false) {
                // Check if the line has the correct number of columns (name, email, category_id)
                if (count($line) < 3) {
                    $errorRows[] = $line;
                    $errorCount++;
                    continue;
                }

                $name = $line[0];
                $email = $line[1];
                $category_id = $line[2];
                $password = password_hash('2025', PASSWORD_BCRYPT); // Default password "2024"

                // Insert into the database
                try {
                    $stmt = $pdo->prepare("INSERT INTO users (name, email, password, category_id) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$name, $email, $password, $category_id]);
                    $successCount++;
                } catch (Exception $e) {
                    // If there's an error inserting the user, track it
                    $errorCount++;
                    $errorRows[] = $line;
                }
            }

            // Close the file
            fclose($file);

            // Display success and error messages
            if ($successCount > 0) {
                $successMessage = "$successCount users uploaded successfully!";
            }
            if ($errorCount > 0) {
                $errorMessage = " ";
            }
        } else {
            $errorMessage = "Failed to open CSV file.";
        }
    } else {
        $errorMessage = "Error uploading CSV file.";
    }
}

// Fetch categories for the form dropdown
$categories = $pdo->query("SELECT id, name FROM categories")->fetchAll(PDO::FETCH_ASSOC);

?>

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

<head>
    <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>
        .chart-container {
            max-width: 600px;
            margin: auto;
            margin-bottom: 50px;
            height: 400px;
        }
    </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="categoriesandtopic.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">add category and topic</span>
                        </a>
                    </li>
                    
                    <li class="sidebar-item  ">
                        <a class="sidebar-link" href="add_question.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="viewusersscores.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="all_questions.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">View Questions</span>
                        </a>
                    </li>
                    <li class="sidebar-item active ">
                        <a class="sidebar-link" href="add_user.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">Add Users</span>
                        </a>
                    </li>
                     <li class="sidebar-item  ">
                        <a class="sidebar-link" href="viewusers.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">view Users</span>
                        </a>
                    </li>
                     <li class="sidebar-item ">
                        <a class="sidebar-link" href="quiz_management.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">Quiz management</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" href="#" id="alertsDropdown" data-bs-toggle="dropdown">
                                 <div class="position-relative">
                                    <i class="align-middle" data-feather="bell"></i>
                                    <span class="indicator">4</span>
                                </div> -->
                            </a>
                            <div class="dropdown-menu dropdown-menu-lg dropdown-menu-end py-0" aria-labelledby="alertsDropdown">
                                 
                                <div class="list-group">
                                    <a href="#" class="list-group-item">
                                        <div class="row g-0 align-items-center">
                                            <div class="col-2">
                                                <i class="text-danger" data-feather="alert-circle"></i>
                                            </div>
                                            <!-- <div class="col-10">
                                                <div class="text-dark">Update completed</div>
                                                <div class="text-muted small mt-1">Restart server 12 to complete the update.</div>
                                                <div class="text-muted small mt-1">30m ago</div>
                                            </div> -->
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item">
                                        <div class="row g-0 align-items-center">
                                            <div class="col-2">
                                                <i class="text-warning" data-feather="bell"></i>
                                            </div>
                                            <!-- <div class="col-10">
                                                <div class="text-dark">Lorem ipsum</div>
                                                <div class="text-muted small mt-1">Aliquam ex eros, imperdiet vulputate hendrerit et.</div>
                                                <div class="text-muted small mt-1">2h ago</div>
                                            </div> -->c
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item">
                                        <div class="row g-0 align-items-cetnter">
                                            <div class="col-2">
                                                <i class="text-primary" data-feather="home"></i>
                                            </div>
                                            <!-- <div class="col-10">
                                                <div class="text-dark">Login from 192.186.1.1</div>
                                                <div class="text-muted small mt-1">5h ago</div>
                                            </div> -->
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item">
                                        <div class="row g-0 align-items-center">
                                            <div class="col-2">
                                                <i class="text-success" data-feather="user-plus"></i>
                                            </div>
                                            <!-- <div class="col-10">
                                                <div class="text-dark">New connection</div>
                                                <div class="text-muted small mt-1">Christina accepted your request.</div>
                                                <div class="text-muted small mt-1">14h ago</div>
                                            </div> -->
                                        </div>
                                    </a>
                                </div>
                            </div>
                        </li>
                        <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/kijanilogo.png" class="avatar img-fluid rounded me-1" alt=" " />
                                <span class="text-dark">kijani admin</span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-end">
                                <a class="dropdown-item" href="profile.php">
                                    <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="settings.php"><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">
                    <h1 class="h3 mb-3">Dashboard</h1>
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title">Add user</h5>
                                    <h6 class="card-subtitle text-muted"> </h6>
                                </div>
                                 <?php if (isset($successMessage)): ?>
        <div class="alert alert-success">
            <?php echo $successMessage; ?>
        </div>
    <?php elseif (isset($errorMessage)): ?>
        <div class="alert alert-danger">
            <?php echo $errorMessage; ?>
        </div>
    <?php endif; ?>
                                <div class="card-body">
                                    <form method="POST" class="mb-4">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" name="name" required>
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">Email</label>
            <input type="email" class="form-control" id="email" name="email" required>
        </div>
        <div class="mb-3">
            <label for="category" class="form-label">Category</label>
            <select class="form-select" id="category" name="category_id" required>
                <option selected disabled>Select Category</option>
                <?php foreach ($categories as $category): ?>
                    <option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" name="add_user" class="btn btn-primary">Add User</button>
    </form>
 
 
 
 
 
  
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-12">
                            
                        </div>
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h2>bulk upload</h2>
                                </div>
                                 <?php if (isset($successMessage)): ?>
        <div class="alert alert-success">
            <?php echo $successMessage; ?>
        </div>
    <?php endif; ?>

    <?php if (isset($errorMessage)): ?>
        <div class="alert alert-danger">
            <?php echo $errorMessage; ?>
            <?php if (!empty($errorRows)): ?>
                <p>Failed Rows:</p>
                <ul>
                    <?php foreach ($errorRows as $row): ?>
                        <li><?php echo implode(', ', $row); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </div>
    <?php endif; ?>
                                <div class="card-body">
                                     <form method="POST" enctype="multipart/form-data">
        <div class="mb-3">
            <label for="csv_file" class="form-label">CSV File</label>
            <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv" required>
        </div>
        <button type="submit" name="bulk_upload" class="btn btn-success">Upload CSV</button>
    </form>
                                  
                        

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="js/app.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
     
</body>
</html>
