<?php include("../database/auth_check.php"); ?>

<?php
$con = mysqli_connect('localhost', 'root', ''); 
$db = mysqli_select_db($con, 'WSAS');

if (isset($_GET['success'])): ?>
<?php endif; ?>

<?php

$sy_query = mysqli_query($con, "SELECT sy_id, sy_begin FROM school_year WHERE is_active = 1");
$sy = mysqli_fetch_assoc($sy_query);

if (!$sy) {
    die("No active school year found. Please add a school year first.");
}

$sy_begin = $sy['sy_begin'];

$last = mysqli_query($con, "SELECT student_id_num FROM adminstudent WHERE student_id_num LIKE '$sy_begin-%'ORDER BY student_id DESC LIMIT 1");

if(mysqli_num_rows($last) > 0){

    $row = mysqli_fetch_assoc($last);
    $last_id = $row['student_id_num'];

    $num = explode("-", $last_id)[1];
    $new_num = $num + 1;

}else{
    $new_num = 1;
}

$next_student_id = $sy_begin . "-" . str_pad($new_num,3,"0",STR_PAD_LEFT);

?>

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Students - Admin</title>
    <link rel="shortcut icon" type="x-icon" href="../images/logo.png">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="../Style/navstyle.css">

<style>
/* Main dashboard container */
.dashboard-container {
  display: flex;
  min-height: 100vh;
  background-color: #f4f6f8;
  font-family: "Segoe UI", sans-serif;
}

.mainbar {
    margin-left: 260px;
    width: calc(100% - 260px);
    flex: 1;
    display: flex;
    flex-direction: column;
} 
 
.open-btn {
  background-color: #4a9c3f;
  color: #fff;
  padding: 10px 18px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
  font-size: 12px;
}

.open-btn:hover {
  background-color: #3e8c36;
}

/* Mainbar content */
.mainbar-context {
  flex: 1;
  padding: 20px 25px;
  overflow-y: auto;
}

/* Inner containers */
.container, .container1 {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

/* Subject box / cards */
.subject {
  background-color: #4a9c3f;
  color: #fff;
  padding: 20px;
  flex: 1 1 300px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 4px 10px rgba(0,0,0,0.05);
  transition: transform 0.2s;
}

.subject:hover {
  transform: translateY(-3px);
}

/* Labels inside cards */
.label {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
}

.label-percent {
  font-size: 24px;
  font-weight: bold;
}

/* Student table */
table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0,0,0,0.05);
  text-align: center;
}

table th, table td {
  padding: 12px 10px;
  border-bottom: 1px solid #e0e0e0;
  font-size: 12px;
  color: #333;
}

table th {
  background-color: #4a9c3f;
  color: #fff;
  font-weight: 600;
}

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

table tr:hover {
  background-color: rgba(74, 156, 63, 0.1);
  transition: background-color 0.3s;
}

.st_view {
  text-decoration: none;
  color: #4a9c3f;
  font-weight: 500;
}

.st_view:hover {
  text-decoration: underline;
}

/* Search box */
.search-container {
  margin-bottom: 15px;
  text-align: right;
}

.search-input {
  padding: 6px 12px;
  width: 200px;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 12px;
}

.search-input:focus {
  outline: none;
  border-color: #4a9c3f;
  box-shadow: 0 0 3px rgba(74,156,63,0.5);
}

/* Responsive adjustments */
@media (max-width: 1024px) {
  .mainbar {
    margin-left: 0;
    margin-top: 70px;
  }
  .dashboard-container {
    flex-direction: column;
  }
  .container, .container1 {
    flex-direction: column;
  }
  .subject {
    flex: 1 1 100%;
  }
}
</style>
<style>
/* Modal overlay */
.modal {
  display: none;
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  overflow-y: auto;
  padding: 20px;
}

/* Modal content box */
.modal-content {
  background: #fff;
  max-width: 650px;      /* Widened modal */
  width: 95%;
  margin: 50px auto;
  padding: 30px 35px;    /* More padding for comfort */
  border-radius: 10px;
  box-shadow: 0 6px 20px rgba(0,0,0,0.2);
  animation: pop 0.3s ease;
  position: relative;
  box-sizing: border-box;
}

