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

<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;
}

.negative{
    width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10px;
    margin-top: 20px;
}
.negative i{
    font-size: 70px;
    color: #FE9C13;

}
.negative h5{
    font-size: 20px;
    color: #FE9C13;
    text-align: center;
    /*font-weight: bold;*/
    font-family: sans-serif; 
}
.negative a{
    padding: 10px;
    color: #fff;
    text-decoration: none;
    text-align: center;
    font-size: 17px;
    border-radius: 5px;
    /*font-weight: bold;*/
}
.negative a i{
    font-size: 17px;
    color: #fff;
}
.card-header{
    width: 100%;
    display: flex; 
    align-items: center; 
    justify-content: space-between;
}
.break-btn{
    display: flex;
    gap:10px;
}
@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{
    }
}
.break-btn{
    display: flex;
    gap:5px;
}
@media(max-width: 992px){
    
    .card-header{
        justify-content: space-between!important;
    }
   
    .text-sm{
        font-size: 12px;
    }
}
</style>
<?php

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

    $class      = $unvel[0];
    $subject    = $unvel[1]; 
    $go_back_link = "sub.php?class=$class"; 
}else{
    header('Location:disp-std.php');
}

$msgActionBtn = '';
$moveNdxtLink = "sub.php?class=$class";
if (isset($_POST['move-btn'])) {
    header("Location:$moveNdxtLink");
}

if (isset($_POST['upd-btn'])) {
    $rstId      = $_POST['rstId'];
    $stdId      = $_POST['stdId'];
    $surName    = $_POST['surName'];
    $examMark   = $_POST['examMark'];
    $totalMark  = $_POST['totalMark'];
    $gradeMark  = $_POST['gradeMark'];
    $adminNo    = $_POST['adminNo'];


    $errors = [];
    for ($i=0; $i < count($stdId) ; $i++) { 
        $total = $totalMark[$i];
        $stdName = $surName[$i];
        if ($total > 100) {
            $errors[] = "Student {$stdName}: Exam score is {$total} (Max allowed is 100)";
        }
    }
    if (!empty($errors)) {
        // Save the failed entries into failed table
        for ($i=0; $i < count($stdId); $i++) { 
            $studentId = $stdId[$i];
            $resultId  = $rstId[$i]; // Set to resultId

            $exam = $examMark[$i];
            $total = $totalMark[$i];
            $grade = $gradeMark[$i];
            $adNo  = $adminNo[$i];

            $totalStd = count($studentId);

            // Avoid duplicates entries
            $checDupl = "SELECT * FROM failed_entries 
                        WHERE adminNo = ? AND subject = ? 
                        AND class = ? AND session = ? AND term = ? ";
            $duplStmt = $pdo->prepare($checDupl);
            $duplStmt->execute([$adNo, $subject, $class, $current_session, $current_term]);
            $countDupl = $duplStmt->rowCount();
            if ($countDupl == TRUE) {
                // update the data in the student result db
                $updaQuery = "UPDATE failed_entries SET exam_score = ?, 
                                total_score = ?, grade = ? 
                                WHERE adminNo = ? AND subject = ? 
                                AND class = ? AND session = ? AND term = ? ";
                $updatePdo = $pdo->prepare($updaQuery);
                $updatePdo->execute([$exam, $total, $grade, 
                    $adNo, $subject, $class, $current_session, $current_term]);
            }else{

                // insert the data in the student result db
                $failedSql = "INSERT INTO failed_entries (adminNo, exam_score,
                             total_score, grade, subject, class, session, term)
                             VALUES(?,?,?,?,?,?,?,?)";
                $failedStmt = $pdo->prepare($failedSql);
                $failedStmt->execute([$adNo, $exam, $total, $grade, 
                    $subject, $class, $current_session, $current_term]);
            }   
        }
        // Then display the error message
        $msgTitle   = "Exam Score Input Error";
        $msgBody    = "Please review your entries.<br>
                    Each student's total score must not exceed 100.
                    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($stdId); $i++) { 
            $studentId = $stdId[$i];
            $resultId  = $rstId[$i]; // Set to resultId

            $exam = $examMark[$i];
            $total = $totalMark[$i];
            $grade = $gradeMark[$i];
            $adNo  = $adminNo[$i];

            $totalStd = count($studentId);

            // Update the data in the student result db
            $updaQuery = "UPDATE results SET exam_score = ?, total = ?, grade = ? 
                            WHERE resultId = ? ";
            $updatePdo = $pdo->prepare($updaQuery);
            $updatePdo->execute([$exam, $total, $grade, $resultId]);

            // Delete failed entries if exist
            $delFailed = "DELETE FROM failed_entries 
                            WHERE adminNo = ? AND subject = ? 
                            AND class = ? AND session = ? AND term = ? ";
            $delStmt = $pdo->prepare($delFailed);
            $delStmt->execute([$adNo, $subject, $class, $current_session, $current_term]); 
        }
        
        $msgTitle = "Exam Grading Updated";
        $totalStd = count($stdId);
        $zeroScores = 0;

        for ($i=0; $i < $totalStd; $i++) { 
            $exam = $examMark[$i];

            if (empty($exam) || $exam == 0) {
                $zeroScores ++;
            }
        }
        $msgBody = "$totalStd students have been graded 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 exam scores here, or from the Student List.";
        }else{
            $msgBody .= "<br><br>
                        <b>Note:</b> Any adjustment can be made when the current session is still active.";
        }
        $msgBody.= "<br><small class='text-danger'><i>Would you like to view the current scores or view all students score in the list?</i></small>";

        $msgCloseBtn = "No, I'll view the scores";
        $msgActionBtn = "Yes, view all student score list";
            include'includes/success-alert.php';
    }
}

