<?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>
    td span{
        padding: 10px; border-radius: 6px;
        font-size: 13px;
    }
    .success_stutus{
        background: #E8FCEF; color: #4ECA74;
    }
    .error_status{
        background: #F8D7DA; color: #90151C;
    }
    .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{
            flex-direction: column; 
        }
    }
</style>
<?php

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

    $class      = $unvel[0];
    $subject    = $unvel[1]; 
}

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


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

            $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]);
            
        }
        
        $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.";
            $msgCloseBtn = "Okay, got it";
            include'includes/success-alert.php';
        }else{
            $msgBody .= "<br><br>
                        <b>Note:</b> Any adjustment can be made when the current session is still active.";
            $msgCloseBtn = "Okay, Got it.";
            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">
            <div class="cat-page-header">
                <h5><?= $current_session?> A.S. | <?= $subject ?></h5>
                <div>
                    <h6>Current Term: <span class="success_stutus"><?= $current_term?></span></h6>
                </div>
                <!-- <h5>All <?=$class?> Students</h5> -->
                <!-- <div>
                    <a href="add-product.php" class="btn info text-white">Add Test Scores <i class="fa fa-plus-circle"></i></a>

                    <a href="add-product.php" class="btn invoice text-white">Add Exam Score <i class="fa fa-pen"></i></a>
                </div> -->
            </div>

            <div class="card mt-3">
                <form action="" method="POST">
                    <div class="card-header text-center">
                        <div class="card-header text-center" 
                        style="display: flex; align-items: center; justify-content: space-between;">
                            <h5><?=$class?> Exam Score <i class="fa fa-pen"></i></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 invoice text-white" name="upd-btn">
                                    Update Details <i class="fa fa-edit"></i>
                                </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-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>ID</th>
                                            <th>Surname</th>
                                            <th>Othernames</th>
                                            <th>Test Score</th>
                                            <th>Exam Score</th>                                        
                                            <th>Total</th>
                                            <th>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'];
                                            $stdId      = $row['stdId'];
                                            $testScore  = $row['test_score'];
                                            $examScore  = $row['exam_score'];
                                            $totalScore = $row['total'];
                                            $grade      = $row['grade'];
                                            if ($examScore == 'pending') {
                                                $examGrade = 0;
                                            }else{
                                                $examGrade = $examScore;
                                            }

                                            // collectt normal students info
                                            $stdInfo = "SELECT * FROM student WHERE studId = ?";
                                            $stdPdo = $pdo->prepare($stdInfo);
                                            $stdPdo->execute([$stdId]);
                                            while ($stdRow = $stdPdo->fetch(PDO::FETCH_ASSOC)) {
                                                $surName    = $stdRow['surname'];
                                                $otherNames = $stdRow['otherNames'];
                                                $sn = $sn + 1;
                                            ?>
                                            <tr>
                                                <td><?= $sn ?></td>
                                                <td>
                                                    <?=$surName?>
                                                </td>
                                                <td>
                                                    <?=$otherNames?>
                                                </td>
                                                <td >
                                                    <input type="text" class="short-input" name="" placeholder="Enter Score" disabled="" 
                                                    id="testScore-<?=$stdId?>" 
                                                    value="<?= $testScore?>">
                                                </td>

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

                                                <td>
                                                    <input type="number" class="short-input" 
                                                    disabled="" 
                                                    id="totalScore-<?= $stdId?>" 
                                                    value="<?= $totalScore?>">
                                                </td>

                                                <td>
                                                    <input type="text" class="form-control" 
                                                    disabled="" id="remarks-<?= $stdId?>" 
                                                    value="<?= $grade?>">
                                                </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="<?= $grade?>">
                                                <!-- hidden totalMark -->
                                                <input type="hidden" name="totalMark[]" 
                                                id="hiddenTotal-<?= $stdId?>" 
                                                value="<?= $totalScore?>">
                                                
                                            </tr>
                                        <!-- End while loop -->
                                        <?php } }?>
                                    </tbody>
                                </table>
                            </div>
                        <?php } ?>  
                    </div>
                </form>
            </div>
            
        </div>
   
    </div>
</div>

<script>
    function examScore(stdId){
        let testScore = document.getElementById('testScore-' + 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 examScore = parseInt(exam.value);

        let sum = test + 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'; ?>

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