/* Pop animation */
@keyframes pop {
  from { transform: scale(0.8); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

/* Close button */
.close-btn {
  position: absolute;
  top: 15px;
  right: 20px;
  font-size: 26px;
  font-weight: bold;
  cursor: pointer;
  color: #444;
  transition: color 0.3s;
}

.close-btn:hover {
  color: #4a9c3f;
}

/* Modal title */
.student-title {
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 25px;
  color: #333;
}

/* Form styling */
.student-form {
  display: flex;
  flex-direction: column;
  gap: 18px;  /* Increase spacing between fields */
}

/* Form groups */
.student-form .form-group {
  display: flex;
  flex-direction: column;
}

/* Form labels */
.student-form label {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 6px;
}

/* Inputs and selects */
.student-form input,
.student-form select {
  padding: 11px 12px;
  font-size: 14px;
  border-radius: 6px;
  border: 1px solid #ccc;
  outline: none;
  transition: all 0.2s;
}

.student-form input:focus,
.student-form select:focus {
  border-color: #4a9c3f;
  box-shadow: 0 0 4px rgba(74,156,63,0.3);
}

.readonly-input {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

/* Radio button container styling */
.student-form .form-group .radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;   /* Space between radio buttons */
}

.student-form .form-group input[type="radio"] {
  cursor: pointer;
  margin-right: 6px;
}

/* Submit button */
.submit-btn {
  background-color: #4a9c3f;
  color: #fff;
  border: none;
  padding: 14px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: 5px;
}

.submit-btn:hover {
  background-color: #3e8c36;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .modal-content {
    margin: 30px 15px;
    padding: 25px 20px;
  }
  .student-form .form-group .radio-group {
    flex-direction: column; /* Stack radios on smaller screens */
  }
}

.action_btn {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 12px;
  text-decoration: none;
  color: #fff;
  font-family: inherit;
  transition: 0.3s ease;
}

.view_btn {
  background: #1261A0;
}

.view_btn:hover {
  background: #0f4d80;
}

.cur_btn {
 background: #EE7A02;
  color: #fff;
}

.cur_btn:hover {
  background: #c36100;
}
</style>

<body>
   <div class="dashboard-container">
    
    <?php include('adminnav.php'); ?>

    
    <aside class="mainbar">
      <div class="mainbar-context">
        <div class="container1">
            <button id="openModal" class="open-btn">ADD STUDENT</button>
        </div>
        <div class="container">
          <div class="subject">


            <div class="search-container">
                <input type="text" id="subjectSearch" placeholder="Search Students..." class="search-input">
            </div>
            <?php
              $select_products = mysqli_query($con, "SELECT * FROM `adminstudent`");
              ?>

              <table>
                  <tr>
                      <th>Student ID Number</th>
                      <th>Student Name</th>
                      <th>Course</th>
                      <th colspan=2>Action</th>
                  </tr>

                  <?php
                  if(mysqli_num_rows($select_products) > 0){
                      while($fetch_product = mysqli_fetch_assoc($select_products)){
                  ?>
                      <tr>
                          <td>
                              <?php echo $fetch_product['student_id_num']; ?>
                              <input type="hidden" name="student_id_num" value="<?php echo $fetch_product['student_id_num']; ?>">
                          </td>

                          <td>
                              <?php 
                              echo $fetch_product['l_name'] . ', ' . 
                                  $fetch_product['f_name'] . ' ' . 
                                  $fetch_product['m_name'];

                              if(!empty($fetch_product['suffix'])){
                                  echo ' ' . $fetch_product['suffix'];
                              }
                              ?>
                          </td>

                          <td>
                            <?php
                            $course_id = $fetch_product['course_id']; 
                            $course_res = mysqli_query($con, "SELECT course_name FROM admincourse WHERE course_id = '$course_id'");

                            if ($course_res && mysqli_num_rows($course_res) > 0) {
                                $course_row = mysqli_fetch_assoc($course_res);
                                echo $course_row['course_name'];
                            } else {
                                echo "N/A";
                            }
                            ?>
                            </td>

                         <td>
                          <a class="action_btn view_btn" href="../view/student_sub.php?student_id=<?php echo $fetch_product['student_id']; ?>">VIEW</a>
                        </td>
                        <td>
                          <a class="action_btn cur_btn" href="../view/student_curriculum.php?student_id=<?php echo $fetch_product['student_id']; ?>">CURRICULUM</a>
                        </td>
                      </tr>
                      <?php
                          }
                      }
                      ?>
                  </table>


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

<div id="courseModal" class="modal">
  <div class="modal-content">
    <span id="closeModal" class="close-btn">&times;</span>

    <h2 class="student-title">Add Student</h2>

    <form id="studentForm" class="student-form" action="../database/student_connect.php" method="POST">

      <!-- Student ID -->
      <div class="form-group">
        <label>Student ID Number <span style="color:red">*</span></label>
        <input type="text" name="student_id_num" id="student_id_num" class="readonly-input" value="<?php echo $next_student_id; ?>" readonly>
      </div>

      <!-- First Name -->
      <div class="form-group">
        <label>First Name <span style="color:red">*</span></label>
        <input type="text" name="f_name" required>
      </div>

      <!-- Middle Name -->
      <div class="form-group">
        <label>Middle Name</label>
        <input type="text" name="m_name">
      </div>

      <!-- Suffix -->
      <div class="form-group">
        <label>Suffix</label>
        <input type="text" name="suffix" placeholder="e.g., Jr., Sr., III">
      </div>

      <!-- Last Name -->
      <div class="form-group">
        <label>Last Name <span style="color:red">*</span></label>
        <input type="text" name="l_name" id="l_name" required>
      </div>

      <div class="form-group">
        <label>Sex <span style="color:red">*</span></label>
        <div class="radio-group">
          <input type="radio" name="sex" value="Male" required> Male
          <input type="radio" name="sex" value="Female" required> Female
        </div>
      </div>

      <div class="form-group">
      <label>Course <span style="color:red">*</span></label>
      <select name="course_id" required>
        <option value="">Select Course</option>
        
        <?php
          $course = mysqli_query($con, "SELECT * FROM admincourse");
          while ($row = mysqli_fetch_assoc($course)) {
            echo "<option value='{$row['course_id']}'>{$row['course_name']}</option>";
          }
        ?>
        
      </select>
    </div>

      <!-- Enrollment Status -->
      <div class="form-group">
        <label>Enrollment Status <span style="color:red">*</span></label>
        <select name="e_status" id="e_status" required onchange="toggleStatusType()">
          <option value="">Select Status</option>
          <option value="Regular">Regular</option>
          <option value="Irregular">Irregular</option>
        </select>
      </div>

      <div class="form-group" id="yearLevelGroup" style="display:none;">
      <label>Year Level <span style="color:red">*</span></label>
      <select name="year_level" id="year_level">
        <option value="">Select Year</option>
        <option value="1">1st Year</option>
        <option value="2">2nd Year</option>
        <option value="3">3rd Year</option>
        <option value="4">4th Year</option>
      </select>
    </div>

      <!-- Status Type -->
      <div class="form-group" id="statusTypeGroup" style="display:none;">
        <label>Status Type <span style="color:red">*</span></label>
        <select name="status_type" id="status_type">
          <option value="">Select Type</option>
          <option value="Transferee">Transferee</option>
          <option value="Old Student">Old Student</option>
        </select>
      </div>

      <!-- Email -->
      <div class="form-group">
        <label>Email <span style="color:red">*</span></label>
        <input type="email" name="email" required>
      </div>

      <!-- CDLB SHS Graduate -->
      <div class="form-group">
        <label>CDLB SHS Graduate? <span style="color:red">*</span></label>
        <div class="radio-group">
          <input type="radio" name="is_alumni" value="Yes" required> Yes
          <input type="radio" name="is_alumni" value="No" required> No
        </div>
      </div>

      <!-- Password -->
      <div class="form-group">
        <label>Password</label>
        <input type="text" name="pword" id="pword" readonly placeholder="Auto-generated Password">
      </div>

      <button type="button" id="openConfirmAdd" class="submit-btn">Submit</button>
    </form>
  </div>
</div>

<div id="confirmModal" class="modal">
  <div class="modal-content">
    <h3 id="confirmMessage">Are you sure?</h3>
    <br>
    <button id="yesBtn" class="open-btn">Yes</button>
    <button id="noBtn" class="close-btn">Cancel</button>
  </div>
</div>

     <script src="../Jscript/script.js"></script>
     <script>
        const openBtn = document.getElementById("openModal");
        const modal = document.getElementById("courseModal");
        const closeBtn = document.getElementById("closeModal");

        openBtn.addEventListener("click", () => {
          modal.style.display = "block";
        });

        closeBtn.addEventListener("click", () => {
          modal.style.display = "none";
        });

        window.addEventListener("click", (e) => {
          if (e.target === modal) {
            modal.style.display = "none";
          }
        });
      </script>

      <script>
const openConfirmAdd = document.getElementById("openConfirmAdd");
const confirmModal = document.getElementById("confirmModal");
const yesBtn = document.getElementById("yesBtn");
const noBtn = document.getElementById("noBtn");
const studentForm = document.getElementById("studentForm");
const eStatus = document.getElementById("e_status");
const confirmMessage = document.getElementById("confirmMessage");

// Open modal
openConfirmAdd.addEventListener("click", () => {

  let message = "Are you sure you want to add this student?";

  if (eStatus.value === "Irregular") {
    message = "Are you sure you want to add this student?\nYou will proceed to subject evaluation.";
  }

  confirmMessage.innerText = message;
  confirmModal.style.display = "block";
});

// Cancel
noBtn.addEventListener("click", () => {
  confirmModal.style.display = "none";
});

// Confirm submit
yesBtn.addEventListener("click", () => {
  studentForm.submit();
});

// Close outside click
window.addEventListener("click", (e) => {
  if (e.target === confirmModal) {
    confirmModal.style.display = "none";
  }
});
</script>

      <script>
      const studentIdInput = document.getElementById("student_id_num");
      const lastNameInput = document.getElementById("l_name");
      const passwordInput = document.getElementById("pword");

      function generatePassword() {
        const lname = lastNameInput.value.trim().toLowerCase();
        const studentId = studentIdInput.value.trim();

        if (lname && studentId.length >= 4) {
          const last4 = studentId.slice(-4);
          passwordInput.value = lname + last4;
        } else {
          passwordInput.value = "";
        }
      }

      studentIdInput.addEventListener("input", generatePassword);
      lastNameInput.addEventListener("input", generatePassword);

      function toggleStatusType() {
      const status = document.getElementById("e_status").value;

      const statusGroup = document.getElementById("statusTypeGroup");
      const yearGroup = document.getElementById("yearLevelGroup");
      const semGroup = document.getElementById("semGroup");

      if (status === "Irregular") {
        statusGroup.style.display = "block";
        yearGroup.style.display = "none";
        semGroup.style.display = "none";
      } 
      else if (status === "Regular") {
        statusGroup.style.display = "none";
        yearGroup.style.display = "block";
        semGroup.style.display = "block";
      } 
      else {
        statusGroup.style.display = "none";
        yearGroup.style.display = "none";
        semGroup.style.display = "none";
      }
    }
    </script>

    <script>
      openBtn.addEventListener("click", () => {
        modal.style.display = "block";
        document.body.classList.add("modal-open");
      });

      closeBtn.addEventListener("click", () => {
        modal.style.display = "none";
        document.body.classList.remove("modal-open");
      });

      window.addEventListener("click", (e) => {
        if (e.target === modal) {
          modal.style.display = "none";
          document.body.classList.remove("modal-open");
        }
      });
    </script>
    <script>
      const searchInput = document.getElementById('subjectSearch');
      const table = document.querySelector('.container table');

      searchInput.addEventListener('input', function() {
          const filter = searchInput.value.toLowerCase();
          const rows = table.querySelectorAll('tbody tr, tr'); 

          rows.forEach((row, index) => {
              if(index === 0) return; 
              const subjectCode = row.cells[0].textContent.toLowerCase();
              const subjectName = row.cells[1].textContent.toLowerCase();

              if(subjectCode.includes(filter) || subjectName.includes(filter)){
                  row.style.display = '';
              } else {
                  row.style.display = 'none';
              }
          });
      });
      </script>

</body>
</html>