<?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>
@media(max-width: 992px){
  .insider{
      margin-top: -50px;
  }
  .card{
    height: 500px;
  }
  .negative{
    height: 500px;
  } 
  .card-header h5{
    font-size: 12px;
  }
}

.card{
    height: 500px;
}
.card-header h5{
  font-size: 13px;
  font-weight: bold;
}
.custom-fieldset-box{
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  position: relative;
  margin-bottom: 20px;
  background: #F7F9FB;
}
.custom-field-title{
  position: absolute;
  top: -12px;
  left: 15px;
  background: #F7F9FB;
  padding: 0 10px;
  font-weight: bold;
  color: #1E5F67;
  font-size: 15px;
}

input{
  width: 100%;
  height: 50px;
  border:2px solid #ccc;
  outline: none;
  border-radius: 5px;
  padding-left: 10px;
  padding-right: 10px;
}
select{
  width: 100%;
  height: 50px;
  border:2px solid #ccc;
  outline: none;
  border-radius: 5px;
  padding-left: 10px;
  padding-right: 10px;
}
.avater{
    width: 60px;
    height: 60px;
    border:2px solid #ccc;
    border-radius: 50%;
}
</style>
<?php
// studentId is the formal row name for student_image
// Get next admission number
$adminNo = generateAdmissionNumber($pdo);
?>
<!-- Main page starts here -->
<div id="notification-containers" class="notification-containers"></div>
<div class="insider">
  <div class="container">
    <div class="cat-pag">
      <form action="" method="POST" enctype="multipart/form-data">
        <div class="cat-page-header d-flex justify-content-between align-items-center">
          <h5></h5>
          <div>
                          
            <button name="register-btn" 
              class="btn btn-sm 
              info text-white">
              Add Student 
              <i class="fa fa-user-plus"></i>
            </button>

          </div>
        </div>

        <div class="card mt-3">
          <div class="card-header" style="display: flex; align-items: center; justify-content: space-between;">
            <h5>ADD NEW STUDENT</h5>
          </div>
          <div class="card-body" style="background: #F7F9FB;">
            <div class="row" style="margin-top: -10px;">

              <!-- Disabled AdminNo -->
              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title"><i class="fa fa-id-card"></i>Admin No:</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <input type="text" 
                      value="<?=$adminNo?>" 
                      disabled="" 
                      class="form-control">
                    </div>
                  </div>
                </div>
              </div>

              <!-- Surname -->
              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Surname</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <input type="text" 
                      name="surname" 
                      placeholder="Student Surname" 
                      required="" 
                      class="form-control">
                    </div>
                  </div>
                </div>
              </div>

              <!-- Othernames -->
              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Other Names</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <input type="text" 
                      name="othername" 
                      placeholder="Second & Last Names"
                      required="" 
                      class="form-control">               
                    </div>
                  </div>
                </div>
              </div>

              <!-- Date of birth -->
              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Date of Birth</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <input type="date" 
                      name="dob"
                      required="" 
                      class="form-control">                  
                    </div>
                  </div>
                </div>
              </div>

              <!-- Gender -->
              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Gender</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <select name="gender">
                        <option value="M">Male</option>
                        <option value="F">Female</option>
                      </select>                          
                    </div>
                  </div>
                </div>
              </div>

              <!-- Class -->
              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Class</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                     <select name="class" required="">
                      <option hidden="">--Select Class -- </option>
                      <?php
                      $clss = "SELECT * FROM classes";
                      $stmtClass = $pdo->prepare($clss);
                      $stmtClass->execute([]);
                      while ($clList = $stmtClass->fetch(PDO::FETCH_ASSOC)) {
                        $className = $clList['className'];?>
                        <option value="<?=$className?>"><?=$className?></option>
                      <?php };
                      ?>
                     </select>                       
                    </div>
                  </div>
                </div>
              </div>

              <!-- New Password -->
              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">New Password</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <input type="password" 
                      name="new_password"
                      placeholder="Set New Password" 
                      required="" 
                      class="form-control">                          
                    </div>
                  </div>
                </div>
              </div>

              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Confirm Password</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <input type="password"
                      required=""
                      placeholder="Enter password again" 
                      name="confirm" 
                      class="form-control">                          
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>

    </div>
   
  </div>
</div>
<?php
if (isset($_POST['register-btn'])) {
    // Get next admission number
    $stmt = $pdo->query("SELECT MAX(studId) AS lastId FROM students");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $nextId = ($row && $row['lastId']) ? $row['lastId'] + 1 : 1;
    $admission_no = "DEG/" . str_pad($nextId, 3, "0", STR_PAD_LEFT);

    // Collect form values
    $surname = $_POST['surname'];
    $otherNames = $_POST['otherNames'];
    $gender = $_POST['gender'];
    $class = $_POST['class'];
    $dob = $_POST['dob'];
    $password = password_hash($surname . '123', PASSWORD_DEFAULT);

    try {
        $pdo->beginTransaction();

        $insert = "INSERT INTO students (surname, otherNames, gender, password, class, term, session)
                   VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($insert);
        $stmt->execute([$surname, $otherNames, $gender, $password, $class, $current_term, $current_session]);

        $lastId = $pdo->lastInsertId();

        // Update admission number
        $update = "UPDATE students SET admission_no = ? WHERE studId = ?";
        $pdo->prepare($update)->execute([$admission_no, $lastId]);

        // Insert into image table
        $pdo->prepare("INSERT INTO student_image (studentId, dob) VALUES (?, ?)")
            ->execute([$lastId, $dob]);

        $pdo->commit();

        echo "<div class='alert alert-success text-center'>
                <b>Registration Successful!</b><br>
                Admission Number: <b>$admission_no</b>
              </div>";

    } catch (Exception $e) {
        $pdo->rollBack();
        echo "<div class='alert alert-danger text-center'>
                Something went wrong: {$e->getMessage()}
              </div>";
    }
}

?>


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


<script>
    $(document).ready(function () {
        $('#example').DataTable();
        $('#SelectAllBoxes').click(function () {
            $('.checkBoxes').prop('checked', this.checked);
        });
    });

    function openModal(id) {
        document.getElementById(id).style.display = "block";
    }

    function closeModal(id) {
        document.getElementById(id).style.display = "none";
    }

    function handleDelete() {
        const checked = document.querySelectorAll("input[name='checkBoxArray[]']:checked");
        if (checked.length === 0) {
            alert("No user selected!");
            return;
        }
        openModal('modal-delete');
    }
   
</script>

<script type="text/javascript">
    document.getElementById("fileImg").onchange = function(){
      document.getElementById("image").src = URL.createObjectURL(fileImg.files[0]); // Preview new image
      document.getElementById("cancel").style.display = "block";
      document.getElementById("uploads").style.display = "none";
    }
    var userImage = document.getElementById('image').src;
    document.getElementById("cancel").onclick = function(){
      document.getElementById("image").src = userImage; // Back to previous image
      document.getElementById("cancel").style.display = "none";
      document.getElementById("uploads").style.display = "block";
    }      
</script>


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

