<?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-to
    height: 100p: 10px;
}
/*.nav-links{%;
    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 h3{
    font-weight: bold;
    font-size: 16px;
}
.card-header h5{
    font-size: 14px;
}


.success_stutus{
    background: #E8FCEF; color: #4ECA74;
}
.error_status{
    background: #F8D7DA; color: #90151C;
}
.cat-page-header .warning-text{
    color: #90151C;
    font-weight: normal;
    /*font-style: italic;*/
}
.cat-page-header .success-text{
    color: #4ECA74;
    font-weight: normal;
    /*font-style: italic;*/
}
.cat-page-header h5,span{
    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: 768px) {
    .admin-text{
      font-size: 13px;
  }
  .small-bt{
    font-size: 12px;
    padding: 4px;
  }
  table.dataTable.dtr-inline.collapsed>tbody>tr>td:first-child:before {
    background-color: #007bff !important;
    color: white;
    border: none;
  }
  .text-sm{
    font-size: 12px;
    }
}
@media(max-width: 992px){
    .negative h5{
        font-size: 15px;
    }
    .negative a{
        font-size: 14px;
    }
    .negative a i{
        font-size: 14px;
    }
    .negative i{
        font-size: 30px;
    }
    .negative p{
        font-size: 13px;
    }
    .card-header h3{
        font-size: 15px;
    }
    .card-header h5{
        font-size: 13px;
    }
}
</style>
<?php
// Get your class student
$clastd = "SELECT class FROM class_teacher WHERE staffId = ?";
$thepdo = $pdo->prepare($clastd);
$thepdo->execute([$staffId]);
$filter = $thepdo->rowCount();
if ($filter == FALSE) {
    header('Location:index.php');
}else{
    $classRow = $thepdo->fetch(PDO::FETCH_ASSOC);
    $myClass = $classRow['class'];
}

$allstd = "SELECT * FROM student WHERE class = ? 
        AND term = ? AND session = ?";
$stmt = $pdo->prepare($allstd);
$stmt->execute([$myClass, $current_term, $current_session]);
while ($stdData = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $studentId = $stdData['studId'];
    $adminNo   = $stdData['adminNo'];

    $norms = "SELECT stdId, SUM(total) AS overall FROM results WHERE stdId = ?";
    $msa = $pdo->prepare($norms);
    $msa->execute([$adminNo]);
    while ($print = $msa->fetch(PDO::FETCH_ASSOC)) {
        $overall_score  = isset($print['overall'])? $print['overall']: 0;
        $overall_id     = isset($print['stdId'])? $print['stdId'] : null;
       
        if ($overall_id !== null) {
            // Check if exist
            $sql_validate = "SELECT * FROM performance WHERE stdId = ? 
            AND class = ? AND term = ? AND session = ? ";
            $query_validate = $pdo->prepare($sql_validate);
            $query_validate->execute([$adminNo, $myClass, $current_term, $current_session]);
            $count_val_row = $query_validate->rowCount();
            if ($count_val_row < 1) {
                // Insert new items
                $sql_insert_items = "INSERT INTO performance (stdId, class, term, session, total_score) VALUES(?,?,?,?,?)";
                $query_items = $pdo->prepare($sql_insert_items);
                $query_items->execute([$overall_id, $myClass, $current_term, 
                $current_session, $overall_score ]);
            }else{
                // update the items
                $sql_update_items = "UPDATE performance SET total_score = ? WHERE stdId = ?
                AND class = ? AND term = ? AND session = ?";
                $query_items_upd = $pdo->prepare($sql_update_items);
                $query_items_upd->execute([$overall_score, $overall_id, 
                                $myClass, $current_term, 
                                $current_session ]);
            }
        }
        
    }
}


// Get the notification
$sqlResult = "SELECT stdId FROM results 
        WHERE class = ? AND term = ? AND session = ?";
$stmtRst = $pdo->prepare($sqlResult);
$stmtRst->execute([$myClass, $current_term, $current_session]);
$valid = $stmtRst->rowCount();
if ($valid < 1) {
    $table = "display:none";
    $negat = "display:flex";
}else{
    $table = "display:block";
    $negat = "display:none";
}


// Get the status for result approval
$approRest = "SELECT status FROM result_approval 
            WHERE class = ? AND term = ? AND session = ?";
$queryRest = $pdo->prepare($approRest);
$queryRest->execute([$myClass, $current_term, $current_session]);
$countProval = $queryRest->rowCount();
$rowproval = $queryRest->fetch(PDO::FETCH_ASSOC);
$provalStatus = isset($rowproval['status'])? $rowproval['status']:'';

if ($countProval < 1) {
    $ca_color = 'warning-text';
    $sta_text = 'Not Submitted';
}else
if ($provalStatus =='Pending') {
    $ca_color = 'warning-text';
    $sta_text = 'Pending';
}else if ($provalStatus == 'Rejected') {
    $ca_color = 'warning-text';
    $sta_text = 'Rejected';
}
else{
    $ca_color = 'success-text';
    $sta_text = 'Approved';
}

