<?php
require_once('db_connection.php');

if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}

/**
 * =========================
 * DASHBOARD STATS
 * =========================
 */
$stats_query = "
    SELECT 
        COUNT(*) AS total_students,
        COUNT(DISTINCT class_id) AS total_classes
    FROM students
";

$result = $conn->query($stats_query);

$stats = [
    'total_students' => 0,
    'total_classes' => 0
];

if ($result) {
    $stats = $result->fetch_assoc();
}

/**
 * =========================
 * FETCH STUDENTS
 * =========================
 */
$students = [];

$stmt = $conn->prepare("
    SELECT 
        s.student_id,
        s.name,
        s.class_id,
        s.regNumber,
        c.class_name,
        u.email
    FROM students s
    LEFT JOIN classes c ON s.class_id = c.class_id
    LEFT JOIN users u ON s.user_id = u.user_id
    ORDER BY s.name ASC
");

if ($stmt && $stmt->execute()) {
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $students[] = $row;
    }
    $stmt->close();
}

/**
 * =========================
 * FETCH CLASSES
 * =========================
 */
$class_list = [];

$class_query = $conn->query("
    SELECT class_id, class_name 
    FROM classes 
    ORDER BY class_name ASC
");

if ($class_query) {
    while ($row = $class_query->fetch_assoc()) {
        $class_list[] = $row;
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Management System</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

<style>
body {
    background: #f5f7ff;
    font-family: 'Poppins', sans-serif;
}

.card {
    border-radius: 10px;
    border: none;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
}

.card-header {
    background: #3a57e8;
    color: #fff;
    font-weight: 600;
}

.stats-card {
    text-align: center;
    padding: 20px;
    background: #fff;
    border-radius: 10px;
}

.stats-number {
    font-size: 26px;
    font-weight: bold;
    color: #3a57e8;
}

.student-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #3a57e8;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}
</style>
</head>

<body>

<div class="container py-4">

<!-- HEADER -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h3><i class="fas fa-user-graduate"></i> Student Management</h3>
        <small class="text-muted">Manage all students</small>
    </div>
    <div>
        <a href="add_student.php" class="btn btn-primary">+ Add Student</a>
        <a href="admin_dashboard.php" class="btn btn-outline-secondary">Dashboard</a>
    </div>
</div>

<!-- STATS -->
<div class="row mb-4">
    <div class="col-md-6">
        <div class="stats-card">
            <div class="stats-number"><?= $stats['total_students']; ?></div>
            <small>Total Students</small>
        </div>
    </div>

    <div class="col-md-6">
        <div class="stats-card">
            <div class="stats-number"><?= $stats['total_classes']; ?></div>
            <small>Total Classes</small>
        </div>
    </div>
</div>

<!-- TABLE -->
<div class="card">
    <div class="card-header d-flex justify-content-between">
        <span>Students List</span>
        <span class="badge bg-light text-dark"><?= $stats['total_students']; ?></span>
    </div>

    <div class="card-body">

        <!-- FILTER -->
        <div class="row mb-3">
            <div class="col-md-6">
                <input type="text" id="searchInput" class="form-control" placeholder="Search students...">
            </div>

            <div class="col-md-6">
                <select id="classFilter" class="form-select">
                    <option value="">Filter by Class</option>
                    <?php foreach ($class_list as $class): ?>
                        <option value="<?= htmlspecialchars($class['class_name']); ?>">
                            <?= htmlspecialchars($class['class_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <!-- TABLE -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead class="table-primary">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Class</th>
                        <th>Actions</th>
                    </tr>
                </thead>

                <tbody>
                <?php if (!empty($students)): ?>
                    <?php foreach ($students as $student): ?>
                        <?php
                            $initial = strtoupper(substr($student['name'], 0, 1));
                            $class_name = $student['class_name'] ?? 'Not Assigned';
                        ?>
                        <tr class="student-row"
                            data-name="<?= strtolower($student['name']); ?>"
                            data-email="<?= strtolower($student['email']); ?>"
                            data-class="<?= strtolower($class_name); ?>">

                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="student-avatar me-2"><?= $initial; ?></div>
                                    <?= htmlspecialchars($student['name']); ?>
                                </div>
                            </td>

                            <td><?= htmlspecialchars($student['email']); ?></td>

                            <td><?= htmlspecialchars($class_name); ?></td>

                            <td>
                                <a href="edit_student.php?id=<?= $student['student_id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                <a href="view_student.php?id=<?= $student['student_id']; ?>" class="btn btn-sm btn-info">View</a>
                                <a href="delete_student.php?id=<?= $student['student_id']; ?>" class="btn btn-sm btn-danger"
                                   onclick="return confirm('Delete student?')">
                                   Delete
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="4" class="text-center">No students found</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>

</div>

<script>
document.addEventListener("DOMContentLoaded", function () {

    const searchInput = document.getElementById("searchInput");
    const classFilter = document.getElementById("classFilter");
    const rows = document.querySelectorAll(".student-row");

    function filterTable() {

        const searchValue = searchInput.value.toLowerCase().trim();
        const classValue = classFilter.value.toLowerCase().trim();

        rows.forEach(row => {

            const name = row.dataset.name;
            const email = row.dataset.email;
            const studentClass = row.dataset.class;

            const matchesSearch =
                name.includes(searchValue) ||
                email.includes(searchValue);

            const matchesClass =
                classValue === "" || studentClass === classValue;

            row.style.display = (matchesSearch && matchesClass) ? "" : "none";
        });
    }

    searchInput.addEventListener("input", filterTable);
    classFilter.addEventListener("change", filterTable);

});
</script>

</body>
</html>