<?php

// Initialize variables
$subject_scores = [];
$subject_pass_fail = [];

$chart_type = $_POST['chart_type'] ?? 'bar';
$chart_width = isset($_POST['chart_width']) ? (int)$_POST['chart_width'] : 400;
$chart_height = isset($_POST['chart_height']) ? (int)$_POST['chart_height'] : 200;
$pass_mark = isset($_POST['pass_mark']) ? (int)$_POST['pass_mark'] : 40;

$class = $_POST['show_publish_result_class'] ?? '';
$term = $_POST['show_publish_result_term'] ?? '';
$session = $_POST['show_publish_result_session'] ?? '';

// Sanitize inputs
$class = $connection->real_escape_string($class);
$term = $connection->real_escape_string($term);
$session = $connection->real_escape_string($session);

// Build dynamic query
$query = "SELECT subjects, subject_total FROM results1 WHERE 1=1";
if (!empty($class)) $query .= " AND class = '$class'";
if (!empty($term)) $query .= " AND term = '$term'";
if (!empty($session)) $query .= " AND session = '$session'";

$result = $connection->query($query);

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $subject = $row['subjects'];
        $score = (int)$row['subject_total'];

        if (!isset($subject_scores[$subject])) {
            $subject_scores[$subject] = 0;
            $subject_pass_fail[$subject] = ['pass' => 0, 'fail' => 0];
        }

        $subject_scores[$subject] += $score;
        if ($score >= $pass_mark) {
            $subject_pass_fail[$subject]['pass']++;
        } else {
            $subject_pass_fail[$subject]['fail']++;
        }
    }

    $_SESSION['msg'] = "✅ Performance data loaded successfully.";
    $_SESSION['type'] = "success";
} else {
    $_SESSION['msg'] = "⚠️ No results found for the selected filters.";
    $_SESSION['type'] = "warning";
}

?>


<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Subject Performance Chart</h1>
    <p>Students Performance Chart by Subject</p>
  </div>
</div>

<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>View Performance by Subject</h4>
        </div>
        <div class='panel-body'>
            <form method='POST' action=''>
                <div class='row'>
                    <!-- Select Class -->
                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Class:</span>
                            <select class='form-control' name='show_publish_result_class'>
                                <option selected><?php echo $select; ?></option>
                                <?php
                                    $query = "SELECT classes FROM `classes`";
                                    $run_query = mysqli_query($connection, $query);
                                    if ($run_query && mysqli_num_rows($run_query) > 0) {
                                        while ($result = mysqli_fetch_assoc($run_query)) {
                                            echo "<option>{$result['classes']}</option>";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                    </div>
                    <!-- Select Term -->
                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Term:</span>
                            <select class='form-control' name='show_publish_result_term'>
                                <option selected><?php echo $select; ?></option>
                                <?php
                                    $term_array = ["First Term", "Second Term", "Third Term"];
                                    foreach ($term_array as $term_option) {
                                        echo "<option>{$term_option}</option>";
                                    }
                                ?>
                            </select>
                        </div>
                    </div>
                    <!-- Select Session -->
                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Session:</span>
                            <select class='form-control' name='show_publish_result_session'>
                                <option selected><?php echo $select; ?></option>
                                <?php
                                    $query = "SELECT current_session FROM `current_season`";
                                    $run_query = mysqli_query($connection, $query);
                                    if ($run_query && mysqli_num_rows($run_query) > 0) {
                                        while ($result = mysqli_fetch_assoc($run_query)) {
                                            echo "<option>{$result['current_session']}</option>";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                    </div>                  
                </div>
                <br />
                <div class='row'>
                    <!-- Pass Mark Input -->
                    <div class='col-md-5'>
                    <div class='input-group'>
                            <span class='input-group-addon'>Pass Mark:</span>
                        <input type='number' class='form-control' name='pass_mark' value='<?php echo $pass_mark; ?>' placeholder='Pass Mark' />
                    </div>
                    </div>
                    <!-- Chart Type Selection -->
                    <div class='col-md-5'>
		                <div class='input-group'>
		                    <span class='input-group-addon'>Chart Type:</span>
		                    <select class='form-control' name='chart_type'>
		                        <option value='bar' <?php echo ($chart_type == 'bar') ? 'selected' : ''; ?>>Bar</option>
		                        <option value='pie' <?php echo ($chart_type == 'pie') ? 'selected' : ''; ?>>Pie</option>
		                        <option value='line' <?php echo ($chart_type == 'line') ? 'selected' : ''; ?>>Line</option>
		                    </select>
		                 </div>
                    </div>
                    <!-- Submit Button -->
                    <div class='col-md-2'>
                        <input type='submit' name='view_publish_result_btn' value='VIEW' class='btn btn-primary btn-sm' />
                    </div>
                </div>
            </form>
            <br />
            <canvas id="performanceChart" width="<?php echo $chart_width; ?>" height="<?php echo $chart_height; ?>"></canvas>
            <br />
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    var ctx = document.getElementById('performanceChart').getContext('2d');
    var performanceChart = new Chart(ctx, {
        type: '<?php echo $chart_type; ?>',
        data: {
            labels: <?php echo json_encode(array_keys($subject_pass_fail)); ?>,
            datasets: [
                {
                    label: 'Pass',
                    data: <?php echo json_encode(array_column($subject_pass_fail, 'pass')); ?>,
                    backgroundColor: 'green',
                    borderColor: 'darkgreen',
                    borderWidth: 1
                },
                {
                    label: 'Fail',
                    data: <?php echo json_encode(array_column($subject_pass_fail, 'fail')); ?>,
                    backgroundColor: 'red',
                    borderColor: 'darkred',
                    borderWidth: 1
                }
            ]
        }
    });
</script>