?>

<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">
                <h5>Status: <span class="<?=$ca_color?>"><?=$sta_text?></span>
                </h5>
                <form action="" method="POST">
                    <?php
                    if ($valid < 1) {?>
                        <button name="confirm-btn" 
                            disabled="" 
                            class="btn btn-sm btn-primary">
                            <i class="fa fa-paper-plane"></i> Submit Now
                        </button><?php
                    }
                    else if ($countProval < 1) {?>
                        <button name="confirm-btn" class="btn btn-sm info text-white">
                            <i class="fa fa-paper-plane"></i> Submit Now
                        </button>
                    <?php }else if ($provalStatus == 'Pending') {?>
                        <button name="" 
                        disabled="" 
                        class="btn btn-sm warning text-warning">
                        Result Submitted 
                        </button> 
                    <?php }else if ($provalStatus == 'Rejected') {?>
                        <button name="re_submit_btn" class="btn btn-sm primary text-white">
                        Re-Submit
                        </button>
                    <?php }
                    else{?>
                        <button name="" 
                        disabled="" 
                        class="btn btn-sm success text-success">
                        Result Approved 
                        <i class="fa fa-check-circle"></i>
                        </button> 
                    <?php }

                    ?>
                </form>
                    
            </div>
            <div class="card mt-3">
                <div class="card-header text-center">
                    <h3><?php SchoolName()?></h3>
                    <h5 class="text-success"><?= $myClass?> | 
                        <?= $current_term?>Term <?= $current_session?> Academic Session
                    </h5>
                </div>
                <div class="card-body">
                    <!-- If Empty -->
                    <div class="negative" style="<?=$negat?>">
                        <i class="fa fa-hourglass-half"></i>
                        <h5>No Results Uploaded.</h5>
                        <p class="text-muted text-center">
                            This means the subject teacher has not graded this class yet, or the results are still being uploaded. <br>
                            Kindly check back later.
                          </p>
                    </div>
                    <form action="" method="POST" id="mainForm" style="<?=$table?>">        
                        <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">Names</th>
                                        <th data-priority="2" class="text-sm">Admin No</th>
                                        <th data-priority="3" class="text-sm">Image</th>
                                        <th data-priority="4" class="text-sm">Subject</th>
                                        <th data-priority="5" class="text-sm">Total Score</th>
                                        <th data-priority="1" class="text-sm">Comments</th>
                                        <!-- <th>Total</th> -->
                                        <th data-priority="1" class="text-sm">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <!-- Display all student in this class -->
                                <?php
                                // Print all Results
                                $sn = 0;
                                $sql = "SELECT * FROM performance WHERE class = ? 
                                        AND term = ? AND session = ? order by total_score desc";
                                $query = $pdo->prepare($sql);
                                $query->execute([$myClass, $current_term, $current_session]);

                                while ($perfData = $query->fetch(PDO::FETCH_ASSOC)) {
                                    $student_perf_id = $perfData['stdId'];
                                
                                // Get student Info according to id
                                $query_student = "SELECT * FROM student WHERE adminNo = ? 
                                AND class = ? AND term = ? AND session = ? ";
                                $query_pdo = $pdo->prepare($query_student);
                                $query_pdo->execute([$student_perf_id, $myClass, $current_term, $current_session]);
                                
                                while ($stdRow = $query_pdo->fetch(PDO::FETCH_ASSOC)) {
                                    $stdId      = $stdRow['studId'];
                                    $adminNo    = $stdRow['adminNo'];
                                    $surName    = $stdRow['surname'];
                                    $otherNames  = $stdRow['otherNames'];
                                    $gender     = $stdRow['gender'];
                                    $sn = $sn + 1;
                                    $encryptId = encryptData($adminNo);

                                    $shtn = explode(' ', $otherNames);
                                    $name1 = $shtn[0];
                                    $name2 = isset($shtn[1])? $shtn[1]: '';
                                    $fullNames = $surName.' '.$name1;

                                // Get all their total score
                                    $getScore = "SELECT SUM(total) AS total_score, count(subject) 
                                    AS total_sub  FROM results 
                                    WHERE stdId = ? AND class = ? AND term = ? AND session = ? ";
                                    $queryScore = $pdo->prepare($getScore);
                                    $queryScore->execute([$adminNo, $myClass, $current_term, 
                                        $current_session]);

                                    while ($scoreRow = $queryScore->FETCH(PDO::FETCH_ASSOC)) {
                                       $total_score = $scoreRow['total_score'];
                                       $total_subj   = $scoreRow['total_sub'];

                                    // Get number of subject for this class
                                    $getSubject = "SELECT subName FROM subject WHERE inClass = ?";
                                    $subQuery = $pdo->prepare($getSubject);
                                    $subQuery->execute([$myClass]);
                                    $countSub = $subQuery->rowCount();

                                    // Get student image
                                    $stdImg = "SELECT photo_path, dob 
                                            FROM student_image WHERE adminNo = ?";
                                    $imgStmt = $pdo->prepare($stdImg);
                                    $imgStmt->execute([$adminNo]);
                                    while ($imgRow = $imgStmt->fetch(PDO::FETCH_ASSOC)) {
                                        $theImg = $imgRow['photo_path'];
                                        $dob    = $imgRow['dob'];

                                // Get each student comment status
                                    $comstatus = "SELECT * FROM class_teacher_inputs 
                                    WHERE student_id = ? AND term = ? AND session = ? ";

                                    $stmtComent = $pdo->prepare($comstatus);
                                    $stmtComent->execute([$adminNo, $current_term, 
                                                $current_session]);
                                    $comdes_status = $stmtComent->rowCount();
                                    if ($comdes_status > 0) {
                                      $respond_to = 'Filled';
                                    }else{
                                      $respond_to = 'No Record';
                                    }
                                ?>
                                    <tr>
                                        <td></td>
                                        <td class="text-sm"><?=$fullNames?></td>
                                        <td class="text-sm"><?=$adminNo?></td>
                                        <td>
                                            <img alt="Student Image" src="../../student/images/avatar/<?=$theImg?>" id = "image-<?=$stdId?>" width="60px" height="40px" >
                                        </td>
                                        <td><?=$total_subj.'/'.$countSub?></td>
                                        <td><?=$total_score?></td>
                                        <td class="text-sm"><?=$respond_to?></td>
                                        <td class="text-sm">
                                            <a href="compile.php?stdVal=<?= $adminNo?>" class="btn btn-sm btn-primary small-bt">
                                                Compile <i class="fa fa-pen"></i>
                                            </a>
                                        </td>
                                    </tr>
                                   <?php } } } } ?> 
                                </tbody>
                            </table>
                        </div>
                        
                    </form>
                </div>
            </div>
        </div>
   
    </div>
