<?php session_start();?>
<?php include'includes/header.php'; ?>
<?php include'includes/sidebar.php';?>
<?php include'includes/functions.php';?>
<?php include'includes/navbar.php'; ?>

<!-- This page unique styles -->
<style>
/*Core setup styles*/
.sideNav{
    height: 100%;
    /*width: 220px;*/
    position: fixed;
    z-index: 9;
}
.navbar{
    top: 0;
    position: fixed;
    z-index: 9999;
}
.the-links{
    padding-top: 10px;
}
/*.nav-links{
    height: 100%;
    overflow-y: auto;
}*/
.insider{
    margin-top: 10px;
    position: relative;
}
.card{
    height: auto;
}
.cat-pag{
    position: relative;
}
.cat-page-header{
    position: sticky;
    width: 100%;
    height: 50px;
    background:#F7F9FB; 
    top: 60px;
    right: 60px;
    z-index: 1;
}
@media(max-width: 992px){
.insider{
    margin-top: 10px;
    padding-left: 10px;
    padding-right: 10px;
    }        
}
.card-header h5{
    font-size: 14px;
}

@media(max-width: 992px){
    .negative h5{
        font-size: 15px;
    }
    .negative a{
        font-size: 14px;
    }
    .negative a i{
        font-size: 14px;
    }
    .test-input{
        width: 20px;
    }
    .disp-input{

    }
}
</style>
<?php

