<?php
session_start();
ob_start(); 
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";
$userlogin = $_SESSION['email'];
$email = $_SESSION['email'];
$role = $_SESSION['role'];
$intake = $_SESSION['department'];

if (isset($_SESSION['email'])){ 
    // Handle filtering
    $filter_intake = isset($_GET['filter_intake']) ? $_GET['filter_intake'] : '';
    $filter_program = isset($_GET['filter_program']) ? $_GET['filter_program'] : '';
    
    // Build query based on filters
    $where_conditions = [];
    if (!empty($filter_intake)) {
        $where_conditions[] = "intake = '$filter_intake'";
    }
    if (!empty($filter_program)) {
        $where_conditions[] = "program = '$filter_program'";
    }
    
    $where_clause = '';
    if (!empty($where_conditions)) {
        $where_clause = "WHERE " . implode(' AND ', $where_conditions);
    }
    
    // Get totals for statistics
    $total_students_query = mysqli_query($conn, "SELECT COUNT(*) as total FROM students");
    $total_students = mysqli_fetch_assoc($total_students_query)['total'];
    
    $filtered_students_query = mysqli_query($conn, "SELECT COUNT(*) as total FROM students $where_clause");
    $filtered_students = mysqli_fetch_assoc($filtered_students_query)['total'];
    
    // Get distinct intakes and programs for filter dropdowns
    $intakes_query = mysqli_query($conn, "SELECT DISTINCT intake FROM students ORDER BY intake DESC");
    $programs_query = mysqli_query($conn, "SELECT DISTINCT program FROM students ORDER BY program ASC");
    
    // Get count by program for statistics
    $program_stats_query = mysqli_query($conn, "SELECT program, COUNT(*) as count FROM students GROUP BY program ORDER BY count DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Management</title>

<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&family=Source+Sans+Pro:wght@300;400;600&display=swap" rel="stylesheet">

<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<!-- Favicon -->
<link rel="icon" href="favicon.png" type="image/png">

<!-- Bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" crossorigin="anonymous">

<!-- jQuery & Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>

<style>
:root {
    --primary-color: var(--primary);
    --secondary-color: #54B68F;
    --accent-color: #ff8a65;
    --light-bg: #f8f9fa;
    --dark-text: #333;
    --light-text: #6c757d;
    --border-radius: 8px;
    --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

body {
    margin: 0;
    padding: 0;
    font-family: 'Source Sans Pro', sans-serif;
    font-size: 16px;
    width: 100%;
    background: var(--light-bg);
    color: var(--dark-text);
}

nav {
    background: var(--primary);
    line-height: 60px;
}

nav a {
    color: white;
    text-decoration: none;
}

nav a:hover {
    color: orange;
}

.page-header {
    background: linear-gradient(135deg, var(--primary) 0%, #c94452 100%);
    color: white;
    padding: 1.5rem 0;
    margin-bottom: 2rem;
    border-radius: 0 0 var(--border-radius) var(--border-radius);
}

.page-title {
    font-family: 'Montserrat', sans-serif;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.page-subtitle {
    opacity: 0.9;
    font-size: 1rem;
}

.card {
    border: none;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
    margin-bottom: 1.5rem;
}

.card-header {
    background: white;
    border-bottom: 1px solid rgba(0,0,0,0.05);
    padding: 1rem 1.5rem;
    font-weight: 600;
    border-radius: var(--border-radius) var(--border-radius) 0 0 !important;
}

.btn-primary {
    background-color: var(--primary);
    border-color: var(--primary);
}

.btn-primary:hover {
    background-color: #b83744;
    border-color: #b83744;
}

.btn-success {
    background-color: var(--secondary-color);
    border-color: var(--secondary-color);
}

.btn-warning {
    background-color: var(--accent-color);
    border-color: var(--accent-color);
    color: white;
}

.btn-info {
    background-color: #17a2b8;
    border-color: #17a2b8;
}

.action-buttons .btn {
    margin-right: 5px;
    font-size: 14px;
    border-radius: 4px;
}

.table-responsive {
    border-radius: var(--border-radius);
    overflow: hidden;
}

.table {
    width: 100%;
    font-size: 14px;
    margin-bottom: 0;
}

.table th {
    background-color: var(--primary);
    color: white;
    font-weight: 500;
    border: none;
    padding: 12px 15px;
}

.table td {
    padding: 12px 15px;
    vertical-align: middle;
    border-bottom: 1px solid #dee2e6;
}

.table tbody tr {
    transition: all 0.2s ease;
}

.table tbody tr:hover {
    background-color: rgba(208, 63, 77, 0.05);
}

.student-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #e9ecef;
}

.mob {
    display: table-cell;
}

@media only screen and (max-width: 768px){
    .mob {
        display: none;
    }
    
    .action-buttons {
        display: flex;
        flex-direction: column;
    }
    
    .action-buttons .btn {
        margin-bottom: 5px;
        margin-right: 0;
    }
    
    .page-title {
        font-size: 1.5rem;
    }
    
    .stats-card {
        padding: 1rem;
    }
    
    .stats-number {
        font-size: 1.5rem;
    }
}

.search-box {
    position: relative;
    max-width: 300px;
}

.search-box .form-control {
    padding-left: 40px;
    border-radius: 30px;
    border: 1px solid #ced4da;
}

.search-box i {
    position: absolute;
    left: 15px;
    top: 12px;
    color: var(--light-text);
    z-index: 10;
}

.whatsapp-float {
    position: fixed;
    width: 60px;
    height: 60px;
    bottom: 25px;
    right: 25px;
    background-color: #25d366;
    color: #FFF;
    border-radius: 50px;
    text-align: center;
    font-size: 30px;
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2);
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.whatsapp-float:hover {
    background-color: #128C7E;
    color: white;
    transform: scale(1.1);
}

.alert {
    border-radius: var(--border-radius);
    border: none;
    box-shadow: var(--box-shadow);
}

.alert-success {
    background-color: rgba(84, 182, 143, 0.15);
    color: var(--secondary-color);
    border-left: 4px solid var(--secondary-color);
}

.alert-info {
    background-color: rgba(23, 162, 184, 0.15);
    color: #17a2b8;
    border-left: 4px solid #17a2b8;
}

.content {
    margin-left: 210px;
    padding: 20px;
}

@media only screen and (max-width: 992px) {
    .content {
        margin-left: 0;
    }
}

.stats-card {
    background: white;
    border-radius: var(--border-radius);
    padding: 1.5rem;
    box-shadow: var(--box-shadow);
    margin-bottom: 1.5rem;
    text-align: center;
    transition: transform 0.3s ease;
}

.stats-card:hover {
    transform: translateY(-5px);
}

.stats-number {
    font-size: 2rem;
    font-weight: 600;
    color: var(--primary);
    margin-bottom: 0.5rem;
}

.stats-label {
    color: var(--light-text);
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.stats-icon {
    font-size: 2rem;
    color: var(--secondary-color);
    margin-bottom: 1rem;
}

.filter-card {
    background: white;
    border-radius: var(--border-radius);
    padding: 1.5rem;
    box-shadow: var(--box-shadow);
    margin-bottom: 1.5rem;
}

.filter-header {
    font-weight: 600;
    margin-bottom: 1rem;
    color: var(--primary);
    border-bottom: 2px solid var(--light-bg);
    padding-bottom: 0.5rem;
}

.active-filters {
    background: rgba(208, 63, 77, 0.1);
    border-left: 4px solid var(--primary);
    padding: 1rem;
    border-radius: var(--border-radius);
    margin-bottom: 1rem;
}

.badge-filter {
    background-color: var(--primary);
    color: white;
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 0.8rem;
    margin-right: 5px;
}

.clear-filters {
    color: var(--primary);
    text-decoration: none;
    font-size: 0.9rem;
}

.clear-filters:hover {
    text-decoration: underline;
}

.program-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    margin: 2px;
    background: #e9ecef;
    color: var(--dark-text);
}
</style>
</head>
<body>
<?php include "../include/nav.php";?>

<div class="content">
    <div class="page-header">
        <div class="container-fluid">
            <h1 class="page-title">Students List</h1>
            <p class="page-subtitle">Manage student records and information</p>
        </div>
    </div>

    <div class="container-fluid">


        <!-- Filter Card -->
        <div class="filter-card">
            <div class="filter-header">Filter Students</div>
            <?php if(!empty($filter_intake) || !empty($filter_program)): ?>
            <div class="active-filters">
                <strong>Active Filters:</strong>
                <?php if(!empty($filter_intake)): ?>
                    <span class="badge-filter">Intake: <?= $filter_intake ?></span>
                <?php endif; ?>
                <?php if(!empty($filter_program)): ?>
                    <span class="badge-filter">Program: <?= $filter_program ?></span>
                <?php endif; ?>
                <a href="?" class="clear-filters ml-2"><i class="fa fa-times"></i> Clear All</a>
            </div>
            <?php endif; ?>
            
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Filter by Intake:</label>
                            <select name="filter_intake" class="form-control" onchange="this.form.submit()">
                                <option value="">All Intakes</option>
                                <?php while($intake_row = mysqli_fetch_assoc($intakes_query)): ?>
                                    <option value="<?= $intake_row['intake'] ?>" 
                                        <?= ($filter_intake == $intake_row['intake']) ? 'selected' : '' ?>>
                                        <?= $intake_row['intake'] ?>
                                    </option>
                                <?php endwhile; ?>
                                <?php mysqli_data_seek($intakes_query, 0); // Reset pointer ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Filter by Program:</label>
                            <select name="filter_program" class="form-control" onchange="this.form.submit()">
                                <option value="">All Programs</option>
                                <?php while($program_row = mysqli_fetch_assoc($programs_query)): ?>
                                    <option value="<?= $program_row['program'] ?>" 
                                        <?= ($filter_program == $program_row['program']) ? 'selected' : '' ?>>
                                        <?= $program_row['program'] ?>
                                    </option>
                                <?php endwhile; ?>
                                <?php mysqli_data_seek($programs_query, 0); // Reset pointer ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <div>
                                <button type="submit" class="btn btn-primary"><i class="fa fa-filter"></i> Apply Filters</button>
                                <?php if(!empty($filter_intake) || !empty($filter_program)): ?>
                                    <a href="?" class="btn btn-secondary"><i class="fa fa-times"></i> Clear</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    Student Records
                    <?php if(!empty($filter_intake) || !empty($filter_program)): ?>
                        <small class="text-muted">(Filtered: <?= $filtered_students ?> students)</small>
                    <?php endif; ?>
                </h5>
                <div class="action-buttons">
                    <a href="addstudent.php" class="btn btn-primary"><i class="fa fa-plus-circle"></i> Add New</a>
                    <a href="report.php?<?= http_build_query(['filter_intake' => $filter_intake, 'filter_program' => $filter_program]) ?>" 
                       class="btn btn-success"><i class="fa fa-list"></i> Generate Report</a>
                </div>
            </div>
            
            <div class="card-body">
                <?php if (isset($_GET['success'])): ?>
                <div class="alert alert-success">
                    <p><i class="fa fa-check-circle"></i> <?= htmlspecialchars($_GET['success']) ?></p>
                </div>
                <?php endif; ?>

                <?php if (isset($_GET['delete'])): ?>
                <div class="alert alert-success">
                    <p><i class="fa fa-check-circle"></i> <?= htmlspecialchars($_GET['delete']) ?></p>
                </div>
                <?php endif; ?>
                
                <?php if($filtered_students == 0 && (!empty($filter_intake) || !empty($filter_program))): ?>
                <div class="alert alert-info">
                    <p><i class="fa fa-info-circle"></i> No students found with the selected filters.</p>
                </div>
                <?php endif; ?>
                
                <div class="search-box mb-3">
                    <i class="fa fa-search"></i>
                    <input id="searchInput" type="text" class="form-control" placeholder="Search students...">
                </div>

                <div class="table-responsive">
                    <table id="myTable" class="table table-hover">
                        <thead>
                            <tr>
                                <th class="mob">Image</th>
                                <th class="mob">Student ID</th>
                                <th>Name</th>
                                <th class="mob">Program</th>
                                <th>Intake</th>
                                <th class="mob">Year Started</th>
                                <th class="mob">Finishing Year</th>
                                <th class="mob">Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $query = mysqli_query($conn, "SELECT * FROM students ORDER BY studentname ASC");
                            while($row = mysqli_fetch_array($query)):
                            ?>
                            <tr>
                                <td class="mob">
                                    <img src="../../students/img/<?= htmlspecialchars($row['image']) ?>" class="student-avatar" alt="Student Image">
                                </td>
                                <td class="mob"><?= htmlspecialchars($row['studentid']) ?></td>
                                <td><?= htmlspecialchars($row['studentname']) ?></td>
                                <td class="mob"><?= htmlspecialchars($row['program']) ?></td>
                                <td><?= htmlspecialchars($row['intake']) ?></td>
                                <td class="mob"><?= htmlspecialchars($row['start_year']) ?></td>
                                <td class="mob"><?= htmlspecialchars($row['end_year']) ?></td>
                                <td class="mob"><?= htmlspecialchars($row['status']) ?></td>
                                <td>
                                    <div class="action-buttons d-flex">
                                        <a href="view.php?id=<?= $row['id'] ?>" class="btn btn-success" title="View Details">
                                            <i class="fa fa-eye"></i>
                                        </a>
                                        <a hidden href="https://wa.me/+26<?= $row['mobile'] ?>?text=Hello%20<?= urlencode($row['studentname']) ?>%20" 
                                           target="_blank" class="btn btn-primary" title="Chat on WhatsApp">
                                            <i class="fa fa-whatsapp"></i>
                                        </a>
                                        <a hidden href="delete.php?ids=<?= $row['id'] ?>" class="btn btn-warning" title="Delete" onclick="return checkdelete()">
                                            <i class="fa fa-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function checkdelete() {
    return confirm('Are you sure you want to delete this student?');
}

// Live table search
$(document).ready(function(){
    $("#searchInput").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("#myTable tbody tr").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });
});
</script>

</body>
</html>
<?php } else {
  header("location:../index.php");
} ?>