<?php
// Include your database connection here
include('config.php');

session_start();

// Check if user is logged in
if (!isset($_SESSION['registration_number'])) {
    header("Location: login.php");
    exit();
}

$registration_number = $_SESSION['registration_number'];

$error_messages = [];
$filtered_results = [];

try {
    // Fetch grades for the current user
    $query = "
    SELECT DISTINCT 
        g.id AS grade1_id,
        a3.id AS grade2_id,
        am.id AS grade3_id,
        amm.id AS grade4_id,
        g.grade AS grade_one,
        a3.grade AS grade_two,
        am.grade AS grade_three,
        amm.grade AS grade_four,
        g.exam_type,
        g.year,
        g.sem_number AS semester_no,
        g.user,
        sub.subject_name,
         a3.start_date,
          a3.end_date,
        sub.subject_code,
        s.study_mode,
        s.firstname,
        s.registration_number
    FROM assignments2 g
    LEFT JOIN assignments3 a3 
        ON a3.registration_number = g.registration_number
        AND a3.subject_code = g.subject_code
        AND a3.semester_no = g.sem_number
        AND a3.year = g.year
        AND a3.user = g.user
    LEFT JOIN exam_results_mid am
        ON am.registration_number = g.registration_number
        AND am.subject_code = g.subject_code
        AND am.semester_no = g.sem_number
        AND am.year = g.year
        AND am.user = g.user
    LEFT JOIN exam_results amm
        ON amm.registration_number = g.registration_number
        AND amm.subject_code = g.subject_code
        AND amm.semester_no = g.sem_number
        AND amm.year = g.year
        AND amm.user = g.user
    JOIN student_enrollments sub 
        ON g.subject_code = sub.subject_code
    JOIN students s 
        ON g.registration_number = s.registration_number
    WHERE g.exam_type = 'conti'
      AND g.user = :registration_number
      AND g.approve = 9
    GROUP BY g.id
    ORDER BY sub.subject_name ASC, s.study_mode ASC, g.year DESC;
    ";

    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':registration_number', $registration_number);
    $stmt->execute();

} catch (PDOException $e) {
    $error_messages[] = "Error fetching grades: " . $e->getMessage();
}



// ================= FILTERED DROPDOWNS =================
$filter_query = "
    SELECT DISTINCT 
        se.subject_code,
        se.subject_name,
        se.start_date,
        se.level,
        se.semester_no,
        g.study_mode
    FROM student_enrollments se
    JOIN assignments2 g 
        ON se.subject_code = g.subject_code
        AND g.user = :reg_num
    LEFT JOIN lectures l 
        ON se.lecturer_id = l.lecturer_id
";

$filter_stmt = $pdo->prepare($filter_query);
$filter_stmt->bindParam(':reg_num', $registration_number);
$filter_stmt->execute();

$codes = [];
$names = [];
$levels = [];
$sems = [];
$start = [];
$study_modes = [];

while ($f = $filter_stmt->fetch(PDO::FETCH_ASSOC)) {
    $codes[]  = $f['subject_code'];
    $names[]  = $f['subject_name'];
    $levels[] = $f['level'];
    $sems[]   = $f['semester_no'];
      $start[]   = $f['start_date'];
      $study_modes[] = $f['study_mode'] ?? '';
}

$codes = array_unique($codes);
$names = array_unique($names);
$levels = array_unique($levels);
$sems = array_unique($sems);
$start = array_unique($start);
$study_modes = array_unique($study_modes);


// 🔥 ADD THESE LINES HERE
sort($codes);
sort($names);
sort($levels, SORT_NUMERIC);
sort($sems, SORT_NUMERIC);
sort($start);
sort($study_modes);