if (isset($_GET['class'])) {
    $getVal = $_GET['class'];
    $unvel = explode('*', $getVal);

    $class = $unvel[0];
    $subject = $unvel[1];
    $go_back_link = "sub.php?class=$class";

}else{

}
$msgActionBtn = '';
$moveNdxtLink = "second_test.php?class=$class*$subject";
// Move to next step
if (isset($_POST['move-btn'])) {
    header("Location:$moveNdxtLink");
}
// Add Student test
if (isset($_POST['add-btn'])) {
    $detect = $_POST['detect'];
    $studId = $_POST['studId'];
    $test   = $_POST['test'];
    $surName = $_POST['surName'];
    $adminNo  = $_POST['adminNo'];
    $errors = [];

    $gradedCount     = 0;
    $ignoredCount    = 0; // empty scores
    $zeroScoreCount  = 0; // score = 0
    $failedCount     = 0; // if needed

    for ($i=0; $i < count($studId) ; $i++) { 
        $stdTest = $test[$i];
        $stdName = $surName[$i];
        if ($stdTest > 20) {
            $errors[] = "Student {$stdName}: Test score is {$stdTest} (Max allowed is 20)";
        }
    }
    if (!empty($errors)) {

        for ($i=0; $i < count($studId); $i++) { 
            $stdId = $studId[$i]; // insert this as oldstdId
            $score = $test[$i];
            $adNo = $adminNo[$i];

            // Avoid duplicates entries
            $dupSql = "SELECT * FROM failed_entries
                    WHERE adminNo = ? AND subject = ?
                    AND class = ? AND session = ? AND term = ?";
            $dupStmt = $pdo->prepare($dupSql);
            $dupStmt->execute([$adNo, 
                $subject, $class, 
                $current_session, $current_term]);
            $countDup = $dupStmt->rowCount();
            if ($countDup == TRUE) {
                $updDup = "UPDATE failed_entries SET test_scores = ? 
                    WHERE adminNo = ? AND subject = ? AND class = ? 
                    AND session = ? AND term = ?";
                $updStmt = $pdo->prepare($updDup);
                $updStmt->execute([$score, $adNo, 
                $subject, $class, 
                $current_session, $current_term ]);
            }else{
                // Insert the data in the student result db
                if ($score != '') {
                    $sql_fail = "INSERT INTO failed_entries 
                        (adminNo, test_scores, subject, class, session, term)
                             VALUES (?, ?, ?, ?, ?, ?)";
                    $failpdo = $pdo->prepare($sql_fail);
                    $failpdo->execute([
                        $adNo,
                        $score,
                        $subject, 
                        $class, 
                        $current_session,
                        $current_term
                    ]);
                }
            }
        }

        $msgTitle   = "Test Score Input Error";
        $msgBody    = "Please review your entries.<br>
                    Each student's test score must not exceed 20.
                    Kindly correct the highlighted errors and try again.";
        $msgBody .= "<br><br><b>Details:</b><ul>";
                    foreach ($errors as $err) {
                        $msgBody .= "<li>$err</li>";
                    }
        $msgBody .= "</ul>";
        $msgCloseBtn = "Okay, got it.";
        include'includes/alertMsg-blur.php';
    }else{
        try {
            // ✅ Start Transaction
            $pdo->beginTransaction();

            for ($i=0; $i < count($studId); $i++) { 
                $stdId = $studId[$i]; // insert this as oldstdId
                $score = $test[$i];
                $totalStd = count($studId);
                $adNo = $adminNo[$i];

                if ($score === '' || $score === null) {
                    $ignoredCount++;
                    continue;
                }
                if ($score === '0' || $score === 0) {
                    $zeroScoreCount++;
                }

                // Insert the data in the student result db
                // avoid inserting student that their score is empty
                if ($score != '') {
                    $inst = "INSERT INTO results (oldstdId, stdId, 
                            subject, class, term, session, test_score)
                            VALUES (?, ?, ?, ?, ?, ?, ?)";
                    $instpdo = $pdo->prepare($inst);
                    $instpdo->execute([$stdId, $adNo, $subject, 
                            $class, $current_term, 
                            $current_session, $score]);
                    $gradedCount++;
                }

                // Delete if there is failed entries
                $delFailed = "DELETE FROM failed_entries 
                    WHERE adminNo = ? AND subject = ?
                    AND class = ? AND session = ? AND term = ?";
                $delFailedStmt = $pdo->prepare($delFailed);
                $delFailedStmt->execute([$adNo, 
                    $subject, $class, 
                    $current_session, $current_term]);
            }

            // ✅ Commit only when all are successful
            $pdo->commit();

            // Success message
            $msgTitle = "Test Grading Summary";
            $msgBody = "";

            // graded
            $msgBody .= "<b>$gradedCount</b> student(s) graded successfully out of <b>".
            count($studId)."</b>.<br>";

            // ignored (only show if >0)
            if ($ignoredCount > 0) {
                $msgBody .= "<b>$ignoredCount</b> student(s) were ignored (no score entered).<br>";
            }

            // zero score (only show if >0)
            if ($zeroScoreCount > 0) {
                $msgBody .= "<b>$zeroScoreCount</b> student(s) scored zero (0).<br>";
            }

            // failed (if applicable)
            if ($failedCount > 0) {
                $msgBody .= "<b>$failedCount</b> student(s) failed to save.</b><br>";
            }

            $msgBody.= "<br><small class='text-danger'><i>Would you like to view the scores or   proceed to the second CA?</i></small>";

            $msgCloseBtn = "No, I'll view the scores";
            $msgActionBtn = "Yes, proceed to second CA";
            include 'includes/success-alert.php';

        } catch (Exception $e) {
            // ❌ If any error occurs, rollback all
            $pdo->rollBack();

            $msgTitle = "Database Error";
            $msgBody = "An error occurred while saving results. Please try again.<br><br><b>Technical details:</b> " . $e->getMessage();
            $msgCloseBtn = "Close";
            include 'includes/alertMsg-blur.php';
        }
    }
}

// Update Student Test
if (isset($_POST['upd-btn'])) {
    $detect = $_POST['detect'];
    $theStId = $_POST['stdId'];
    $test   = $_POST['test'];
    $surName = $_POST['surName'];
    $resultId = $_POST['resultId'];
    
    
    $errors = [];
    for ($i=0; $i < count($theStId) ; $i++) { 
        $stdTest = $test[$i];
        $stdName = $surName[$i];
        if ($stdTest > 20) {
            $errors[] = "Student {$stdName}: Test score is {$stdTest} (Max allowed is 20)";
        }
    }
    if (!empty($errors)) {
        $msgTitle   = "Test Score Input Error";
        $msgBody    = "Please review your entries.<br>
                    Each student's test score must not exceed 20.
                    Kindly correct the highlighted errors and try again.";
        $msgBody .= "<br><br><b>Details:</b><ul>";
                    foreach ($errors as $err) {
                        $msgBody .= "<li>$err</li>";
                    }
        $msgBody .= "</ul>";
        $msgCloseBtn = "Okay, got it.";
        include'includes/alertMsg-blur.php';
    }else{
        for ($i=0; $i < count($theStId); $i++) { 
            $stdId = $theStId[$i];
            $rstId = $resultId[$i]; // Set to resultId

            $score = $test[$i];
            $totalStd = count($theStId);


            // Update the data in the student result db
            $updaQuery = "UPDATE results SET test_score = ? WHERE resultId = ? ";
            $updatePdo = $pdo->prepare($updaQuery);
            $updatePdo->execute([$score, $rstId]);
            
        }
        
        $msgTitle = "Test Grading Updated";
        $totalStudents = count($theStId);
        $zeroScores = 0;

        for ($i=0; $i < $totalStudents; $i++) { 
            $stdTest = $test[$i];

            if (empty($stdTest) || $stdTest == 0) {
                $zeroScores ++;
            }
        }
        $msgBody = "$totalStudents students have been updated successfully.";
        if ($zeroScores > 0) {
            $msgBody .= "<br><br> Note:
                        <b>$zeroScores student(s)</b> scored <b>0</b>.
                        If this was unintentional, you can easily update 
                        thier test scores from the Student List.";
            $msgCloseBtn = "Okay, got it";
            include'includes/success-alert.php';
        }else{
            $msgBody .= "<br><br>
                        <b>Note:</b> Any adjustment can be made in the Student List";
            $msgCloseBtn = "Alright, close";
            include'includes/success-alert.php';
        }
    }
}

