<?php $act =66;
 include './login/connect.php';

?>
<?php

// Fetch classes
$classQuery = "SELECT * FROM classes";
$classResult = $conn->query($classQuery);
$classes = [];
while ($row = $classResult->fetch_assoc()) {
    $classes[$row['id']] = $row['class_name'];
}

// Fetch subjects
$subjectQuery = "SELECT * FROM subjects";
$subjectResult = $conn->query($subjectQuery);
$subjects = [];
while ($row = $subjectResult->fetch_assoc()) {
    $subjects[$row['id']] = $row['subject_name'];
}

// Fetch student results
$monthFilter = isset($_GET['month']) ? $_GET['month'] : 'all';
$classFilter = isset($_GET['class']) ? $_GET['class'] : 'all';
$query = "SELECT s.id AS student_id, s.name AS student_name, c.class_name, r.subject_id, subj.subject_name, r.score_given, r.month 
          FROM results r
          JOIN students s ON r.student_id = s.id
          JOIN classes c ON s.class_id = c.id
          JOIN subjects subj ON r.subject_id = subj.id";

if ($monthFilter !== 'all' || $classFilter !== 'all') {
    $query .= " WHERE ";
    $conditions = [];
    if ($monthFilter !== 'all') {
        $conditions[] = "r.month = '$monthFilter'";
    }
    if ($classFilter !== 'all') {
        $conditions[] = "c.id = '$classFilter'";
    }
    $query .= implode(" AND ", $conditions);
}

$query .= " ORDER BY r.month, c.class_name, s.name, subj.id";
$result = $conn->query($query);

// Process results into grouped format
$students = [];
while ($row = $result->fetch_assoc()) {
    $studentId = $row['student_id'];
    if (!isset($students[$studentId])) {
        $students[$studentId] = [
            'name' => $row['student_name'],
            'class' => $row['class_name'],
            'subjects' => array_fill_keys(array_keys($subjects), 0), // Initialize all subjects
            'total' => 0,
            'month' => $row['month']
        ];
    }
    $students[$studentId]['subjects'][$row['subject_id']] = $row['score_given'];
    $students[$studentId]['total'] += $row['score_given'];
}
?>
<!DOCTYPE html>
<!-- =========================================================
* ekseba Admin Template - Pro | v1.0.0
==============================================================

* Product Page: https://ekseba.com
* Created by: ekseba
* License: ekseba.com
* Copyright ThemeSelection (https://ekseba.com)

=========================================================
 -->
<!-- beautify ignore:start -->
<html lang="en"  class="light-style layout-menu-fixed"  dir="ltr"  data-theme="theme-default"  data-assets-path="assets/"  data-template="vertical-menu-template-free">
  <head>
    
    <?php include './html/head.php'; ?>
      
        <!-- serch script -->
        <script src="jeffartagame.js" type="text/javascript" charset="utf-8"></script>
        <script src="application.js" type="text/javascript" charset="utf-8"></script>
        <!-- serch script -->
     
      <style>
#customers {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 100%; font-size: 12px;
}

#customers td, #customers th {
  border: 1px solid #ddd;
  padding: 5px 2px 5px 2px; font-size: 12px;
  text-align: center;
}

#customers tr:nth-child(even){background-color: #f2f2f2;}

#customers tr:hover {background-color: #ddd;}