</div>
<?php
// Confirm Result before sending
if (isset($_POST['confirm-btn'])) {
  
  $msgTitle = "<b>Confirm Submission</b>";
  $msgBody = "<center>
    Are you sure you want to submit the results 
    to the Vice Principal for final approval? 
    <br>This means you have cross-checked the scores, performance, comments, and attendance carefully.
  </center>";
  $msgCloseBtn = "No, Cancel";
  $msgActionBtn = "Yes, Submit";
  include'includes/confirm-alert.php'; 
}

// Send Results to VP for approval
if (isset($_POST['send-result-btn'])) {
  $created = date('Y-m-d');
  $fullName = $title.' '.$names;
  $sendResult = "INSERT INTO result_approval (class, term, session, modified, submitted_by)
                VALUES(?,?,?,?,?)";
  $sendStmt = $pdo->prepare($sendResult);
  $sendStmt->execute([$myClass, $current_term, $current_session, $created, $fullName]);

  $msgTitle = "<b>Results Submitted</b>";
  $msgBody = "<center>
    The Vice Principal/Principal will review the results and add their comments for each student. 
    <br>You will be notified once the results are approved, rejected, or need adjustment.
  </center>";
  $msgCloseBtn = "Okay, Got it.";
  
  include'includes/checkmark-alert.php';

}

// Re-submit the result again for approval after rejection for re-adjustment
if (isset($_POST['re_submit_btn'])) {
    $set_status = 'Pending';
    $created = date('Y-m-d');
    $current_status = 'Rejected';

    $updreslt = "UPDATE result_approval SET status = ?, modified = ?
    WHERE class = ? AND term = ? AND session = ? AND status = ?";
    $rejectPdo = $pdo->prepare($updreslt);
    $rejectPdo->execute([$set_status, $created, 
                $myClass, $current_term, $current_session, 
                $current_status]);

    $msgTitle = "<b>Results Re-submitted</b>";
    $msgBody = "<center>
      The Vice Principal/Principal will re-check the updated results. 
      <br>You will be notified once a decision is made.
    </center>";
    $msgCloseBtn = "Okay, Got it.";
    
    include'includes/checkmark-alert.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>
$(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: 1, responsivePriority: 1 }, // Admin No. - always visible
      { targets: 6, responsivePriority: 1 }, // Score - always visible
      { targets: 7, responsivePriority: 1 }, // Total - always visible
      { targets: [2, 3, 4, 5], responsivePriority: 10 }, // hide Surname & Othernames first on mobile
      { orderable: false, targets: [1, 7] } // no sorting on inputs
    ],
    paging: true,
    searching: true,
    info: true,
    language: {
      emptyTable: "No student records found."
    }
  });
});
</script>
<script type="">
    responsive: true,
    dom: '<"top"lf>rt<"bottom"ip><"clear">',
</script>



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