if (isset($_POST['test-rec-btn'])) {
    header("Location:test_score.php?class=$class*$subject");
}

?>

<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
                        $checktest2 = 'Pending';
                        $rels = "SELECT second_test FROM results WHERE subject = ? 
                                AND class = ? AND term = ? AND session = ? AND second_test != ?";
                        $reslpdo = $pdo->prepare($rels);
                        $reslpdo->execute([$subject, $class, $current_term,$current_session, $checktest2]);
                        $countrow = $reslpdo->rowCount();
                        if ($countrow == TRUE) {?>
                            <button class="btn btn-sm success text-white" name="upd-btn">
                                <i class="fa fa-save"></i> Save Scores
                            </button>
                        <?php } else {?>
                            <button class="btn info text-white" name="test-rec-btn">
                                Start Test Score <i class="fa fa-save"></i>
                            </button>
                        <?php }
                        ?>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header text-center">
                        <h5>
                            Add/Edit Exam Score for <?=$class?> 
                        </h5>
                        <div class="">
                            <a href="<?=$go_back_link?>" class="btn btn-sm text-white primary"><i class="fa fa-arrow-left" style="font-size: 10px;"></i> Go back </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php
                        if ($countrow == FALSE) {?>
                            <div class="negative">
                                <i class="fa fa-clipboard-list"></i>
                                <h5>
                                    No Test Records Yet for <b><?=$subject?></b> - 
                                    <b><?=$class?></b> <br> 
                                    <small>(<?=$current_session?> Session, 
                                        <?=$current_term?> Term)
                                    </small>
                                </h5>
                                <p style="font-size:14px; color:#555;">
                                    Please record the <b>Test Scores</b> 
                                    before proceeding to grade the exam.
                                </p>
                                <a href="test_score.php?class=<?=$class.'*'.$subject?>" 
                                    class="warning">
                                    Record Test Scores <i class="fa fa-pencil-alt"></i> 
                                </a>
                            </div>
                        <?php }else{?>

                            <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="6" class="text-sm">ID</th>
                                            <th data-priority="1" class="text-sm">Surname</th>
                                            <th data-priority="2" class="text-sm">RegNo</th>
                                            <th data-priority="3" class="text-sm">CA1 (20)</th>
                                            <th data-priority="4" class="text-sm">CA2 (10)</th>
                                            <th data-priority="1" class="text-sm">Exam Score (70)</th>                                        
                                            <th data-priority="1" class="text-sm">Total</th>
                                            <th data-priority="5" class="text-sm">Grade</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $sn = 0;
                                        // Get the test and exam details from the result tb

                                        $fetch = "SELECT * FROM results WHERE subject = ? 
                                            AND class = ? AND term = ? AND session = ?";
                                        $stmt = $pdo->prepare($fetch);
                                        $stmt->execute([$subject, $class, $current_term,
                                                        $current_session]);
                                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                            $sn         = $sn + 1;
                                            $restId     = $row['resultId'];
                                            $studId      = $row['stdId'];
                                            $testScore  = $row['test_score'];
                                            $examScore  = $row['exam_score'];
                                            $test2      = $row['second_test'];
                                            $totalScore = $row['total'];
                                            $grade      = $row['grade'];
                                            if ($examScore == 'pending') {
                                                $examGrade = 0;
                                            }else{
                                                $examGrade = $examScore;
                                            }

                                            // collectt normal students info
                                            $stdInfo = "SELECT * FROM student WHERE adminNo = ?";
                                            $stdPdo = $pdo->prepare($stdInfo);
                                            $stdPdo->execute([$studId]);
                                            while ($stdRow = $stdPdo->fetch(PDO::FETCH_ASSOC)) {
                                                $adminNo    = $stdRow['adminNo'];
                                                $stdId      = $stdRow['studId'];
                                                $surName    = $stdRow['surname'];
                                                $otherNames = $stdRow['otherNames'];
                                                $sn = $sn ++;

                                                $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);


                                            $exam_score = isset($entryRow['exam_score']) ? 
                                            $entryRow['exam_score'] : $examGrade;

                                            $totalScore = isset($entryRow['total_score']) ?
                                            $entryRow['total_score'] : $totalScore;

                                            $allGrade = isset($entryRow['grade']) ?
                                            $entryRow['grade'] : $grade;
                                            ?>
                                            <tr>
                                                <td></td>
                                                <td class="text-sm"><?= $sn ?></td>
                                                <td class="text-sm"> <?=$fullNames?></td>
                                                <td class="admin-text"><?=$adminNo?></td>
                                                <td>
                                                    <input type="text"
                                                    style="width:80px; cursor: not-allowed;"
                                                    class="short-input" 
                                                    name="" placeholder="Enter Score" disabled="" 
                                                    id="testScore-<?=$stdId?>" 
                                                    value="<?= $testScore?>">
                                                </td>

                                                <td>
                                                    <input type="text"
                                                    style="width:80px; cursor: not-allowed;"
                                                    class="short-input" 
                                                    name="" placeholder="Enter Score" disabled="" 
                                                    id="test2-<?=$stdId?>" 
                                                    value="<?= $test2?>">
                                                </td>

                                                <td>
                                                    <input type="number" class="short-input" 
                                                    name="examMark[]" placeholder="Enter Score" 
                                                    onkeyup="examScore(<?= $stdId?>)"
                                                    id="exam-<?= $stdId?>" 
                                                    value="<?= $exam_score?>">
                                                </td>

                                                <td>
                                                    <input type="number" 
                                                    style="cursor: not-allowed;"
                                                    class="short-input" 
                                                    disabled="" 
                                                    id="totalScore-<?= $stdId?>" 
                                                    value="<?= $totalScore?>">
                                                </td>

                                                <td>
                                                    <input type="text" 
                                                    style="cursor: not-allowed;"
                                                    class="form-control" 
                                                    disabled="" id="remarks-<?= $stdId?>" 
                                                    value="<?= $allGrade?>">
                                                </td>

                                                <!-- Hidden input -->
                                                <!-- StudentId -->
                                                <input type="hidden" name="stdId[]" 
                                                value="<?= $stdId?>">
                                                <!-- resultId -->
                                                <input type="hidden" name="rstId[]" 
                                                value="<?= $restId?>">
                                                <!-- Student Surname -->
                                                <input type="hidden" name="surName[]" 
                                                value="<?=$surName?>">

                                                <!-- hidden grademark -->
                                                <input type="hidden" name="gradeMark[]"
                                                 id="hiddenRemarks-<?= $stdId?>" 
                                                value="<?= $allGrade?>">
                                                <!-- hidden totalMark -->
                                                <input type="hidden" name="totalMark[]" 
                                                id="hiddenTotal-<?= $stdId?>" 
                                                value="<?= $totalScore?>">
                                                <!-- hidden adminNo -->
                                                <input type="hidden" name="adminNo[]"
                                                value="<?=$adminNo?>"> 
                                                
                                            </tr>
                                        <!-- End while loop -->
                                        <?php } }?>
                                    </tbody>
                                </table>
                            </div>
                        <?php } ?>  
                    </div>
                </div>
            </form>
        </div>
   
    </div>
