<?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>
.card{
  height: 600px
}
@media(max-width: 992px){
.insider{
  margin-top: -50px;
  padding-left: 10px;
  padding-right: 10px;
  }        
}
.multicard {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 25px;
}

.multicard h2 {
  margin-top: 0;
  font-size: 20px;
  border-bottom: 2px solid #eee;
  padding-bottom: 8px;
}

.overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 15px;
}

.overview-item {
  background: #f9fafc;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.overview-item strong {
  display: block;
  margin-bottom: 4px;
  color: #0073e6;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
  font-size: 14px;
}

table thead {
  background: #0073e6;
  color: #fff;
}

table th, table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}

table tbody tr:nth-child(even) {
  background: #f9f9f9;
}

.vp-action {
  margin-top: 20px;
}

textarea {
  width: 100%;
  min-height: 80px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-family: inherit;
  font-size: 14px;
  resize: vertical;
}


.btn-approve {
  background: #28a745;
  color: #fff;
}

.btn-reject {
  background: #dc3545;
  color: #fff;
}

.btn:hover {
  opacity: 0.9;
}

</style>
<?php
if (isset($_GET['rsltVal'])) {
    $package = $_GET['rsltVal'];
    $unpack = explode('*', $package);

    $class  = $unpack[0];
    $term   = $unpack[1];
    $session = $unpack[2];

// Get the total student who participated in the exam
    $getstdNum = "SELECT DISTINCT stdId FROM results 
                WHERE class = ? AND term = ? AND session = ? ";
    $queryTotalStd = $pdo->prepare($getstdNum);
    $queryTotalStd->execute([$class, $term, $session]);
    $totalStdRow = $queryTotalStd->rowCount();

// Get class teacher and the day the result was submitted
    $getClassAuthor = "SELECT * FROM result_approval 
            WHERE class = ? AND term = ? AND session = ? ";
    $queryClassAuthor = $pdo->prepare($getClassAuthor);
    $queryClassAuthor->execute([$class, $term, $session]);
    $approvalRow = $queryClassAuthor->fetch(PDO::FETCH_ASSOC);
    $author         = $approvalRow['submitted_by'];
    $modified       = $approvalRow['modified'];
    $status         = $approvalRow['status'];  
}

// Get the school opening time for this session
$getInfo = "SELECT times_opened FROM school_info WHERE term = ? AND session = ?";
$infoPdo = $pdo->prepare($getInfo);
$infoPdo->execute([$term, $session]);
$openedInfo = $infoPdo->FETCH(PDO::FETCH_ASSOC);
$times_opened = $openedInfo['times_opened'];

?>

<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">
            <form action="" method="POST">
                <button 
                name="confirm-approve-btn" 
                class="btn btn-sm success text-white">
                APPROVE RESULT 
                <i class="fa fa-check-circle"></i>
                </button>

                <button name="confirm-reject-btn" 
                class="btn btn-sm danger text-white">
                REJECT RESULT 
                <i class="fa fa-window-close"></i>
                </button>
            </form>
            <a href="pending_results.php" class="btn btn-sm primary text-white"> Go Back <i class="fa fa-caret-right"></i> </a>
        </div>
      <div class="card mt-3">

          <!-- Class Overview -->
          <div class="multicard">
            <h2>Class Overview</h2>
            <div class="overview">
              <div class="overview-item">
                <strong>Class</strong> <?=$class?>
              </div>
              <div class="overview-item">
                <strong>Class Teacher</strong> <?=$author?>
              </div>
              <div class="overview-item">
                <strong>Total Students</strong> <?=$totalStdRow?>
              </div>
              <div class="overview-item">
                <strong>Submitted On</strong> <?=$modified?>
              </div>
              <div class="overview-item">
                <strong>Status</strong> <?=$status?> Approval
              </div>
            </div>
          </div>

          <!-- Student Results -->
          <div class="multicard">
            <h2>Student Results</h2>
            
            <table id="example" class="display table table-bordered">
                <thead >
                    <tr>
                      <th>#</th>
                      <th>Student</th>
                      <th>Subjects Completed</th>
                      <th>Total Score</th>
                      <th>Position</th>
                      
                      <th>Attendance</th>
                      <th>Status</th>
                      <!-- <th>Teacher's Comment</th> -->
                      <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Get all student result details -->
                    <?php
                    $snr = 0;
                    $sql = "SELECT * FROM performance WHERE class = ? 
                            AND term = ? AND session = ? order by total_score desc";
                    $query = $pdo->prepare($sql);
                    $query->execute([$class, $current_term, $current_session]);

                    while ($perfData = $query->fetch(PDO::FETCH_ASSOC)) {
                        $stdId    = $perfData['stdId'];
                        
                    // Get 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([$stdId, $class, $term, $session]);
                        while ($scoreRow = $queryScore->FETCH(PDO::FETCH_ASSOC)) {
                           $total_score = $scoreRow['total_score'];
                           $total_subj   = $scoreRow['total_sub'];
                    // get student Name 
                        $getStdName = "SELECT * FROM student WHERE adminNo = ?";
                        $stdNameQuery = $pdo->prepare($getStdName);
                        $stdNameQuery->execute([$stdId]);
                        while ($nameRow = $stdNameQuery->FETCH(PDO::FETCH_ASSOC)) {
                            $surname = $nameRow['surname'];
                            $othernames = $nameRow['otherNames'];

                    // Get their comment and attendance
                        $getAttend = "SELECT * FROM class_teacher_inputs WHERE student_id = ?
                            AND term = ? AND session = ?";
                        $pdoAttend = $pdo->prepare($getAttend);
                        $pdoAttend->execute([$stdId, $term, $session]);
                        while ($attendRow = $pdoAttend->FETCH(PDO::FETCH_ASSOC)) {
                            $comment = $attendRow['comment'];
                            $atten_no  = $attendRow['attendance'];
                            $checkStatus = $attendRow['check_status'];
                            $position   = $attendRow['position'];

                    // Get number of subject for this class
                    $getSubject = "SELECT subName FROM subject WHERE inClass = ?";
                    $subQuery = $pdo->prepare($getSubject);
                    $subQuery->execute([$class]);
                    $countSub = $subQuery->rowCount();
                    // Serial Number
                    $snr = $snr + 1;
                    // Link var
                    $encryptId = encryptData($stdId);
                    $viewLinks = $class.'*'.$term.'*'.$session.'*'.$encryptId;
                    ?>
                    <tr>
                        <td><?=$snr?></td>
                        <td><?=$surname.' '.$othernames?></td>
                        <td><?=$total_subj.'/'.$countSub?></td>
                        <td><?=$total_score?></td>
                        <td><?=$position?></td>
                        <td><?=$atten_no.'/'.$times_opened?></td>
                        <td><?=$checkStatus?></td>
                        
                        <td>
                            <a href="view_results.php?viewVal=<?=$viewLinks?>" 
                                class="btn btn-sm info text-white">Full Result
                            </a>
                        </td>
                    </tr>
                    <?php } } } }?>
                    

                </tbody>
            </table>
            
          </div>

        </div>

      </div>
    </div>
  </div>
