<?php
session_start();
if(!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true){
    header('Location: admin_login.php');
    exit;
}
require_once 'connectiondb.php';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

$error = '';
$success = '';

$stmt = $pdo->query("SELECT student_id, name, password_hash FROM students ORDER BY name ASC");
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['set_individual_password'])) {
        $student_id = $_POST['student_id'] ?? '';
        $password = $_POST['password'] ?? '';
        if (empty($student_id) || empty($password)) {
            $error = "Please select a student and enter a password.";
        } else {
            $stmt = $pdo->prepare("UPDATE students SET password_hash = ? WHERE student_id = ?");
            if ($stmt->execute([$password, $student_id])) {
                $success = "Password updated successfully for student ID: " . htmlspecialchars($student_id);
            } else {
                $error = "Failed to update password.";
            }
        }
    } elseif (isset($_POST['bulk_generate_passwords'])) {
        $selected_students = $_POST['selected_students'] ?? [];
        if (empty($selected_students)) {
            $error = "Please select at least one student for bulk password generation.";
        } else {
            $updated_count = 0;
            $failed_count = 0;
            foreach ($selected_students as $student_id) {
                $random_password = bin2hex(random_bytes(4)); // 8 character hex password
                $stmt = $pdo->prepare("UPDATE students SET password_hash = ? WHERE student_id = ?");
                if ($stmt->execute([$random_password, $student_id])) {
                    $updated_count++;
                    // Optionally, you can store or display the generated passwords for admin reference
                } else {
                    $failed_count++;
                }
            }
            $success = "Bulk password generation completed. Success: $updated_count, Failed: $failed_count.";
        }
    } elseif (isset($_POST['upload_csv_passwords'])) {
        if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
            $fileTmpPath = $_FILES['csv_file']['tmp_name'];
            $file = fopen($fileTmpPath, 'r');
            $header = fgetcsv($file);
            $expectedHeaders = ['student_id', 'password'];
            if ($header !== $expectedHeaders) {
                $error = "Invalid CSV format. Expected headers: student_id,password";
            } else {
                $updated_count = 0;
                $failed_count = 0;
                while (($row = fgetcsv($file)) !== false) {
                    if (count($row) === 2) {
                        list($student_id, $password) = $row;
                        $stmt = $pdo->prepare("UPDATE students SET password_hash = ? WHERE student_id = ?");
                        if ($stmt->execute([$password, $student_id])) {
                            $updated_count++;
                        } else {
                            $failed_count++;
                        }
                    } else {
                        $failed_count++;
                    }
                }
                fclose($file);
                $success = "CSV upload completed. Passwords updated: $updated_count, Failed: $failed_count.";
            }
        } else {
            $error = "Error uploading CSV file.";
        }
    }
} elseif (isset($_GET['download_csv_passwords'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="student_passwords.csv"');
    $output = fopen('php://output', 'w');
    fputcsv($output, ['student_id', 'name', 'password']);
    foreach ($students as $student) {
        fputcsv($output, [$student['student_id'], $student['name'], $student['password_hash']]);
    }
    fclose($output);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Set Student Passwords - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container my-4">
    <h2>Set Student Passwords</h2>
    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
    <?php endif; ?>

    <div class="row g-4">
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h3 class="card-title mb-0">Set Individual Password</h3>
                </div>
                <div class="card-body">
                    <form method="POST" action="admin_set_student_password.php">
                        <input type="hidden" name="set_individual_password" value="1">
                        <div class="mb-3">
                            <label for="student_id" class="form-label">Select Student</label>
                            <select class="form-select" id="student_id" name="student_id" required>
                                <option value="">-- Select Student --</option>
                                <?php foreach ($students as $student): ?>
                                    <option value="<?php echo htmlspecialchars($student['student_id']); ?>">
                                        <?php echo htmlspecialchars($student['name']) . " (" . htmlspecialchars($student['student_id']) . ")"; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">New Password</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">Set Password</button>
                    </form>
                </div>
            </div>
        </div>

    <div class="col-md-12">
        <div class="card shadow-sm">
            <div class="card-header bg-secondary text-white">
                <h3 class="card-title mb-0">Bulk Password Generation</h3>
            </div>
            <div class="card-body">
                <form method="POST" action="admin_set_student_password.php">
                    <input type="hidden" name="bulk_generate_passwords" value="1">
                    <div class="mb-3">
                        <label class="form-label">Select Students</label>
                        <div style="max-height: 300px; overflow-y: auto; border: 1px solid #ced4da; padding: 10px;">
                            <?php foreach ($students as $student): ?>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="selected_students[]" value="<?php echo htmlspecialchars($student['student_id']); ?>" id="student_<?php echo htmlspecialchars($student['student_id']); ?>">
                                    <label class="form-check-label" for="student_<?php echo htmlspecialchars($student['student_id']); ?>">
                                        <?php echo htmlspecialchars($student['name']) . " (" . htmlspecialchars($student['student_id']) . ")"; ?>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-secondary w-100">Generate Passwords for Selected Students</button>
                </form>
                <hr>
                <form method="GET" action="admin_set_student_password.php" class="mb-3">
                    <button type="submit" name="download_csv_passwords" value="1" class="btn btn-info w-100">Download Current Passwords CSV</button>
                </form>
                <form method="POST" action="admin_set_student_password.php" enctype="multipart/form-data">
                    <input type="hidden" name="upload_csv_passwords" value="1">
                    <div class="mb-3">
                        <label for="csv_file" class="form-label">Upload CSV to Update Passwords</label>
                        <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv" required>
                    </div>
                    <button type="submit" class="btn btn-success w-100">Upload CSV</button>
                </form>
            </div>
        </div>
    </div>
    </div>

    <div class="row mt-5">
        <div class="col-md-12">
            <div class="card shadow-sm">
                <div class="card-header bg-info text-white">
                    <h3 class="card-title mb-0">Current Password Status</h3>
                </div>
                <div class="card-body p-0">
                    <table id="passwordStatusTable" class="table table-bordered table-striped mb-0">
                        <thead>
                            <tr>
                                <th onclick="sortTable(0)">Student Name &#x25B2;&#x25BC;</th>
                                <th onclick="sortTable(1)">Student ID &#x25B2;&#x25BC;</th>
                                <th onclick="sortTable(2)">Password Status &#x25B2;&#x25BC;</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($students as $student): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($student['name']); ?></td>
                                <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                                <td><?php echo htmlspecialchars($student['password_hash']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
    function sortTable(columnIndex) {
        var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
        table = document.getElementById("passwordStatusTable");
        switching = true;
        dir = "asc"; 
        while (switching) {
            switching = false;
            rows = table.rows;
            for (i = 1; i < (rows.length - 1); i++) {
                shouldSwitch = false;
                x = rows[i].getElementsByTagName("TD")[columnIndex];
                y = rows[i + 1].getElementsByTagName("TD")[columnIndex];
                if (dir == "asc") {
                    if (x.textContent.toLowerCase() > y.textContent.toLowerCase()) {
                        shouldSwitch= true;
                        break;
                    }
                } else if (dir == "desc") {
                    if (x.textContent.toLowerCase() < y.textContent.toLowerCase()) {
                        shouldSwitch= true;
                        break;
                    }
                }
            }
            if (shouldSwitch) {
                rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                switching = true;
                switchcount ++;      
            } else {
                if (switchcount == 0 && dir == "asc") {
                    dir = "desc";
                    switching = true;
                }
            }
        }
    }
    </script>

</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
