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

.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){
    .negative h5{
        font-size: 15px;
    }
    .negative a{
        font-size: 14px;
    }
    .negative a i{
        font-size: 14px;
    }
    .text-sm{
        font-size: 12px;
    }

}
</style>
<?php

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

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

?>

<div id="notification-containers" class="notification-containers"></div>
<div class="insider">
    <div class="container">
        <div class="cat-pag">
            <div class="cat-page-header d-flex justify-content-between align-items-center">
                
                <div>
                    <a href="test_score.php?class=<?=$class.'*'.$subject?>" class="btn btn-sm info text-white"><i class="fa fa-plus-circle"></i> Add First CA </a>

                    <a href="second_test.php?class=<?=$class.'*'.$subject?>" class="btn btn-sm primary text-white"><i class="fa fa-plus-square"></i> Add Second CA </a>

                    <a href="exam_score.php?class=<?=$class.'*'.$subject?>" class="btn btn-sm invoice text-white"><i class="fa fa-edit"></i> Add Exam Score </a>
                </div>
            </div>

            <div class="card mt-3">
                <div class="card-header text-left">
                    <h5 style="font-size: 15px"><?=$class?> Students score list for <?=$subject?></h5>
                </div>
                <div class="card-body">
                    <form action="" method="POST" id="mainForm">
                        
                        <?php
                        $rels = "SELECT stdId 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 == FALSE) {?>
                            <div class="negative">
                                <i class="fa fa-folder-open"></i>
                                <h5>
                                    No Grades Found for <b><?=$subject?></b> - 
                                    <b><?=$class?></b> <br>
                                    <small>(<?=$current_session?> Session, 
                                        <?=$current_term?> Term)
                                    </small>
                                </h5>
                                <p style="font-size:14px; color:#555;">
                                    There’s no grading record yet for this class and subject. <br>
                                    Please begin by adding the <b>Test Scores</b>.
                                </p>
                                    
                                <a href="test_score.php?class=<?=$class.'*'.$subject?>" 
                                    class="warning">
                                    Add Test Score Now <i class="fa fa-plus-circle"></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="1" class="text-sm">ID</th>
                                        <th data-priority="1" class="text-sm">Names</th>
                                        <th data-priority="2" class="text-sm">Gender</th>
                                        <th data-priority="3" class="text-sm">CA1 (20)</th>
                                        <th data-priority="4" class="text-sm">CA2 (20)</th>
                                        <th data-priority="5" class="text-sm">Exam Score (60)</th>
                                        <th data-priority="1" class="text-sm">Total</th>
                                        <th data-priority="1">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sn = 0;
                                    $getsco = "SELECT * FROM results WHERE
                                                subject = ? AND class = ? 
                                                AND term = ? AND session = ?  ";
                                    $scorePdo = $pdo->prepare($getsco);
                                    $scorePdo->execute([$subject, 
                                                $class,
                                                $current_term,
                                                $current_session ]);
                                    while ($scoreRow = $scorePdo->fetch(PDO::FETCH_ASSOC)) {
                                        $adminNo = $scoreRow['stdId'];
                                        $resultId = $scoreRow['resultId'];
                                        $dataTest = $scoreRow['test_score'];
                                        $dataExam = $scoreRow['exam_score'];
                                        $dataTotal = $scoreRow['total'];
                                        $dataGrade = $scoreRow['grade'];
                                        $secondTest = $scoreRow['second_test'];

                                    // Using the adminNo to track get the student
                                        $fetch = "SELECT * FROM student WHERE adminNo = ? AND class = ?";
                                        $stmt = $pdo->prepare($fetch);
                                        $stmt->execute([$adminNo, $class]);
                                        $row = $stmt->fetch(PDO::FETCH_ASSOC);
                                            $stdId = $row['studId'];
                                            $adminNo = $row['adminNo'];
                                            $surName = $row['surname'];
                                            $otherNames = $row['otherNames'];
                                            $gender = $row['gender'];
                                            $sn = $sn +1;
                                            $names = $surName.' '.$otherNames;
                                    ?>
                                    <tr>
                                        <td></td> <!-- Auto-filled by DataTables for toggle icon -->
                                        <td class="text-sm"><?= $sn ?></td>
                                        <td class="text-sm"><?=$names?></td>
                                        <td class="text-sm"><?=$gender?></td>
                                        <td class="text-sm"><?= $dataTest?></td>
                                        <td class="text-sm"><?= $secondTest?></td>
                                        <td class="text-sm"><?= $dataExam?></span></td>
                                        <td class="text-sm"><?= $dataTotal?></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-primary" onclick="openModal('modal-<?= $stdId ?>')">
                                                <i class="fa fa-edit"></i> Edit
                                            </button>
                                        </td>
                                            <!-- Edit Modal -->
                                            <?php EditScores()?>
                                        <!-- End while loop -->
                                    <?php }?>
                                </tbody>
                            </table>
                        </div>
                        <?php } ?>
                    </form>
                </div>
            </div>
        </div>
   
    </div>
