<?php
include('config.php');
session_start();

// ✅ Get registration number from URL
if (!isset($_GET['registration_number'])) {
    die("No student selected.");
}

$registration_number = $_GET['registration_number'];

// Handle AJAX grade update
if(isset($_POST['update_grade'])) {
    $table = $_POST['table'];
    $grade_id = $_POST['grade_id'];
    $new_grade = floatval($_POST['new_grade']);

    // Only allow updating grades >=0
    if($new_grade < 0) {
        echo json_encode(['status'=>'error','message'=>'Grade cannot be negative']);
        exit;
    }

    $column_map = [
        'assignments2'=>'grade',
        'assignments3'=>'grade',
        'exam_results_mid'=>'grade',
        'exam_results'=>'grade'
    ];

    if(isset($column_map[$table])) {
        $col = $column_map[$table];
        $stmt = $pdo->prepare("UPDATE $table SET $col = :grade WHERE id = :id");
        $stmt->execute([':grade'=>$new_grade, ':id'=>$grade_id]);
        echo json_encode(['status'=>'success','message'=>'Grade updated']);
        exit;
    }
}

try {
    $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.year,
        g.sem_number AS semester_no,
        sub.subject_name,
        sub.subject_code,
        a3.start_date,
        a3.end_date,
        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

    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

    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

    JOIN student_enrollments sub 
        ON g.subject_code = sub.subject_code

    JOIN students s 
        ON g.registration_number = s.registration_number

    WHERE g.registration_number = :reg
    ORDER BY g.year DESC, g.sem_number DESC, sub.subject_name ASC
    ";

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

} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage 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;
}



        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'); ?>

<h2 style="text-align:center;">
    Student Grades: <?= htmlspecialchars($registration_number) ?>
</h2>

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

<div class="feedback" id="feedback"></div>

<table>
<thead>
<tr>
    <th>Reg No</th>
    <th>Name</th>
    <th>Code</th>
    <th>Assign 1</th>
    <th>Assign 2</th>
    <th>Assign Total</th>
    <th>Mid 1</th>
    <th>Mid Total</th>
    <th>End 1</th>
    <th>End Total</th>
    <th>Total</th>
    <th>Edit</th>
</tr>
</thead>
<tbody>
<?php while($row = $stmt->fetch(PDO::FETCH_ASSOC)):
$g1 = (float)$row['grade_one'];
$g2 = (float)$row['grade_two'];
$g3 = (float)$row['grade_three'];
$g4 = (float)$row['grade_four'];
$total = $g1*0.1 + $g2*0.1 + $g3*0.2 + $g4*0.6;
?>
<tr data-grade1="<?= $row['grade1_id'] ?>" data-grade2="<?= $row['grade2_id'] ?>" data-grade3="<?= $row['grade3_id'] ?>" data-grade4="<?= $row['grade4_id'] ?>">
<td><?= htmlspecialchars($row['registration_number']) ?><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>

<td class="<?= $g1==0?'zero-highlight':'' ?>"><?= $g1 ?></td>
<td class="<?= $g2==0?'zero-highlight':'' ?>"><?= $g2 ?></td>
<td><?= number_format((($g1+$g2)*0.2)/2,2) ?></td>

<td class="<?= $g3==0?'zero-highlight':'' ?>"><?= $g3 ?></td>
<td><?= number_format($g3*0.2,2) ?></td>

<td class="<?= $g4==0?'zero-highlight':'' ?>"><?= $g4 ?></td>
<td><?= number_format($g4*0.6,2) ?></td>

<td>
    <b><?= number_format($total,2) ?></b>
    <?php if($total >= 50): ?>
        <i class="fas fa-check" style="color:green; margin-left:5px;"></i>
    <?php else: ?>
        <i class="fas fa-times" style="color:red; margin-left:5px;"></i>
    <?php endif; ?>
</td>

<td>
    <?php if($g1==0 || $g2==0 || $g3==0 || $g4==0): ?>
        <button class="button edit-btn">Edit</button>
        <button class="button save-btn" style="display:none;">Save</button>
        <button class="button cancel-btn" style="display:none; background-color:red;">Cancel</button>
    <?php else: ?>
        -
    <?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>

<script>
// Handle inline editing
document.querySelectorAll('tr').forEach(row=>{
    const editBtn = row.querySelector('.edit-btn');
    const saveBtn = row.querySelector('.save-btn');
    const cancelBtn = row.querySelector('.cancel-btn');
    if(!editBtn) return;

    editBtn.addEventListener('click', ()=>{
        // Replace zero grades with input fields
        row.querySelectorAll('td').forEach((td,index)=>{
            if(td.classList.contains('zero-highlight')){
                const val = td.innerText;
                td.innerHTML = `<input type="number" min="0" class="grade-input" value="${val}">`;
            }
        });
        editBtn.style.display='none';
        saveBtn.style.display='inline-block';
        cancelBtn.style.display='inline-block';
    });

    cancelBtn.addEventListener('click', ()=>{
        location.reload();
    });

    saveBtn.addEventListener('click', ()=>{
        const feedback = document.getElementById('feedback');
        const inputs = row.querySelectorAll('input.grade-input');
        let updates = [];
        inputs.forEach((inp,idx)=>{
            let grade_id = null, table=null;
            if(idx==0) { grade_id=row.dataset.grade1; table='assignments2'; }
            else if(idx==1) { grade_id=row.dataset.grade2; table='assignments3'; }
            else if(idx==2) { grade_id=row.dataset.grade3; table='exam_results_mid'; }
            else if(idx==3) { grade_id=row.dataset.grade4; table='exam_results'; }

            updates.push({grade_id, table, value: inp.value});
        });

        let completed=0;
        updates.forEach(u=>{
            if(!u.grade_id) { completed++; return; }
            fetch('',{
                method:'POST',
                headers:{'Content-Type':'application/x-www-form-urlencoded'},
                body:`update_grade=1&table=${u.table}&grade_id=${u.grade_id}&new_grade=${u.value}`
            }).then(r=>r.json()).then(res=>{
                completed++;
                if(completed==updates.length){
                    feedback.innerText = 'Grades updated successfully!';
                    feedback.style.color='green';
                    location.reload();
                }
            });
        });
    });
});
</script>
</body>
</html>