?>

<div id="notification-containers" class="notification-containers"></div>
<div class="insider">
    <div class="container">
        <div class="cat-pag">
            <form action="" method="POST">
                <div class="cat-page-header d-flex justify-content-between align-items-center">
                    <h5></h5>
                    <div>
                        <?php
                        $rels = "SELECT test_score FROM results WHERE subject = ? 
                                AND class = ? AND term = ? AND session = ?";
                        $reslpdo = $pdo->prepare($rels);
                        $reslpdo->execute([$subject, $class, $current_term,$current_session]);
                        $countrow = $reslpdo->rowCount();
                        if ($countrow == TRUE) {?>
                            <button class="btn btn-sm success text-white" name="upd-btn">
                                <i class="fa fa-sync"></i> Update Scores 
                            </button>
                        <?php } else {?>

                        <button class="btn btn-sm success text-white" name="add-btn">
                            <i class="fa fa-save"></i> Save Scores
                        </button>

                        <?php }
                        ?>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header text-center" style="display: flex; align-items: center; justify-content: space-between;">
                        <h5>
                           <i class="fa fa-edit"></i> Add/Edit CA1 Score 
                        </h5>
                        <div class="">
                            <a href="<?=$go_back_link?>" class="btn btn-sm text-white primary " style="font-size: 10px;"> <i class="fa fa-arrow-left"></i> Go back</a>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="example" class="display table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th></th> <!-- This will be used for the toggle (+) -->
                                        <th data-priority="2" class="text-sm">Admin. No.</th>
                                        <th data-priority="1" class="text-sm">Names</th> 
                                        <th data-priority="1" class="text-sm">Score</th> <!-- visible on mobile -->
                                        <th data-priority="1">Total</th> <!-- optional on mobile -->
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sn = 0;
                                    if ($countrow == TRUE) { // Test score for this class exist

                                        $theupd = "SELECT * FROM results WHERE subject = ? 
                                                AND class = ? AND term = ? AND session = ? ";
                                        $uptPdo = $pdo->prepare($theupd);
                                        $uptPdo->execute([$subject, $class, 
                                                        $current_term, $current_session]);
                                        while ($testRow = $uptPdo->fetch(PDO::FETCH_ASSOC)) {
                                            $resultId   = $testRow['resultId'];
                                            $stdId      = $testRow['stdId'];
                                            $dataScore  = $testRow['test_score'];
                                            $sn = $sn + 1;

                                             // Get each std name by their Id
                                            $unamm = "SELECT * FROM student WHERE adminNo = ?";
                                            $unaPdo = $pdo->prepare($unamm);
                                            $unaPdo->execute([$stdId]);
                                            while ($stdRow = $unaPdo->fetch(PDO::FETCH_ASSOC)) {
                                                $adminNo    =   $stdRow['adminNo'];
                                                $stdId      = $stdRow['studId'];
                                                $stdSurname = $stdRow['surname'];
                                                $stdOthername = $stdRow['otherNames'];

                                                $shtn = explode(' ', $stdOthername);
                                                $name1 = $shtn[0];
                                                $name2 = isset($shtn[1])? $shtn[1]: '';
                                                $fullNames = $stdSurname.' '.$name1;

                                                ?>
                                                <tr>
                                                    <td></td>
                                                    <td class="text-sm"><?=$adminNo?></td>
                                                    <td class="text-sm"> <?=$fullNames?></td>
                                                    <td>
                                                        <input type="number" 
                                                        class="short-input test-input" 
                                                        name="test[]" placeholder="Enter Score" id="inputTest-<?=$stdId?>"
                                                        value="<?= $dataScore?>"
                                                         onkeyup="StdScore(<?=$stdId?>)">
                                                    </td>
                                                    <td>
                                                        <input type="text" 
                                                        class="short-input disp-input" 
                                                        name="" placeholder="<?= $dataScore?>/20" disabled="" 
                                                        id="showTotal-<?=$stdId?>">

                                                        <input type="hidden" value="" name="detect[]" 
                                                        id="detectMistake-<?=$studId?>">
                                                    </td>
                                                    
                                                    <!-- put all the variables in the hidden form -->
                                                    <input type="hidden" name="stdId[]" 
                                                    value="<?= $stdId?>">

                                                    <input type="hidden" name="adminNo[]" 
                                                    value="<?=$adminNo?>">

                                                    <input type="hidden" name="resultId[]" 
                                                    value="<?= $resultId?>">
                                                    
                                                    <input type="hidden" name="surName[]" 
                                                    value="<?= $stdSurname?>">
                                                </tr>
                                            
                                            <?php }
                                        }

                                    }else{ // Add New Test score for students

                                        $fetch = "SELECT * FROM student WHERE class = ?";
                                        $stmt = $pdo->prepare($fetch);
                                        $stmt->execute([$class]);
                                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                            $sn = $sn + 1;
                                            $studId = $row['studId'];
                                            $adminNo = $row['adminNo'];
                                            $surName = $row['surname'];
                                            $otherNames = $row['otherNames'];
                                            $gender = $row['gender'];

                                            $shtn = explode(' ', $otherNames);
                                            $name1 = $shtn[0];
                                            $name2 = isset($shtn[1])? $shtn[1]: '';
                                            $fullNames = $surName.' '.$name1;

                                            // Display the failed scores for this class if exist
                                            $entrySql = "SELECT * FROM failed_entries 
                                                    WHERE adminNo = ? AND subject = ?
                                                    AND class = ? AND session = ? AND term = ?";
                                            $entryStmt = $pdo->prepare($entrySql);

                                            $entryStmt->execute([$adminNo, 
                                                        $subject, $class, 
                                                        $current_session, $current_term]);
                                            $entryRow = $entryStmt->fetch(PDO::FETCH_ASSOC); 
                                                $failedScore = isset($entryRow['test_scores']) ? $entryRow['test_scores'] : '';
                                                $failedGrade = isset($entryRow['test_scores']) ? $entryRow['test_scores'] : 0;
                                            ?>
                                            <tr>
                                                <td></td>
                                                <td class="text-sm"><?=$adminNo?></td>
                                                <td class="text-sm"> <?=$fullNames?></td>
                                                <td>
                                                    <input type="number"
                                                    class="short-input test-input" 
                                                    name="test[]" 
                                                    placeholder="Enter Score" 
                                                    id="inputTest-<?=$studId?>"
                                                    value="<?=$failedScore?>" 
                                                    onkeyup="StdScore(<?=$studId?>)">
                                                </td>
                                                <td>
                                                    <input type="text" 
                                                    class="short-input disp-input" 
                                                    name="" placeholder="<?=$failedGrade?>/20" disabled="" 
                                                    id="showTotal-<?=$studId?>">

                                                    <input type="hidden" value="" name="detect[]" 
                                                    id="detectMistake-<?=$studId?>">
                                                </td>
                                                <!-- put all the variables in the hidden form -->
                                                <input type="hidden" name="studId[]" value="<?= $studId?>">
                                                <input type="hidden" name="surName[]" value="<?= $surName?>">
                                                <input type="hidden" name="adminNo[]" value="<?=$adminNo?>">
                                            </tr>
                                        
                                        <!-- End while loop -->
                                        <?php } }
                                    ?>
                                    
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </form>
        </div>
   
    </div>