function blinkZero($value) {
    return ($value == 0) ? 'blink-zero' : '';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Final Grades</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

    <style>
        body {
            font-family: 'Poppins', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f9f9f9;
            font-size: 14px;
        }

             table {
            width: 90%;
            font-size: 12px;
            text-align: center;
            border-collapse: collapse;
            margin: 20px auto;
        }

        table input[type="text"] {
    width: 60px;
    padding: 5px;
    text-align: center;
    font-size: 14px;
}
input:disabled {
    background-color: #eee;
    cursor: not-allowed;
    color: #666;
}


        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #206a29;
            color: white;
        }
        nav {
            background-color: #333;
            overflow: hidden;
        }
        nav a {
            float: left;
            display: block;
            color: white;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
        }
        nav a:hover {
            background-color: #ddd;
            color: black;
        }
        .button {
            display: inline-block;
            padding: 10px 20px;
            color: white;
            background-color: #206a29;
            border: none;
            border-radius: 5px;
            text-align: center;
            text-decoration: none;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        .button:hover {
            background-color: #45a049;
        }
        .warning {
            color: red;
            text-align: center;
            font-weight: bold;
        }
        .center {
            text-align: center;
        }
        .container {
            width: 50%;
            margin: 0 auto; /* Centers the container */
        }
        .form-container {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            margin: 20px;
            width: 100%; /* Full width of container */
        }
        select {
            margin: 5px;
            padding: 10px;
            font-size: 16px;
        }
        select, input[type="text"], input[type="submit"] {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        input[type="submit"] {
            background-color: #206a29;
            color: white;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #45a049;
        }
        .add-grade-btn {
            margin: 20px;
            display: inline-block;
            padding: 10px 20px;
            background-color: #206a29;
            color: white;
            border-radius: 5px;
            text-decoration: none;
            font-size: 16px;
        }
        .add-grade-btn:hover {
            background-color: #45a049;
        }

     .duplicate {
    background-color: yellow; /* Highlight duplicates in yellow */
}


        .container {
            width: 95%;
            margin: 20px auto;
        }
        input#searchInput {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }

 .zero-highlight {
    background-color: #ff4d4d; /* soft red */
    color: white;
    font-weight: bold;
    text-align: center;
    border-radius: 4px;
    padding: 3px 6px;
}
        table {
            width: 100%;
            border-collapse: collapse;
            text-align: center;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #206a29;
            color: white;
        }
        tr.duplicate {
            background-color: yellow;
        }
        tr.orange {
            background-color: orange;
        }
    </style>
</head>
<body>
    <?php include('nav.php'); ?>

    <div class="container">
        <div style="margin: 20px 0;">
    <button class="button" onclick="goBack()">⬅ Back</button>
</div>

<script>
function goBack() {
    // Go back one page in history
    window.history.back();
}
</script>
<style>
.info-message {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff5f5; /* very light red/pink background */
    color: #b30000; /* dark red text */
    font-family: 'Poppins', sans-serif;
    font-size: 12px;
    font-weight: 500;
    padding: 12px 20px;
    border-radius: 10px;
    border: 2px solid #ff0000; /* bright red border */
    box-shadow: 0 3px 8px rgba(0,0,0,0.15);
    margin: 15px auto;
    max-width:100%;
    text-align: center;
}

.info-message i {
    margin-right: 10px;
    font-size: 18px;
}
</style>
     

        <!-- Live Search -->
        <input type="text" id="searchInput" placeholder="Search by student name, reg number, or subject...">

<?php
// Fetch unique values

?>

<div style="display:grid; grid-template-columns: repeat(4,1fr); gap:10px; margin-bottom:15px;">
    
    <select id="filterCode">
        <option value="">All Subject Codes</option>
        <?php foreach($codes as $c): ?>
            <option value="<?= strtolower($c) ?>"><?= htmlspecialchars($c) ?></option>
        <?php endforeach; ?>
    </select>

    <select id="filterName">
        <option value="">All Subjects</option>
        <?php foreach($names as $n): ?>
            <option value="<?= strtolower($n) ?>"><?= htmlspecialchars($n) ?></option>
        <?php endforeach; ?>
    </select>

    <select id="filterLevel">
        <option value="">All Levels</option>
        <?php foreach($levels as $l): ?>
            <option value="<?= strtolower($l) ?>"><?= htmlspecialchars($l) ?></option>
        <?php endforeach; ?>
    </select>

    <select id="filterSemester">
        <option value="">All Semesters</option>
        <?php foreach($sems as $s): ?>
            <option value="<?= strtolower($s) ?>"><?= htmlspecialchars($s) ?></option>
        <?php endforeach; ?>
    </select>

      <select id="filterStart">
        <option value="">Sem Start Date</option>
        <?php foreach($start as $s): ?>
            <option value="<?= strtolower($s) ?>"><?= htmlspecialchars($s) ?></option>
        <?php endforeach; ?>
    </select>

    <select id="filterStudyMode">
    <option value="">All Study Modes</option>
    <?php foreach($study_modes as $sm): ?>
        <option value="<?= strtolower($sm) ?>"><?= htmlspecialchars($sm) ?></option>
    <?php endforeach; ?>
</select>

</div>


        <table id="gradesTable">
           <thead>
    <!-- First row: group headers -->
    <tr>
       
        <th rowspan="2">Reg. Number</th>
         <th rowspan="2">Student Name</th>
        <th rowspan="2">Code</th>
        <th colspan="3"><center>Assignments</center></th>
        <th colspan="2"><center>Mid Semester</center></th>
        <th colspan="2"><center>End Semester</center></th>
        <th colspan="2"><center>Final Grade</center></th>
    </tr>
    <!-- Second row: sub-headers -->
    <tr>
        <!-- Assignments -->
        <th><center>1</center></th>
        <th><center>2</center></th>
         <th><center>Total</center></th>
        <!-- Mid Semester -->
       
        <th><center>1</center></th>
         <th><center>Total</center></th>
        <!-- End Semester -->
         <th><center>1</center></th>
        <th><center>Total</center></th>
          <!-- Final Grade -->
            
         <th><center>Total</center></th>
       
       
    </tr>
</thead>
            <tbody>
<?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)): 
    $grade_one = (int)($row['grade_one'] ?? 0);
    $grade_two = (int)($row['grade_two'] ?? 0);
    $grade_three = (int)($row['grade_three'] ?? 0);
    $grade_three_02 = (float)($row['grade_three'] ?? 0) * 0.2;
    $grade_four = (int)($row['grade_four'] ?? 0);

        $grade_three_04 = (float)($row['grade_four'] ?? 0) *0.6;
    $total = $grade_one * 0.1 + $grade_two * 0.1  + $grade_three * 0.2 + $grade_four * 0.6;
    $row_class = ($grade_one === 0) ? 'orange' : '';
