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

@media(max-width: 992px){
  .negative h5{
    font-size: 15px;
  }
  .negative a{
    font-size: 14px;
  }
  .negative a i{
    font-size: 14px;
  }
}
.sug-area {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 5px;
}

.sug {
  background: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  padding: 6px 12px;
  font-size: 13px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  transition: background 0.3s;
}
.sug:hover {
  background: #0056b3;
}

.suggested-bg {
  position: absolute;
  right: 30px;
  bottom: 50px;
  width: 260px;
  height: 0;
  background: #f8fafc;
  box-shadow: 0 2px 6px rgba(0,0,0,0.25);
  overflow: hidden;
  border-radius: 6px;
  transition: height 0.4s ease;
  z-index: 1000;
}

.suggested-bg.active {
  height: 250px;
  padding: 6px;
  overflow-y: auto;
}

.sugMsgBg {
  width: 100%;
  padding: 8px 10px;
  background: #fff;
  border-radius: 6px;
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  transition: all 0.3s;
}
.sugMsgBg:hover {
  background: #e8f0fe;
  transform: scale(1.02);
}
.sugMsgBg i {
  color: #007bff;
  margin-top: 3px;
}
.sugMsgBg span {
  font-size: 13px;
  font-family: 'Segoe UI', sans-serif;
  color: #444;
  line-height: 1.4;
}

/* ====== TEXTAREA STYLING ====== */
.comment-box {
  position: relative;
  width: 100%;
  margin-bottom: 10px;
}
.comment-box textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  font-size: 14px;
  font-family: 'Segoe UI', sans-serif;
}

</style>

<?php
if (isset($_GET['stdVal'])) {
  $stdVal = $_GET['stdVal'];
  // $decryptId = decryptData($stdVal);
}else{
  header('Location:my-students.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'];
}
$myClass; // class name
$current_term; // this term
$current_session; // this session
$studentId = $stdVal;

// Get student information
$stdInfo = "SELECT * FROM student WHERE adminNo = ?";
$infoStmt = $pdo->prepare($stdInfo);
$infoStmt->execute([$studentId]);
$infoRow = $infoStmt->fetch(PDO::FETCH_ASSOC);
$surname = $infoRow['surname'];
$othernames = $infoRow['otherNames'];
$studId = $infoRow['studId'];

// Get comments details for this student
$comdes = "SELECT * FROM class_teacher_inputs WHERE student_id = ? 
          AND term = ? AND session = ? ";
$stmtComent = $pdo->prepare($comdes);
$stmtComent->execute([$studentId, $current_term, $current_session]);
$comdes_status = $stmtComent->rowCount();
if ($comdes_status < 1) {
  $res = 'disabled=""';
}else{
  $res = '';
}

// Get the results details
$resultNow = "SELECT * FROM results WHERE stdId = ? 
            AND class = ? AND term = ? AND session = ? ";
$stmtResult = $pdo->prepare($resultNow);
$stmtResult->execute([$studentId, $myClass, $current_term, $current_session]); 
$currentResult = $stmtResult->rowCount();

// Get student image
$getImg = "SELECT photo_path FROM student_image WHERE adminNo = ?";
$imgPdo = $pdo->prepare($getImg);
$imgPdo->execute([$studentId]);
$imgRow = $imgPdo->FETCH(PDO::FETCH_ASSOC);
$theImg = $imgRow['photo_path'];

// 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([$current_term, $current_session]);
$openedInfo = $infoPdo->FETCH(PDO::FETCH_ASSOC);
$times_opened = $openedInfo['times_opened'];
$check_if_exist = $infoPdo->rowCount();

?>
<?php
function ordinalSuffix($num) {
  if (!in_array(($num % 100), [11, 12, 13])) {
    switch ($num % 10) {
      case 1:  return $num . "<sup>st</sup>";
      case 2:  return $num . "<sup>nd</sup>";
      case 3:  return $num . "<sup>rd</sup>";
    }
  }
  return $num . "<sup>th</sup>";
}


// 1) Get totals per student (sorted DESC by total)
$sql = "SELECT oldstdId, SUM(total) AS total_score
        FROM results
        WHERE class = :class AND term = :term AND session = :session
        GROUP BY stdId
        ORDER BY total_score DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute([':class'=>$myClass, ':term'=>$current_term, ':session'=>$current_session]);