</div>

<script>
    function StdScore(studId){
        let inputField = document.getElementById('inputTest-' + studId);
        let showScore = document.getElementById('showTotal-' + studId);
        let detectError = document.getElementById('detectMistake-' + studId);

        if (inputField.value <= 20) {
            let addTotal = inputField.value + '/20';
            showScore.value = addTotal;
            detectError.value = 'Good';
        }else{
            let addTotal = 'Error';
            showScore.value = addTotal;
            detectError.value = 'Error';
        } 
    }
</script>


<?php include 'includes/footer.php'; ?>

<!-- DataTables & jQuery -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css">

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<script>
$(document).ready(function () {
  $('#example').DataTable({
    responsive: {
      details: {
        type: 'column', // adds the (+) toggle
        target: 0,
        renderer: function(api, rowIdx, columns) {
          // Filter out Surname & Othernames from details
          let data = $.map(columns, function(col, i) {
            if (col.hidden && col.title !== 'Surname' && col.title !== 'Othernames') {
              return '<p><strong>' + col.title + ':</strong> ' + col.data + '</p>';
            }
            return '';
          }).join('');
          return data ? $('<div/>').append(data) : false;
        }
      }
    },
    columnDefs: [
      { className: 'control', orderable: false, targets: 0 },
      { targets: 2, responsivePriority: 1 }, // Admin No. - always visible
      { targets: 3, responsivePriority: 1 }, // Score - always visible
      { targets: 4, responsivePriority: 1 }, // Score - always visible
      { targets: [1], responsivePriority: 10 }, // hide Surname & Othernames first on mobile
      { orderable: false, targets: [2, 3, 4] } // no sorting on inputs     
      
    ],
    paging: false,
    searching: true,
    info: true,
    language: {
      emptyTable: "No student records found. Click 'Add Test' to add student records."
    }
  });
});
</script>
<script type="">
    responsive: true,
    dom: '<"top"lf>rt<"bottom"ip><"clear">',