</div>

<?php
if (isset($_POST['upd-std'])) {
    $resultId   = $_POST['resultId'];
    $test       = $_POST['test'];
    $test2      = $_POST['test2'];
    $exam       = $_POST['exam'];
    // $total      = $_POST['total'];
    // $remarks    = $_POST['remarks'];

    $total = $test + $test2 + $exam;

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


    if ($total > 100) {
        $_SESSION['message'] = "Total score is greater than 100";
        $_SESSION['type'] = 'error';
    }else{
        // update the result table for this student
        $upd = "UPDATE results SET test_score = ?, second_test = ?, 
                exam_score = ?, 
                total = ?, grade = ? WHERE resultId = ?";
        $updPdo = $pdo->prepare($upd);
        $updPdo->execute([$test, $test2, $exam, $total, $remarks, $resultId]);
        $_SESSION['message'] = "Student Score Updated";
        $_SESSION['type'] = 'success';?>

        <script type="text/javascript">
          setTimeout("location.href='javascript:history.back()';", 2000);
        </script>
        <?php 
    }
}

// Delete Student for this subject
if (isset($_POST['del-stdScore'])) {
    $resultId   = $_POST['resultId'];
    // delete this student score
    $delSc = "DELETE FROM results WHERE resultId = ?";
    $delPdo = $pdo->prepare($delSc);
    $delPdo->execute([$resultId]);

    $_SESSION['message'] = 'Student Score Deleted Successfully';
    $_SESSION['type'] = 'success';?>
    <script type="text/javascript">
      setTimeout("location.href='javascript:history.back()';", 2000);
    </script>
    <?php
}
?>

<?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>
    $('#example').DataTable({
      responsive: {
        details: {
          type: 'column',
          target: 0 // (+) icon for toggling hidden info
        }
      },

      columnDefs: [
        { className: 'control', orderable: false, targets: 0 }, // (+) toggle
        { orderable: false, targets: [1, -1] }, // disable sorting on checkbox & action
        { targets: 1, responsivePriority: 1 }, // Checkbox always visible
        { targets: 2, responsivePriority: 1 }, // Names always visible
        { targets: 7, responsivePriority: 1 }, // Roles always visible
        { targets: 8, responsivePriority: 4 }, // S/N less important
        
        { targets: -1, responsivePriority: 2 }, // Action visible after roles
      ],
      paging: true,
      searching: true,
      info: true
    });

    language: {
      emptyTable: "No student records found. Click 'Add New' to register student."
    }

</script>
<script type="">
    responsive: true,
    dom: '<"top"lf>rt<"bottom"ip><"clear">',
</script>

<script>
    $(document).ready(function () {
        $('#example').DataTable();
        $('#SelectAllBoxes').click(function () {
            $('.checkBoxes').prop('checked', this.checked);
        });
    });

    function openModal(id) {
        document.getElementById(id).style.display = "block";
    }

    function closeModal(id) {
        document.getElementById(id).style.display = "none";
    }

    function handleDelete() {
        const checked = document.querySelectorAll("input[name='checkBoxArray[]']:checked");
        if (checked.length === 0) {
            alert("No products selected!");
            return;
        }
        openModal('modal-delete');
    }
   
</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;
}
</style>

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