#customers th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #04AA6D;
  color: white; font-size: 12px;
}
      </style>
      <style>
       
        .table-container { overflow-x: auto; margin-top: 20px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { border: 1px solid #ccc; padding: 10px; text-align: center; }
        th { background-color: #f4f4f4; }
        .filter-container { margin-bottom: 20px; }
        .filter-container select { padding: 5px 10px; font-size: 16px; }
    </style>
  </head>

  <body>
    <!-- Layout wrapper -->
    <div class="layout-wrapper layout-content-navbar">
      <div class="layout-container">
        <!-- Menu -->
        <?php 
        include './menue.php';
        ?>
        <!-- / Menu -->

        <!-- Layout container -->
        <div class="layout-page">
          <!-- Navbar -->

          <?php include './navbar.php'; ?>

          <!-- / Navbar -->

          <!-- Content wrapper -->
          <div class="content-wrapper">
            <!-- Content -->

            <!-- Content wrapper -->
          <div class="content-wrapper">
            <!-- Content -->

            <div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Results/</span> Information</h4>

              <!-- Basic Layout & Basic with Icons -->
              <div class="row">
                <!-- Basic Layout -->
                <div class="col-xl">
                  <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                      <h5 class="mb-0">Results Information</h5>
                      
                      
                      <span class="float:right;" >
                           <button   type="button" class="btn btn-primary" data-bs-toggle="modal"
                          data-bs-target="#largeModal">Add Results
                        </button>
				</a></span>
                       
                  
                    </div>
                    <div class="card-body">
                     

                <div class="col-xxl"> 
                  <div class="card mb-4">
              <!--/ Result Classes --> 
              
              <div class="filter-container" >
        <label for="class-filter" style="float: left;">Select Class:</label>
        <select id="class-filter" style="float: left; width:150px" onchange="applyFilters()">
            <option value="all" >All Classes</option>
            <?php foreach ($classes as $id => $class_name): ?>
                <option value="<?= $id ?>" <?= $classFilter == $id ? 'selected' : '' ?>>
                    <?= $class_name ?>
                </option>
            <?php endforeach; ?>
        </select>
      
        <label for="month-filter" style="float: left;">Select Month:</label>
        <select id="month-filter" style="float: left;width:150px" onchange="applyFilters()">
            <option value="all" <?= $monthFilter === 'all' ? 'selected' : '' ?>>All Months</option>
            <option value="January" <?= $monthFilter === 'January' ? 'selected' : '' ?>>January</option>
            <option value="February" <?= $monthFilter === 'February' ? 'selected' : '' ?>>February</option>
            <option value="March" <?= $monthFilter === 'March' ? 'selected' : '' ?>>March</option>
            <option value="April" <?= $monthFilter === 'April' ? 'selected' : '' ?>>April</option>
            <option value="May" <?= $monthFilter === 'May' ? 'selected' : '' ?>>May</option>
            <option value="June" <?= $monthFilter === 'June' ? 'selected' : '' ?>>June</option>
            <option value="July" <?= $monthFilter === 'July' ? 'selected' : '' ?>>July</option><!-- comment -->
            <option value="August" <?= $monthFilter === 'August' ? 'selected' : '' ?>>August</option><!-- comment -->
            <option value="September" <?= $monthFilter === 'September' ? 'selected' : '' ?>>September</option><!-- comment -->
            <option value="October" <?= $monthFilter === 'October' ? 'selected' : '' ?>>October</option><!-- comment -->
            <option value="November" <?= $monthFilter === 'November' ? 'selected' : '' ?>>November</option><!-- comment -->
            <option value="December" <?= $monthFilter === 'December' ? 'selected' : '' ?>>December</option>
            
            
            
            
            
            
        </select>
    </div>

    <!-- Table -->
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>ক্র. নং</th>
                    <th>ক্লাস</th>
                    <th>ছাত্রের নাম</th>
                    <?php foreach ($subjects as $subjectName): ?>
                        <th><?= htmlspecialchars($subjectName) ?></th>
                    <?php endforeach; ?>
                    <th>সর্বমোট নম্বর</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($students as $index => $student): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td><?= htmlspecialchars($student['class']) ?></td>
                        <td><?= htmlspecialchars($student['name']) ?></td>
                        <?php foreach ($student['subjects'] as $score): ?>
                            <td><?= $score ?></td>
                        <?php endforeach; ?>
                        <td><?= $student['total'] ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <script>
        function applyFilters() {
            const classFilter = document.getElementById('class-filter').value;
            const monthFilter = document.getElementById('month-filter').value;
            window.location.href = `?class=${classFilter}&month=${monthFilter}`;
        }
    </script>
              
              <!--/ Result Classes --> 
                  </div>
                <!-- Basic with Icons -->
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- / Content -->
          </div>
            <!-- Footer -->
           <?php require './footer.php'; ?>
<!-- Large Modal -->

                      <div class="modal fade" id="largeModal" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-lg" role="document">
                          <div class="modal-content">
                            <div class="modal-header">
                              <h5 class="modal-title" id="exampleModalLabel3">Insert New Result</h5>
                              <button type="button" class="btn-close" data-bs-dismiss="modal"  aria-label="Close" ></button>
                            </div>
                            <div class="modal-body">
                                
<?php
// Fetch subjects from the database
$query = "SELECT id, class_name FROM classes";
$classs = $conn->query($query);
// Fetch subjects from the database
$query = "SELECT id, subject_name FROM subjects";
$result = $conn->query($query);
?>

<div>
    <select id="class-select" name="class_id">
        <option value="">Select Class</option>
        <?php
            if ($result->num_rows > 0) {
                while ($row = $classs->fetch_assoc()) {
                    echo "<option value='" . $row['id'] . "'>" . $row['class_name'] . "</option>";
                }
            } else {
                echo "<option value=''>No subjects available</option>";
            }
            ?>

    </select>

    <select id="month-select" name="month">
                <option value="">Select month</option>
                <option value="January">January</option>
                <option value="February">February</option>
                <option value="March">March</option>
                <option value="April">April</option>
                <option value="May">May</option>
                <option value="June">June</option>
                <option value="July">July</option>
                <option value="August">August</option>
                <option value="September">September</option>
                <option value="October">October</option>
                <option value="November">November</option>
                <option value="December">December</option>
    </select>

    <select id="subject-select" name="subject_id">
        <option value="">Select Subject</option>
        <?php
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    echo "<option value='" . $row['id'] . "'>" . $row['subject_name'] . "</option>";
                }
            } else {
                echo "<option value=''>No subjects available</option>";
            }
            ?>

    </select>

    <button type="button" onclick="loadStudents()">Load Students</button>
</div>

<div id="student-container">
    <!-- Students will be loaded here -->
</div>

<script>
function loadStudents() {
    const classId = document.getElementById('class-select').value;
    const month = document.getElementById('month-select').value;
    const subjectId = document.getElementById('subject-select').value;

    fetch('fetch_students.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `class_id=${classId}&month=${month}&subject_id=${subjectId}`
    })
    .then(response => response.text())
    .then(data => {
        document.getElementById('student-container').innerHTML = data;

        const form = document.getElementById('score-form');
        form.addEventListener('submit', function (event) {
            event.preventDefault();

            const formData = new FormData(form);
            formData.append('class_id', classId);
            formData.append('month', month);
            formData.append('subject_id', subjectId);

            fetch('save_scores.php', {
                method: 'POST',
                body: new URLSearchParams([...formData])
            })
            .then(response => response.text())
            .then(data => {
                alert(data);
                loadStudents(); // Reload students to display updated scores
            });
        });
    });
}
</script>
                            
                          </div>
                        </div>
                      </div>
</form>

                      <!-- Extra Large Modal -->
                      