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

<!-- Handle Add Slider -->
<style>
.insider{
    margin-top: -90px;
}
.card-header h5{
    font-size: 15px;
}
@media(max-width: 992px){
   .insider{
       margin-top: -50px;
   }
   .card{
     height: 500px;
   }
   .negative{
     height: 500px;
   } 
   .card-header h5{
     font-size: 12px;
   }
}
</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{

}

// Add Student test
if (isset($_POST['add-btn'])) {
    $detect = $_POST['detect'];
    $studId = $_POST['studId'];
    $test   = $_POST['test'];
    $surName = $_POST['surName'];
    $adminNo  = $_POST['adminNo'];
    $errors = [];
    for ($i=0; $i < count($studId) ; $i++) { 
        $stdTest = $test[$i];
        $stdName = $surName[$i];
        if ($stdTest > 40) {
            $errors[] = "Student {$stdName}: Test score is {$stdTest} (Max allowed is 40)";
        }
    }
    if (!empty($errors)) {
        $msgTitle   = "Test Score Input Error";
        $msgBody    = "Please review your entries.<br>
                    Each student's test score must not exceed 40.
                    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($studId); $i++) { 
            $stdId = $studId[$i]; // insert this as oldstdId
            $score = $test[$i];
            $totalStd = count($studId);
            $adNo = $adminNo[$i];

            // Insert the data in the student result db
            $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]);   
        }
        
        $msgTitle = "Test Grading Completed";
        $totalStudents = count($studId);
        $zeroScores = 0;

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

            if (empty($stdTest) || $stdTest == 0) {
                $zeroScores ++;
            }
        }
        $msgBody = "$totalStudents 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 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';
        }
    }
}

// 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 > 40) {
            $errors[] = "Student {$stdName}: Test score is {$stdTest} (Max allowed is 40)";
        }
    }
    if (!empty($errors)) {
        $msgTitle   = "Test Score Input Error";
        $msgBody    = "Please review your entries.<br>
                    Each student's test score must not exceed 40.
                    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">
            <div class="cat-page-header">
            </div>

            <div class="card mt-3">
                <form action="" method="POST">
                    <div class="card-header text-center" style="display: flex; align-items: center; justify-content: space-between;">
                        <h5>
                            <?=$class?> Test Score | Or
                            <a href="<?=$go_back_link?>" class="btn btn-sm text-white info">Go back <i class="fa fa-caret-left"></i></a>
                        </h5>
                        <!-- Check to know which button to display -->
                        <?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 invoice text-white" name="upd-btn">
                                Update Scores <i class="fa fa-edit"></i>
                            </button>
                        <?php } else {?>
                            <button class="btn btn-sm info text-white" name="add-btn">
                                Save Test Scores <i class="fa fa-save"></i>
                            </button>
                        <?php }
                        ?>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="example" class="display table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Admin. No.</th>
                                        <th>Surname</th>
                                        <th>Othernames</th>
                                        <th>Score</th>                                        
                                        <th>Total</th>
                                    </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'];?>
                                                <tr>
                                                    <td><?= $sn ?></td>
                                                    <td><?=$adminNo?></td>
                                                    <td>
                                                        <?= $stdSurname?>
                                                    </td>
                                                    <td>
                                                        <?=$stdOthername?>
                                                    </td>
                                                    <td>
                                                        <input type="number" class="short-input" 
                                                        name="test[]" placeholder="Enter Score" id="inputTest-<?=$stdId?>"
                                                        value="<?= $dataScore?>"
                                                         onkeyup="StdScore(<?=$stdId?>)">
                                                    </td>
                                                    <td>
                                                        <input type="text" class="short-input" 
                                                        name="" placeholder="<?= $dataScore?>/40" 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'];
                                            ?>
                                            <tr>
                                            
                                                <td><?= $sn ?></td>
                                                <td><?=$adminNo?></td>
                                                <td>
                                                    <?=$surName?>
                                                </td>
                                                <td>
                                                    <?=$otherNames?>
                                                </td>
                                                <td>
                                                    <input type="number"
                                                    required="" 
                                                    class="short-input" 
                                                    name="test[]" 
                                                    placeholder="Enter Score" 
                                                    id="inputTest-<?=$studId?>" 
                                                    onkeyup="StdScore(<?=$studId?>)">
                                                </td>
                                                <td>
                                                    <input type="text" class="short-input" name="" placeholder="0/40" 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>
                    
                </form>
                
            </div>
        </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 <= 40) {
            let addTotal = inputField.value + '/40';
            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">
<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>
    $(document).ready(function () {
        $('#example').DataTable();
        
    });
</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;
    }
</style>

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