<?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;
}
.card-header{
    width: 100%;
    display: flex; 
    align-items: center; 
    justify-content: space-between;
}

@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{

    }
    .card-header{
        flex-direction: row;
    }
    .break-btn{
        display: flex;
        gap:20px;
    }
    .text-sm{
        font-size: 12px;
    }
}
.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;
}
@media(max-width: 992px){
    .cat-page-header{
        
    }
}
</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 = "exam_score.php?class=$class*$subject";

// Move next link 
if (isset($_POST['move-btn'])) {
    header("Location:$moveNdxtLink");
}

// Update Student Test
if (isset($_POST['upd-btn'])) {
    $detect = $_POST['detect'];
    $theStId = $_POST['stdId'];
    $test   = $_POST['test'];
    $surName = $_POST['surName'];
    $resultId = $_POST['resultId'];
    $adminNo = $_POST['adminNo'];
    
    
    $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)) {

        for ($i=0; $i < count($theStId); $i++) { 
            $stdId = $theStId[$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 second_test = ? 
                    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
                $sql_fail = "INSERT INTO failed_entries 
                    (adminNo, second_test, 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{
        for ($i=0; $i < count($theStId); $i++) { 
            $stdId = $theStId[$i];
            $rstId = $resultId[$i]; // Set to resultId
            $adNo = $adminNo[$i];

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

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

            // 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]);
        }
        
        $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 saved 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.";
        }else{
            $msgBody .= "<br><br>
                        <b>Note:</b> Any adjustment can be made in the Student List";
        }
        $msgBody.= "<br><small class='text-danger'><i>Would you like to view the scores or   proceed to exam grading?</i></small>";

        $msgCloseBtn = "No, I'll view the scores";
        $msgActionBtn = "Yes, proceed to exam grading";
        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
                        $rels = "SELECT second_test 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-save"></i> Save Scores 
                            </button>
                        <?php } else {?>
                        <button class="btn info text-white" name="test-rec-btn">
                            Add First Test <i class="fa fa-save"></i>
                        </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 Second C.A. Scores
                        </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">
                        <?php
                        if ($countrow == FALSE) {?>
                        <div class="negative">
                            <i class="fa fa-clipboard-list"></i>
                            <h5>
                                No First 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 First 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="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;
                                $stam = 'Pending';
                                $mmstam = '';

                                $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'];
                                    $secondScore  = $testRow['second_test'];
                                    $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;

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

                                        $dataScore = isset($entryRow['second_test']) ? 
                                        $entryRow['second_test'] : $secondScore;

                                        ?>
                                        <tr>
                                            <td></td>
                                            <td class="text-sm"><?=$adminNo?></td>
                                            <td class="text-sm"> <?=$fullNames?></td>
                                            <td>
                                                <input type="number" class="short-input" 
                                                name="test[]" placeholder="Enter Score" id="inputTest-<?=$stdId?>"
                                                value="<?= $dataScore?>"
                                                required=""
                                                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 }
                                }?>    
                                </tbody>
                            </table>
                        </div>
                        <?php }; ?>
                    </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'; ?>


<!-- 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 },
      { 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>

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