?>
<tr class="<?= $row_class ?>"
    data-code="<?= strtolower($row['subject_code'] ?? '') ?>"
    data-name="<?= strtolower($row['subject_name'] ?? '') ?>"
    data-level="<?= strtolower($row['year'] ?? '') ?>"
    data-start="<?= strtolower($row['start_date'] ?? '') ?>"
    data-sem="<?= strtolower($row['semester_no'] ?? '') ?>"
    data-study="<?= strtolower($row['study_mode'] ?? '') ?>">

    <td><a href="student_grades_view.php?registration_number=<?= $row['registration_number'] ?>">
    <?= htmlspecialchars($row['registration_number']) ?>
</a><br/><span style="font-size:10px; color:#000; font-weight:bold;">
    <?=
        (!empty($row['start_date']) ? date('M Y', strtotime($row['start_date'])) : '') .
        (!empty($row['end_date']) ? ' - ' . date('M Y', strtotime($row['end_date'])) : '')
    ?>
</span></td>
    <td><?= htmlspecialchars($row['firstname']) ?></td>
    <td><?= htmlspecialchars($row['subject_code']) ?></td>
<?php
    $grade_one   = (float)$row['grade_one'];
$grade_two   = (float)$row['grade_two'];
$grade_three = (float)$row['grade_three'];
?>
    <td class="<?= ($grade_one == 0) ? 'zero-highlight' : '' ?>"><input type="text" class="grade1-inputt" data-id="<?= $row['grade1_id'] ?>" value="<?= $grade_one ?>"></td>
    <td class="<?= ($grade_two == 0) ? 'zero-highlight' : '' ?>"><input type="text" class="grade2-inputt" data-id="<?= $row['grade2_id'] ?>" value="<?= $grade_two ?>"></td>
  <td>
    <b><?= htmlspecialchars(number_format((($row['grade_one'] + $row['grade_two']) * 0.2) / 2, 2)) ?></b>