</script>
<!-- Modal Styling -->
<style>
.modal {
    display: none;
    position: fixed;
    z-index: 99999;
    left: 0; top: 0;
    width: 100%; height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.5);

}

.modal-content {
    background-color: #fff;
    margin: auto;
    padding: 20px;
    border-radius: 8px;
    width: 80%;
    max-width: 500px;
    animation: fadeIn 0.3s;
}

.modal-header, .modal-footer {
    font-weight: bold;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-20px); }
    to { opacity: 1; transform: translateY(0); }
}

.label-wraps{
    width: 100%;
    padding-left: 30px;
    padding-right: 30px;
    display: flex;
    justify-content: space-between;
  
}
.input-wraps{
    width: 100%;
    display: flex;
    gap:8px;
    padding: 5px;
}
.price-box{
    width: 50%;
    height: 55px;
    /*border-bottom: 2px solid #ddd;*/
    border:2px solid #ddd;
    padding: 15px;
    border-radius: 10px;
}
.price-box span{
    font-size: 18px;
    color: #666;
    /*font-weight: bold;*/
}
.price-box input{
    width: 85%;
    
    border:none;
    outline: none;
    font-size: 16px;
    color: 888;
   /* height: 20px;*/
}
.quant-box{
    width: 50%;
    height: 55px;
    /*border-bottom: 2px solid #ddd;*/
    border:2px solid #ddd;
    padding: 15px;
    border-radius: 10px;
}
.quant-box input{
    width: 100%;
    border:none;
    outline: none;
    font-size: 16px;
    color: 888;
}
.short-input{
    width: 150px;
    height: 45px;
    border:2px solid #ddd;
    border-radius: 5px;
    outline: none;
    padding-left: 30px;
}
.disp-input{
    cursor: not-allowed;
}
@media(max-width: 992px){
    .short-input{
        width: 120px;
        font-size: 14px;
        padding-left: 1px;
        text-align: center;
    }
    .admin-text{
        font-size: 13px;
    }
    .text-sm{
      font-size: 12px;
      }
}

/*@media (max-width: 768px) {
  .disp-input {
    width: 80px !important;
    font-size: 13px;
  }
  .short-input {
    width: 80px !important;
    font-size: 13px;
  }
}*/
</style>
<style>
@media (max-width: 768px) {
  .short-input, .disp-input {
    width: 90px !important;
    font-size: 13px;
  }

  table.dataTable.dtr-inline.collapsed>tbody>tr>td:first-child:before {
    background-color: #007bff !important;
    color: white;
    border: none;
  }
}
</style>

<?php include'includes/notification-alert-js.php';?>