</div>

<script>
    function examScore(stdId){
        let testScore = document.getElementById('testScore-' + stdId);
        let test2 = document.getElementById('test2-' + stdId);
        let exam = document.getElementById('exam-' + stdId);
        let total = document.getElementById('totalScore-' + stdId);
        let remarks = document.getElementById('remarks-' + stdId);

        // hidden input to submit to database
        let hiddenTotal = document.getElementById('hiddenTotal-' + stdId);
        let hiddenRemarks = document.getElementById('hiddenRemarks-' + stdId);

        let test = parseInt(testScore.value);
        let secondTest = parseInt(test2.value);
        let examScore = parseInt(exam.value);

        let sum = test + secondTest + examScore;
        total.value = sum;
        hiddenTotal.value = sum;

        let grade = sum;

        if (grade < 30) {
            remarks.value = "Very Poor";
            hiddenRemarks.value = "Very Poor";
        } else if (grade >= 30 && grade < 40) {
            remarks.value = "Poor";
            hiddenRemarks.value = "Poor";
        } else if (grade >= 40 && grade < 50) {
            remarks.value = "Fair";
            hiddenRemarks.value = "Fair";
        } else if (grade >= 50 && grade < 70) {
            remarks.value = "Good";
            hiddenRemarks.value = "Good";
        }else if (grade >= 70 && grade < 101) {
            remarks.value = "Excellent";
            hiddenRemarks.value = "Excellent";
        } else {
            remarks.value = "Error";
            hiddenRemarks.value = "Error";
        }
    }


</script>

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


<!-- 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: 768px) {
  .short-input, .disp-input {
    width: 90px !important;
    font-size: 13px;
    padding-left: 1px;
    text-align: center;
  }
  .admin-text{
      font-size: 13px;
  }
  table.dataTable.dtr-inline.collapsed>tbody>tr>td:first-child:before {
    background-color: #007bff !important;
    color: white;
    border: none;
  }
</style>
<!-- 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       // first column used for toggle
      }
    },
    columnDefs: [
      { className: 'control', orderable: false, targets: 0 }, // toggle column
      { targets: 2, responsivePriority: 1 }, // Admin No. - always visible
      { targets: 6, responsivePriority: 1 }, // Score - always visible
      { targets: 7, responsivePriority: 1 }, // Total - always visible
      { targets: [3, 4, 5, 8], responsivePriority: 10 }, // hide Surname & Othernames first on mobile
      { orderable: false, targets: [6, 7] } // 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>


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