</div>
     

<?php

// Confirm Approval
if (isset($_POST['confirm-approve-btn'])) {
    
    $msgTitle = "<b>Confirm Approval</b>";
    $msgBody = "<center>
                  Are you sure you want to approve the results for 
                  <b>$class, $term Term, $session</b>? 
                  <br>This means all student results have been thoroughly reviewed, 
                  and once approved, they will be visible to students.
                </center>";
    $msgCloseBtn = "No, Cancel";
    $msgActionBtn = "Yes, Approve";

    include'includes/confirm-approve.php'; 
}
// Confirm Rejection
if (isset($_POST['confirm-reject-btn'])) {

    $msgTitle = "<b>Confirm Rejection</b>";
    $msgBody = "<center>
                  Are you sure you want to reject the results for 
                  <b>$class, $term Term, $session</b>? 
                  <br>The class teacher will be notified to make corrections and resubmit.
                </center>";
    $msgCloseBtn = "No, Cancel";
    $msgActionBtn = "Yes, Reject";

    include'includes/confirm-reject.php'; 
}

// When the approve button is clicked show this
if (isset($_POST['approve-btn'])) {

    $set_status_to = 'Approved';
    $modified_date = date('Y-m-d');
    $apprvrst = "UPDATE result_approval SET status = ?, modified = ? 
                WHERE class = ? AND term = ? AND session = ?";
    $apprvPdo = $pdo->prepare($apprvrst);
    $apprvPdo->execute([$set_status_to, $modified_date, $class, $term, $session]);

// Then show this message
    $msgTitle = "<b>Result Released!</b>";
    $msgBody = "<center>
                  Results for <b>$class, $term Term, $session</b> are now available. <br>
                  Students can view and print their results. <br>
                  <small>Note: Adjustments can still be made if needed.</small>
                </center>";
    $msgCloseBtn = "Okay, Got it.";
    include'includes/checkmark-alert.php';
}

// When the reject button is pressed show this warning:
if (isset($_POST['reject-btn'])) {

    $set_status_to = 'Rejected';
    $modified_date = date('Y-m-d');
    $apprvrst = "UPDATE result_approval SET status = ?, modified = ? 
                WHERE class = ? AND term = ? AND session = ?";
    $apprvPdo = $pdo->prepare($apprvrst);
    $apprvPdo->execute([$set_status_to, $modified_date, $class, $term, $session]);

    // Then show this message
    $msgTitle = "<b>Result Rejected</b>";
    $msgBody = "<center>
                  Results for <b>$class, $term Term, $session</b> have been rejected. <br>
                  The class teacher will be notified to make adjustments and re-submit. <br>
                  <small>Note: You may contact the teacher directly if necessary.</small>
                </center>";
    $msgCloseBtn = "Okay, Got it.";
    include'includes/error_alert.php';
}

if (isset($_POST['escape-btn'])) {
    header('Location:pending_results.php');
}

?>


<?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();
        $('#SelectAllBoxes').click(function () {
            $('.checkBoxes').prop('checked', this.checked);
        });
    });

    
</script>

<script>
  function openModal() {
    document.getElementById("reviewModal").style.display = "flex";
  }
  function closeModal() {
    document.getElementById("reviewModal").style.display = "none";
  }
</script>

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