$totals = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 2) Assign positions
$positions = [];
$prev = null;
$i = 0;           // 1-based index
$rankComp = 0;    // competition rank

foreach ($totals as $row) {
  $i++;
  $id    = (int)$row['oldstdId'];
  $score = (int)$row['total_score'];

  if ($score !== $prev) {      
    $rankComp  = $i;   // assign new rank only when score changes
  }

  $positions[$id] = [
    'position'   => $rankComp,
    'score' => $score
  ];

  $prev = $score;
}

// 3) Output only the chosen student
$student = $positions[$studId];
$rankPosition = ordinalSuffix($student['position']);
$remtag = strip_tags($rankPosition);

?>
<div id="notification-containers" class="notification-containers"></div>
<div class="insider">
  <div class="container">
    <div class="cat-pag">

      <div class="card mt-3">
        <div class="card-header">
          <form action="" method="POST" style="display: flex; gap: 20px;">
            <button class="btn btn-sm primary text-sm" 
            onclick="switchToForm(); 
            event.preventDefault();">
            Edit Record 
            <i class="fa fa-edit"></i>
            </button>
            <a href="my_class_results.php" 
            class="btn btn-sm info text-sm">
            <i class="fa fa-caret-left"></i> Go back</a>
          </form>
          </div>
          <div class="card-body" style="background: #F7F9FB;">
            <div class="dashboard">

              <!-- Student Info Card -->
              <div class="student-card">
                <div class="student-header">
                  <img src="../../student/images/avatar/<?=$theImg?>" alt="Student Photo">
                  <div>
                    <h2><?php echo strtoupper($surname).', '.$othernames; ?></h2>
                    <h5><?=$stdVal?></h5>
                  </div>
                </div>

                <!-- Already Entered Data -->
                <div id="student-data">
                  <?php
                  if ($comdes_status < 1) { ?>
                    <div id="no-data" class="info-box">
                      No record for student attendance and activities.
                    </div>
                  <?php }else{
                    $recordRow = $stmtComent->fetch(PDO::FETCH_ASSOC);
                    $presentNo = $recordRow['attendance'];
                    $comment  = $recordRow['comment'];
                    $vp_comment = $recordRow['vp_comment'];
                    $data_position = $recordRow['position'];
                    ?>
                    <div class="entered-data">
                      <p><strong>Attendance:</strong> <?=$presentNo?>/<?=$times_opened?></p>
                      
                      <p><strong>Comment:</strong> <?=$comment?></p>
                        <!-- Hardworking and respectful student. Keep it up! -->
                        <!-- Principal or VP Comments -->
                        <?php
                        if ($vp_comment == 'No comment yet!' || $comdes_status < 1) {?>
                          <div id="no-data" class="info-box">
                          No comment yet from Principal.
                        </div>
                        <?php }else{?>
                          <p><strong>Principal's Comment:</strong> <?=$vp_comment?></p>
                        <?php }
                        ?>
                        <p><strong>Position: <?=$data_position?></strong></p>
                    </div>
                  <?php }
                  ?>
                  
                  <?php
                  if ($currentResult =='') {?>
                    <div id="" class="info-box">
                      No result data entered yet for this student.
                    </div>
                  <?php }else{?>
                    <!-- Subjects Table -->
                    <table>
                      <thead>
                        <tr>
                          <th class="text-sm">Subject</th>
                          <th class="text-sm">CA1</th>
                          <th class="text-sm">CA2</th>
                          <th class="text-sm">Exam</th>
                          <th class="text-sm">Total</th>
                          <th class="text-sm">Grade</th>
                        </tr>
                      </thead>
                      <tbody>
                        <?php
                        while ($resultRow = $stmtResult->fetch(PDO::FETCH_ASSOC)) {
                          $subject = $resultRow['subject'];
                          $test_score = $resultRow['test_score'];
                          $second_test = $resultRow['second_test'];
                          $exam_score = $resultRow['exam_score'];
                          $total_score = $resultRow['total'];
                          $grade      = $resultRow['grade']; ?>
                        <tr>
                          <td class="text-sm"><?=$subject?></td>
                          <td class="text-sm"><?=$test_score?></td>
                          <td class="text-sm"><?=$second_test?></td>
                          <td class="text-sm"><?=$exam_score?></td>
                          <td class="text-sm"><?=$total_score?></td>
                          <td class="text-sm"><?=$grade?></td>
                        </tr>
                        <?php } ?>
                      </tbody>
                    </table>
                    <!-- <button class="btn" onclick="switchToForm()">Edit Record</button> -->
                 <?php }
                  ?>
                </div>

              <!-- Form to enter data -->
              <form action="" method="POST" id="student-form" style="display:none; margin-top:15px;">
                <?php
                // Save New Record
                if ($comdes_status < 1) {?>

                <div class="form-group">
                  <label>Position (Overall)</label>
                  <input type="text" placeholder="edit postion" name="position" value="<?=$remtag?>" required="">
                </div>

                <div class="form-group">
                  <label>Attendance (Present Times Only)</label>
                  <input type="text" placeholder="e.g. 42" name="attendance" required="">
                </div>

                <div class="form-group comment-box">
                  <label>Class Teacher's Comment</label>
                  <textarea id="teacherComment" 
                    name="comment"
                    placeholder="e.g. Hardworking and respectful student."
                    required></textarea>

                  <div class="sug-area">
                    <button class="sug" type="button" onclick="toggleSug('teacherSug')">
                      <i class="fa fa-comment-dots"></i> Suggestions
                    </button>
                  </div>

                  <div class="suggested-bg" id="teacherSug">
                    <div class="sugMsgBg" onclick="insertComment('teacherComment', this)">
                      <i class="fa fa-commenting"></i><span>Shows consistent improvement in all subjects.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('teacherComment', this)">
                      <i class="fa fa-commenting"></i><span>Hardworking and respectful student, keep it up!</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('teacherComment', this)">
                      <i class="fa fa-commenting"></i><span>Good performance this term, aim even higher next time.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('teacherComment', this)">
                      <i class="fa fa-commenting"></i><span>Very attentive in class and always eager to learn.</span>
                    </div>
                  </div>
                </div>
               <?php
               // Check if school opening times have been updated
               if ($check_if_exist == TRUE ) { ?>
                 <button name="save-record" 
                  type="submit" 
                  class="btn primary">Save Record
                </button>
               <?php }else{ ?>
                <button name="error-save-record" 
                  type="submit" 
                  class="btn primary">Save Record
                </button>
               <?php }

               ?>

                <!-- Already Exists, need updating -->
                <?php }else{?>
                <div class="form-group">

                  <div class="form-group">
                    <label>Position (Overall)</label>
                    <input type="text" 
                      placeholder="edit postion" 
                      name="position" 
                      value="<?=$data_position?>" 
                      required="">
                  </div>

                  <label>Attendance (Present Times Only)</label>
                  <input type="text" placeholder="e.g. 42" name="attendance" value="<?=$presentNo?>">
                </div>

                <div class="form-group comment-box">
                  <label>Class Teacher's Comment</label>
                  <textarea id="teacherComment" 
                    name="comment"
                    required><?=$comment?></textarea>

                  <div class="sug-area">
                    <button class="sug" type="button" onclick="toggleSug('teacherSug')">
                      <i class="fa fa-comment-dots"></i> Suggestions
                    </button>
                  </div>

                  <div class="suggested-bg" id="teacherSug">
                    <div class="sugMsgBg" onclick="insertComment('teacherComment', this)">
                      <i class="fa fa-commenting"></i><span>Shows consistent improvement in all subjects.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('teacherComment', this)">
                      <i class="fa fa-commenting"></i><span>Hardworking and respectful student, keep it up!</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('teacherComment', this)">
                      <i class="fa fa-commenting"></i><span>Good performance this term, aim even higher next time.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('teacherComment', this)">
                      <i class="fa fa-commenting"></i><span>Very attentive in class and always eager to learn.</span>
                    </div>
                  </div>
                </div>
                
                <button name="edit-record" type="submit" class="btn primary">Update Record</button>
                <?php }
                ?>
              </form>
            </div>
            <!-- Dashboard Ends -->
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<?php
// Error: school opening time not set
if (isset($_POST['error-save-record'])) {
  
  $msgTitle = "<b>Unable to Save Record</b>";
  $msgBody = "<center>
    No record found for this term/session school opening time. 
    <br>Please contact the web administrator for an update.
  </center>";
  $msgCloseBtn = "Close";
  
  include'includes/error_alert.php'; 
}
// Save New Record for student
if (isset($_POST['save-record'])) {
  $attendance = $_POST['attendance'];
  $comment    = $_POST['comment'];
  $classPosition = $_POST['position'];
  // Saved New comment
  $insertCom = "INSERT INTO class_teacher_inputs 
                (student_id, term, session, comment, attendance, position)
                VALUES(?,?,?,?,?,?) ";
  $insertPdo = $pdo->prepare($insertCom);
  $insertPdo->execute([$studentId, $current_term, $current_session, $comment, $attendance, $classPosition]);

  $_SESSION['message'] = 'Record Saved Successfully';
  $_SESSION['type'] = 'success';?>

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


}
// Save Editing Records 
if (isset($_POST['edit-record'])) {
  $attendance = $_POST['attendance'];
  $comment    = $_POST['comment'];
  $classPosition = $_POST['position'];
  // Update Record
  $update = "UPDATE class_teacher_inputs SET attendance = ?, comment = ?, 
              position = ?  WHERE student_id = ? ";
  $updateStmt = $pdo->prepare($update);
  $updateStmt->execute([$attendance, $comment, $classPosition, $studentId]);

  $_SESSION['message'] = "Record Updated Successfully";
  $_SESSION['type'] = "success";?>

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

}



