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

.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;
}
form{
  display: flex; gap: 20px; 
  padding-left: 40px; 
  width: 100%;
  align-items: center;
}
@media(max-width: 992px){
  .negative h5{
    font-size: 15px;
  }
  .negative a{
    font-size: 14px;
  }
  .negative a i{
    font-size: 14px;
  }
  form{
    padding-left: 0;
    gap:10px;
  }
  form button{

  }
  #form-top{
    font-size:10px !important;
    padding: 2px !important;
   }
}

</style>

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

  $className = $unpack[0];
  $term = $unpack[1];
  $session = $unpack[2];
  $stdId  = $unpack[3];

  $decryptId = decryptData($stdId);
}else{
  header('Location:my-students.php');
}
$className; // class name
$term; // this term
$session; // this session
$studentId = $decryptId;

// Go back link
$back_link = $className.'*'.$term.'*'.$session;

// 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'];

// 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, $term, $session]);
$recordRow = $stmtComent->fetch(PDO::FETCH_ASSOC);

$presentNo = $recordRow['attendance'];
$comment  = $recordRow['comment'];
$vp_comment = $recordRow['vp_comment'];
$check_status = $recordRow['check_status'];
$position     = $recordRow['position'];


// Get the results details
$resultNow = "SELECT * FROM results WHERE stdId = ? 
            AND class = ? AND term = ? AND session = ? ";
$stmtResult = $pdo->prepare($resultNow);
$stmtResult->execute([$studentId, $className, $term, $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'];
?>
<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" style="width: 100%; display: flex;">
          <form action="" method="POST" style=" ">
            <button class="btn btn-sm primary" 
            onclick="switchToForm(); 
            event.preventDefault();">
            <i class="fa fa-edit"></i>
            Comment
            </button>
            <?php
            if ($check_status == 'Pending') {?>
              <button 
              class="btn btn-sm success"
              name="mark-btn"> 
              <i class="fa fa-check-circle"></i>
              Mark 
              </button>
            <?php }else{?>

              <button 
              class="btn btn-sm invoice"> 
              <i class="fa fa-check-circle"></i>
              Checked 
              </button>

            <?php }?>
            <div style="">
            <a href="review.php?rsltVal=<?=$back_link?>" 
              class="btn btn-sm primary">
              <i class="fa fa-arrow-left"></i> 
              Go Back
            </a>
            </div>
          </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><?=$studentId?></h5>
                  </div>
                </div>

                <!-- Already Entered Data -->
                <div id="student-data">
                  <div class="entered-data">
                    <p><strong>Attendance:</strong> <?=$presentNo.'/'.$times_opened?></p>
                    <p><strong>Comment:</strong> <?=$comment?> </p>
                    <p><strong>Position: <?=$position?></strong> </p>

                    <?php
                    if ($vp_comment == 'No comment yet!') { ?>
                      <div id="no-data" class="info-box">
                        No Comment yet from V/Principal to <?=$surname?>.
                        <button 
                        onclick="switchToForm()"
                        class="btn btn-sm primary text-white text-sm "><i class="fa fa-plus"></i> Add comment</button>
                      </div>
                    <?php }else{?>
                      <p><strong>VP's Comment:</strong> <?=$vp_comment?></p>
                      <!-- Hardworking and respectful student. Keep it up! -->
                    <?php }
                    ?>
                  </div>
                  
                  <?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">Test Score</th>
                          <th class="text-sm">Exam Score</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'];
                          $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"><?=$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 ($vp_comment == 'No comment yet!') {?>

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

                <div class="form-group comment-box">
                  <label>Principal / Vice Principal’s Comment</label>
                  <textarea id="principalComment" 
                    name="vp_comment"
                    placeholder="e.g. Excellent student with great potential."
                    required></textarea>

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

                  <div class="suggested-bg" id="principalSug">
                    <div class="sugMsgBg" onclick="insertComment('principalComment', this)">
                      <i class="fa fa-graduation-cap"></i><span>Excellent term performance, continue in this spirit.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('principalComment', this)">
                      <i class="fa fa-graduation-cap"></i><span>Keep up your hard work, you are a model student.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('principalComment', this)">
                      <i class="fa fa-graduation-cap"></i><span>Commendable behavior and academic excellence.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('principalComment', this)">
                      <i class="fa fa-graduation-cap"></i><span>Outstanding performance. We are proud of your progress!</span>
                    </div>
                  </div>
                </div>
                
                <button name="edit-record" type="submit" class="btn primary">Save Record</button>

                <!-- Already Exists, need updating -->
                <?php }else{?>

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

                <div class="form-group comment-box">
                  <label>Principal / Vice Principal’s Comment</label>
                  <textarea id="principalComment" 
                    name="vp_comment"
                    placeholder="e.g. Excellent student with great potential."
                    required><?=$vp_comment?></textarea>

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

                  <div class="suggested-bg" id="principalSug">
                    <div class="sugMsgBg" onclick="insertComment('principalComment', this)">
                      <i class="fa fa-graduation-cap"></i><span>Excellent term performance, continue in this spirit.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('principalComment', this)">
                      <i class="fa fa-graduation-cap"></i><span>Keep up your hard work, you are a model student.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('principalComment', this)">
                      <i class="fa fa-graduation-cap"></i><span>Commendable behavior and academic excellence.</span>
                    </div>
                    <div class="sugMsgBg" onclick="insertComment('principalComment', this)">
                      <i class="fa fa-graduation-cap"></i><span>Outstanding performance. We are proud of your progress!</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
// Mark as Read
if (isset($_POST['mark-btn'])) {
  $currently = 'Checked';
  // Saved New comment
  $updSta = "UPDATE class_teacher_inputs SET check_status = ? WHERE student_id = ?";
  $theupdPdo = $pdo->prepare($updSta);
  $theupdPdo->execute([$currently, $studentId]);

  $_SESSION['message'] = 'Marked as Checked 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'])) {
  $vp_comment         = $_POST['vp_comment'];
  $teacher_comment    = $_POST['teacher_comment'];
  // Update Record
  $update = "UPDATE class_teacher_inputs SET vp_comment = ?, comment = ? 
            WHERE student_id = ? ";
  $updateStmt = $pdo->prepare($update);
  $updateStmt->execute([$vp_comment, $comment, $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: 14px;
  }
  .student-header h5{
    font-size: 13px;
  }
  .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>

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

<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>