<?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'])){ ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Reports</title>

<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&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">

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- 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>
body {
    margin: 0;
    padding: 0;
    font-family: 'Source Sans Pro', sans-serif;
    font-size: 16px;
    width: 100%;
    background: white;
}

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

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

nav a:hover {
    color: orange;
}

.card-header .btn {
    margin-right: 5px;
    font-size: 14px;
}

.table {
    width: 100%;
    font-size: 14px;
    padding: 5px;
    overflow-x: auto;
}

.table-responsive {
    padding: 10px;
}

.mob {
    display: table-cell;
}

@media only screen and (max-width:500px){
    .mob {
        display: none;
    }
    .flex .box,
    form,
    input {
        width: 100%;
    }
}

#myTable_filter {
    margin-bottom: 10px;
}

@media only screen and (max-width:500px){
    nav a{
        margin-left:%;
        color:white;
        text-decoration:none;
    }
    nav a:hover{
        color: orange;
    }
    .header{
        width:100%;
    }
}

.iterm{
    justify-content: center;
    display: flex;
    flex-wrap: wrap;
    margin-top:10px;
    margin-top: 10px;
    color: white;
    overflow: scroll;
    height:100%;
    text-align: center;
}

.iterm1{
    padding:20px;
    padding-left:30px;
    padding-right:30px;
}

.iterm a{
    width:45%;
    height :%;
    box-shadow:rgba(99, 99, 99, 0.4) 0px 2px 8px 0px;
    padding: 10px;
    text-align: center;
    border-radius: 5px;
    margin: 5px;
    background: white;
    text-decoration: none;
    border:1px solid gray;
}

.header{
    margin-top:px;
    background:var(--primary);
    background-size:cover;
    background-blend-mode:darken;
    height: 200px;
    width:100%;
    color: white;
    padding: px;
    text-align: center ;
}

.header{
    width:100%;
}

part{
    margin-top: -50px;
    position: absolute;
    background: white;
    width:93%;
    height:210px;
    top: 60px;
    left: 50%;
    transform: translate(-50%);
    color: gray;
    display: block;
    border-radius: 6px;
}

.header img{
    width:80px;
    height: 80px;
    border-radius: 50%;
    border: 5px solid white;
    float:right;
    margin-right:15px;
}

.iterm_box img{
}

.iterm  i{
    font-size: 20px;
    background:var(--primary);
    padding: 9px;
    border-radius: 5px;
}

.iterm_box p{
    font-size: 13px;
    margin-top: 5px;
    color:var(--primary);
    margin-bottom: 10px;
}

.btn{
    background:var(--primary);
    border:none;
    border-radius:2px;
    outline:none;
    color: white;
}

.div .btn{
    background: transparent;
    border:;
    border-radius:0px;
    padding:7px;
    border-bottom: 2px solid white;
    outline:none;
}  

.div .btn:hover{
    border:none;
    outline:none;
    background: transparent;
    border-bottom: 2px solid black;
    border-radius:2px;
    box-shadow:none;
} 

.dash{
    color: white;
    font-weight: 900px;
    text-align : center ;
}

.money{
    justify-content:;
    display:flex;
    flex-wrap:wrap;
    width:100%;
}

.money .card1{
    width:60px;
    margin-left:10px;
    box-shadow:2px 1px 10px 0px rgb(199, 235, 202);
    margin-top:-10px;
}

#btn{
    background: var(--primary);
}

.in{
    justify-content:center;
    display:flex;
    flex-wrap:wrap;
    padding:px;
    font-weight:1000;
}

.in p{
    font-size:15px;
    margin-top:10px;
}

.in .card2{
    width:100%;
    margin:2px;
    text-align:center;
    padding:7px;
    box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
    border-radius:6px;
    background:;
    color:var(--primary);
    border:none;
    font-size:15px;
    height:100%;
    text-decoration:none;
}

.in a{
    width:46%;
    margin:5px;
    text-decoration:none;
}

.in .card2 img{
    font-size:30px;
    color:var(--primary);
    opacity:0.4;
}

.loading {
    display: none;
    text-align: center;
    margin: 1rem 0;
}

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