?> 
<script>
  // Switch between view mode and form mode
  function switchToForm() {
    document.getElementById("student-data").style.display = "none";
    document.getElementById("student-form").style.display = "block";
  }
</script>


<?php include 'includes/footer.php'; ?>




<!-- Modal Styling -->
<style>
.dashboard {
  max-width: 900px;
  margin: auto;
}

/* Student Profile Card */
.student-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.student-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.student-header img {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 15px;
}

.student-header h2 {
  margin: 0;
  font-size: 18px;
  color: #222;
  font-family: sans-serif;
  font-weight: bold;
}
.student-header h5{
  font-size: 16px;
}
.info-box {
  background: #eef3fc;
  border-left: 4px solid #007bff;
  padding: 10px 15px;
  margin-bottom: 15px;
  color: #444;
  border-radius: 4px;
  font-size: 14px;
}

.entered-data p {
  margin: 6px 0;
  font-size: 14px;
}

/* Subject Table */
table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
  margin-top: 20px;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

table thead {
  background: #007bff;
  color: #fff;
}

table th, table td {
  padding: 12px 15px;
  text-align: center;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

table tr:last-child td {
  border-bottom: none;
}

table tbody tr:hover {
  background: #f9f9f9;
}

/* Buttons */
.btn {
  display: inline-block;
  padding: 8px 15px;
  /*background: #007bff;*/
  color: #fff;
  border-radius: 6px;
  font-size: 14px;
  border: none;
  cursor: pointer;
  transition: background 0.3s;
  margin-top: 10px;
}

.btn:hover {
  /*background: #0056b3;*/
  color: #fff;
}

/* Form Styling */
.form-group {
  margin-bottom: 15px;
}

.form-group label {
  font-weight: 600;
  display: block;
  margin-bottom: 5px;
}

.form-group input, 
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
   background: #f9f9f9;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
  font-size: 14px;
}

@media(max-width: 992px){
  .student-header h2{
    font-size: 13px;
  }
  .student-header h5{
    font-size: 12px;
  }
  .student-header img{
    width: 50px;
    height: 50px;
  }
  .info-box{
    font-size: 11px;
    padding: 10px 10px;
  }
  .text-sm{
      font-size: 12px;
  }
  .card-body{
    padding: 5px;
  }
  .student-card{
    padding: 10px;
  }
  .form-group label{
    font-size: 13px;
  }

} 
</style>
<script>
function toggleSug(id) {
  // Close other suggestion boxes if open
  document.querySelectorAll('.suggested-bg').forEach(box => {
    if (box.id !== id) box.classList.remove('active');
  });
  // Toggle current
  document.getElementById(id).classList.toggle('active');
}

function insertComment(textareaId, el) {
  const commentText = el.querySelector('span').innerText;
  const textarea = document.getElementById(textareaId);
  textarea.value = commentText;
  // Close suggestions after selecting
  el.parentElement.classList.remove('active');
}
</script>

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