</td>
    <td class="<?= ($grade_three == 0) ? 'zero-highlight' : '' ?>"><input type="text" class="grade3-inputt" data-id="<?= $row['grade3_id'] ?>" value="<?= $grade_three ?>"></td>
     <td>
   <b><?= htmlspecialchars(number_format($grade_three_02, 2)) ?></b>
</td>
    <td class="<?= ($grade_four == 0) ? 'zero-highlight' : '' ?>"><input type="text" class="grade4-inputt" data-id="<?= $row['grade4_id'] ?>" value="<?= $grade_four ?>"></td>
        <td><b><?= htmlspecialchars(number_format($grade_three_04, 2)) ?></b></td>
   <?php
    $status = ($total >= 50) ? 'P' : 'F'; // Pass or Fail
    $icon   = ($total >= 50) ? 'fa-check-circle' : 'fa-times-circle'; // Font Awesome icons
    $iconColor = ($total >= 50) ? 'green' : 'red';
?>
<td>
    <b><?= $total ?></b>
    <i class="fas <?= $icon ?>" style="color: <?= $iconColor ?>; margin-left:5px;" title="<?= $status ?>"></i>
    <span style="margin-left:5px; font-weight:bold; color: <?= $iconColor ?>;"><?= $status ?></span>
</td>

</tr>
<?php endwhile; ?>
</tbody>
        </table>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
   $(document).ready(function(){

    function filterTable() {
        var search = $("#searchInput").val().toLowerCase().trim();
        var code   = $("#filterCode").val().toLowerCase().trim();
        var name   = $("#filterName").val().toLowerCase().trim();
        var level  = $("#filterLevel").val().toLowerCase().trim();
        var sem    = $("#filterSemester").val().toLowerCase().trim();
          var start    = $("#filterStart").val().toLowerCase().trim();
          var study = $("#filterStudyMode").val().toLowerCase().trim();

        $("#gradesTable tbody tr").each(function() {

            var rowText = $(this).text().toLowerCase();

            var rowCode  = ($(this).data("code") + "").toLowerCase().trim();
            var rowName  = ($(this).data("name") + "").toLowerCase().trim();
            var rowLevel = ($(this).data("level") + "").toLowerCase().trim();
            var rowSem   = ($(this).data("sem") + "").toLowerCase().trim();
              var rowStart   = ($(this).data("start") + "").toLowerCase().trim();
              var rowStudy = ($(this).data("study") + "").toLowerCase().trim();

           var match =
    rowText.includes(search) &&
    (code === "" || rowCode.includes(code)) &&
    (name === "" || rowName.includes(name)) &&
    (level === "" || rowLevel.includes(level)) &&
    (sem === "" || rowSem.includes(sem)) &&
    (start === "" || rowStart.includes(start)) &&
    (study === "" || rowStudy.includes(study));

            $(this).toggle(match);
        });
    }

    // Filters trigger
  $("#searchInput, #filterCode, #filterName, #filterLevel, #filterSemester, #filterStart, #filterStudyMode")
    .on("keyup change", filterTable);


    // Grade update
    $('input[class^="grade"]').on('input', function() {
        this.value = this.value.replace(/[^0-9]/g,'');
    }).on('change', function() {

        var id = $(this).data('id');
        var grade = $(this).val();
        var type = $(this).attr('class').split('-')[0];

        var row = $(this).closest('tr');
        var total = 0;

        row.find('input[class^="grade"]').each(function() {
            total += parseInt($(this).val()) || 0;
        });

        row.find('td:last').text(total);

        $.ajax({
            type: 'POST',
            url: 'edit_grades_all.php',
            data: { id: id, grade: grade, type: type },
            dataType: 'json',
            success: function(response) {
                if(response.status !== 'success'){
                    alert('Error updating grade: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert('AJAX Error: ' + error);
            }
        });

    });

});

   $('input[class^="grade"]').each(function(){
    if(parseInt($(this).val()) !== 0){
        $(this).prop('disabled', true);
    }
});
    </script>
</body>
</html>