.chart-container {
    position: relative;
    height: 300px;
    margin-bottom: 20px;
}

.stat-card {
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    padding: 15px;
    margin-bottom: 20px;
    background: white;
}

.stat-card h5 {
    color: var(--primary);
    font-size: 16px;
}

.stat-number {
    font-size: 24px;
    font-weight: bold;
    color: #202342;
}

.filter-section {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 5px;
    margin-bottom: 20px;
}
</style>
</head>
<body>
<?php include "../include/nav.php";?>

<div class="content">

    <div class="card-header" style="background:white; border:none;padding:15px; margin:5px 0; border-radius:4px;">
        <a href="students.php" class="btn btn-secondary" style="color:white;background: "><i class="fa fa-arrow-left"></i> Back to Students</a>
        <button class="btn btn" style="background:var(--primary); color:white" onclick="window.print()"><i class="fa fa-print"></i> Print Report</button>
    </div>

    <div class="filter-section">
        <h4>Student Reports</h4>
        <form method="GET" class="form-inline">
            <div class="form-group mr-2">
                <label for="programFilter" class="mr-2">Program:</label>
                <select class="form-control" id="programFilter" name="program">
                    <option value="">All Programs</option>
                    <?php
                    $programQuery = mysqli_query($conn, "SELECT DISTINCT program FROM students ORDER BY program");
                    while($program = mysqli_fetch_array($programQuery)){
                        $selected = (isset($_GET['program']) && $_GET['program'] == $program['program']) ? 'selected' : '';
                        echo "<option value='".$program['program']."' $selected>".$program['program']."</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="form-group mr-2">
                <label for="intakeFilter" class="mr-2">Intake:</label>
                <select class="form-control" id="intakeFilter" name="intake">
                    <option value="">All Intakes</option>
                    <?php
                    $intakeQuery = mysqli_query($conn, "SELECT DISTINCT intake FROM students ORDER BY intake");
                    while($intake = mysqli_fetch_array($intakeQuery)){
                        $selected = (isset($_GET['intake']) && $_GET['intake'] == $intake['intake']) ? 'selected' : '';
                        echo "<option value='".$intake['intake']."' $selected>".$intake['intake']."</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="form-group mr-2">
                <label for="genderFilter" class="mr-2">Gender:</label>
                <select class="form-control" id="genderFilter" name="gender">
                    <option value="">All Genders</option>
                    <option value="Male" <?php echo (isset($_GET['gender']) && $_GET['gender'] == 'Male') ? 'selected' : ''; ?>>Male</option>
                    <option value="Female" <?php echo (isset($_GET['gender']) && $_GET['gender'] == 'Female') ? 'selected' : ''; ?>>Female</option>
                    <option value="Other" <?php echo (isset($_GET['gender']) && $_GET['gender'] == 'Other') ? 'selected' : ''; ?>>Other</option>
                </select>
            </div>
            <button type="submit" class="btn" style="background:var(--primary); color:white">Filter</button>
        </form>
    </div>

    <?php
    // Build filter conditions
    $filterConditions = [];
    if (isset($_GET['program']) && !empty($_GET['program'])) {
        $filterConditions[] = "program = '".mysqli_real_escape_string($conn, $_GET['program'])."'";
    }
    if (isset($_GET['intake']) && !empty($_GET['intake'])) {
        $filterConditions[] = "intake = '".mysqli_real_escape_string($conn, $_GET['intake'])."'";
    }
    if (isset($_GET['gender']) && !empty($_GET['gender'])) {
        $filterConditions[] = "gender = '".mysqli_real_escape_string($conn, $_GET['gender'])."'";
    }
    
    $whereClause = "";
    if (!empty($filterConditions)) {
        $whereClause = "WHERE " . implode(" AND ", $filterConditions);
    }
    
    // Get total students count
    $totalQuery = mysqli_query($conn, "SELECT COUNT(*) as total FROM students $whereClause");
    $totalData = mysqli_fetch_assoc($totalQuery);
    $totalStudents = $totalData['total'];
    
    // Get students by program
    $programStatsQuery = mysqli_query($conn, "
        SELECT program, COUNT(*) as count 
        FROM students 
        $whereClause
        GROUP BY program 
        ORDER BY count DESC
    ");
    
    $programStats = [];
    while($row = mysqli_fetch_assoc($programStatsQuery)) {
        $programStats[] = $row;
    }
    
    // Get students by intake
    $intakeStatsQuery = mysqli_query($conn, "
        SELECT intake, COUNT(*) as count 
        FROM students 
        $whereClause
        GROUP BY intake 
        ORDER BY intake DESC
    ");
    
    $intakeStats = [];
    while($row = mysqli_fetch_assoc($intakeStatsQuery)) {
        $intakeStats[] = $row;
    }
    
    // Get students by gender
    $genderStatsQuery = mysqli_query($conn, "
        SELECT gender, COUNT(*) as count 
        FROM students 
        $whereClause
        GROUP BY gender 
        ORDER BY gender
    ");
    
    $genderStats = [];
    while($row = mysqli_fetch_assoc($genderStatsQuery)) {
        $genderStats[] = $row;
    }
    
    // Get students by program and intake
    $programIntakeQuery = mysqli_query($conn, "
        SELECT program, intake, COUNT(*) as count 
        FROM students 
        $whereClause
        GROUP BY program, intake 
        ORDER BY program, intake
    ");
    
    $programIntakeStats = [];
    while($row = mysqli_fetch_assoc($programIntakeQuery)) {
        $programIntakeStats[] = $row;
    }
    
    // Get students by program and gender
    $programGenderQuery = mysqli_query($conn, "
        SELECT program, gender, COUNT(*) as count 
        FROM students 
        $whereClause
        GROUP BY program, gender 
        ORDER BY program, gender
    ");
    
    $programGenderStats = [];
    while($row = mysqli_fetch_assoc($programGenderQuery)) {
        $programGenderStats[] = $row;
    }
    ?>

    <div class="row">
        <div class="col-md-3">
            <div class="stat-card">
                <h5>Total Students</h5>
                <div class="stat-number"><?php echo $totalStudents; ?></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <h5>Programs</h5>
                <div class="stat-number"><?php echo count($programStats); ?></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <h5>Intakes</h5>
                <div class="stat-number"><?php echo count($intakeStats); ?></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <h5>Gender Distribution</h5>
                <div class="stat-number">
                    <?php 
                    $maleCount = 0;
                    $femaleCount = 0;
                    $otherCount = 0;
                    
                    foreach($genderStats as $stat) {
                        if ($stat['gender'] == 'Male') $maleCount = $stat['count'];
                        if ($stat['gender'] == 'Female') $femaleCount = $stat['count'];
                        if ($stat['gender'] == 'Other') $otherCount = $stat['count'];
                    }
                    
                    echo "M: $maleCount, F: $femaleCount, O: $otherCount";
                    ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="stat-card">
                <h5>Students by Program</h5>
                <div class="chart-container">
                    <canvas id="programChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="stat-card">
                <h5>Students by Intake</h5>
                <div class="chart-container">
                    <canvas id="intakeChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="stat-card">
                <h5>Students by Gender</h5>
                <div class="chart-container">
                    <canvas id="genderChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="stat-card">
                <h5>Gender Distribution by Program</h5>
                <div class="chart-container">
                    <canvas id="programGenderChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="stat-card">
        <h5>Students by Program and Intake</h5>
        <div class="table-responsive">
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Program</th>
                        <th>Intake</th>
                        <th>Number of Students</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($programIntakeStats as $stat): ?>
                    <tr>
                        <td><?php echo $stat['program']; ?></td>
                        <td><?php echo $stat['intake']; ?></td>
                        <td><?php echo $stat['count']; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="stat-card">
        <h5>Students by Program and Gender</h5>
        <div class="table-responsive">
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Program</th>
                        <th>Gender</th>
                        <th>Number of Students</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($programGenderStats as $stat): ?>
                    <tr>
                        <td><?php echo $stat['program']; ?></td>
                        <td><?php echo $stat['gender']; ?></td>
                        <td><?php echo $stat['count']; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// Program Chart
const programCtx = document.getElementById('programChart').getContext('2d');
const programChart = new Chart(programCtx, {
    type: 'bar',
    data: {
        labels: [<?php echo implode(',', array_map(function($item) { return "'" . $item['program'] . "'"; }, $programStats)); ?>],
        datasets: [{
            label: 'Number of Students',
            data: [<?php echo implode(',', array_map(function($item) { return $item['count']; }, $programStats)); ?>],
            backgroundColor: [
                'rgba(23, 204, 39, 0.7)',
                'rgba(84, 182, 143, 0.7)',
                'rgba(32, 35, 66, 0.7)',
                'rgba(255, 138, 101, 0.7)',
                'rgba(100, 181, 246, 0.7)'
            ],
            borderColor: [
                'rgba(23, 204, 39, 1)',
                'rgba(84, 182, 143, 1)',
                'rgba(32, 35, 66, 1)',
                'rgba(255, 138, 101, 1)',
                'rgba(100, 181, 246, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

// Intake Chart
const intakeCtx = document.getElementById('intakeChart').getContext('2d');
const intakeChart = new Chart(intakeCtx, {
    type: 'pie',
    data: {
        labels: [<?php echo implode(',', array_map(function($item) { return "'" . $item['intake'] . "'"; }, $intakeStats)); ?>],
        datasets: [{
            label: 'Number of Students',
            data: [<?php echo implode(',', array_map(function($item) { return $item['count']; }, $intakeStats)); ?>],
            backgroundColor: [
                'rgba(23, 204, 39, 0.7)',
                'rgba(84, 182, 143, 0.7)',
                'rgba(32, 35, 66, 0.7)',
                'rgba(255, 138, 101, 0.7)',
                'rgba(100, 181, 246, 0.7)',
                'rgba(171, 71, 188, 0.7)',
                'rgba(255, 193, 7, 0.7)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false
    }
});

// Gender Chart
const genderCtx = document.getElementById('genderChart').getContext('2d');
const genderChart = new Chart(genderCtx, {
    type: 'doughnut',
    data: {
        labels: [<?php 
            $genderLabels = [];
            foreach($genderStats as $stat) {
                $genderLabels[] = "'" . $stat['gender'] . "'";
            }
            echo implode(',', $genderLabels);
        ?>],
        datasets: [{
            label: 'Number of Students',
            data: [<?php 
                $genderData = [];
                foreach($genderStats as $stat) {
                    $genderData[] = $stat['count'];
                }
                echo implode(',', $genderData);
            ?>],
            backgroundColor: [
                'rgba(54, 162, 235, 0.7)', // Blue for Male
                'rgba(255, 99, 132, 0.7)', // Pink for Female
                'rgba(255, 206, 86, 0.7)'  // Yellow for Other
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false
    }
});

// Program Gender Chart (Stacked Bar Chart)
const programGenderCtx = document.getElementById('programGenderChart').getContext('2d');

// Prepare data for stacked bar chart
const programs = [...new Set(<?php echo json_encode(array_map(function($item) { return $item['program']; }, $programGenderStats)); ?>)];
const genders = ['Male', 'Female', 'Other'];

// Create datasets for each gender
const genderDatasets = genders.map(gender => {
    return {
        label: gender,
        data: programs.map(program => {
            const found = <?php echo json_encode($programGenderStats); ?>.find(item => 
                item.program === program && item.gender === gender
            );
            return found ? parseInt(found.count) : 0;
        }),
        backgroundColor: gender === 'Male' ? 'rgba(54, 162, 235, 0.7)' : 
                         gender === 'Female' ? 'rgba(255, 99, 132, 0.7)' : 
                         'rgba(255, 206, 86, 0.7)'
    };
});

const programGenderChart = new Chart(programGenderCtx, {
    type: 'bar',
    data: {
        labels: programs,
        datasets: genderDatasets
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            x: {
                stacked: true
            },
            y: {
                stacked: true,
                beginAtZero: true
            }
        }
    }
});
</script>
</body>
</html>
<?php } else {
  header("location:../index.php");
} ?>