<?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>
.insider{
    margin-top: -60px;
}
@media(max-width: 992px){
  .insider{
      margin-top: -50px;
  }
  .card{
    height: 600px;
  }
  .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
if (isset($_GET['editVal'])) {
  $staffId = $_GET['editVal'];

  $sql = "SELECT * FROM staff WHERE staffId = ?";
  $stmt = $pdo->prepare($sql);
  $stmt->execute([$staffId]);

  $staffRow = $stmt->fetch(PDO::FETCH_ASSOC);

  $title      = $staffRow['title'];
  $fullname   = $staffRow['fullname'];
  $email      = $staffRow['email'];
  $mobile     = $staffRow['phone_number'];
  $password   = $staffRow['password'];
  $roles      = $staffRow['roles'];

  // Get class if any
  $sql_class = "SELECT class FROM class_teacher WHERE staffId = ?";
  $queryClass = $pdo->prepare($sql_class);
  $queryClass->execute([$staffId]);
  $lineRow = $queryClass->fetch(PDO::FETCH_ASSOC);
  $class = $lineRow['class'];

  if ($roles == 'vice_principal') {
    $dispRole = 'Vice Principal';
  }
  elseif ($roles == 'class_teacher') {
    $dispRole = 'Class Teacher';
  }
  elseif ($roles == 'subject_teacher') {
    $dispRole = 'Subject Teacher';
  }
  elseif ($roles == 'Admin') {
    $dispRole == 'Admin';
  }
  else{
    $dispRole = 'Principal';
  }

}
?>

<!-- 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">
        <div class="cat-page-header d-flex justify-content-between align-items-center">
          <h5></h5>
          <div>
                          
            <button name="edit-btn" 
              class="btn btn-sm 
              info text-white">
              Finish Editing Staff
              <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 STAFF</h5>
          </div>
          <div class="card-body" style="background: #F7F9FB;">
            <div class="row" style="margin-top: -10px;">

              <!-- Title -->
              <div class="col-lg-6 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Title</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <select name="title" required="">
                        <option value="<?=$title?>"><?=$title?></option>
                        <option value="Mr.">Mr.</option>
                        <option value="Mrs.">Mrs.</option>
                        <option value="Miss">Miss</option>
                      </select>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Othernames -->
              <div class="col-lg-6 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="othernames" 
                      autocomplete="OFF" 
                      placeholder="Names"
                      required="" 
                      value="<?=$fullname?>" 
                      class="form-control">               
                    </div>
                  </div>
                </div>
              </div>

              <!-- Date of birth -->
              <div class="col-lg-6 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Email Address</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <input type="email" 
                      name="email"
                      autocomplete="OFF" 
                      required=""
                      value="<?=$email?>" 
                      placeholder="Email Address" 
                      class="form-control">                  
                    </div>
                  </div>
                </div>
              </div>

              <!-- Gender -->
              <div class="col-lg-6 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Phone Number</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                      <input type="number" 
                      name="mobile"
                      autocomplete="OFF" 
                      required=""
                      value="<?=$mobile?>"
                      placeholder="Mobile Number" 
                      class="form-control">                         
                    </div>
                  </div>
                </div>
              </div>

              <!-- Class -->
              <div class="col-lg-4 mt-3">
                <div class="custom-fieldset-box">
                  <span class="custom-field-title">Select Role</span>
                  <div class="inner-cont">
                    <div class="input-wraps">
                     <select name="role" required="">
                       <option value="<?=$roles?>"><?=$dispRole?></option>
                       <option value="admin">Admin</option>
                       <option value="principal">Principal</option>
                       <option value="vice_principal">Vice Principal</option>
                       <option value="class_teacher">Class Teacher</option>
                       <option value="subject_teacher">Subject Teacher</option>
                     </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="" 
                      value="<?=$password?>" 
                      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"
                      value="<?=$password?>" 
                      class="form-control">                          
                    </div>
                  </div>
                </div>
              </div>

              <div class="col-lg-12">
                <div class="box-overall">
                  <span>Select Class</span>
                  <div class="class-box">
                    <?php
                    $fetchClass = "SELECT * FROM classes";
                    $classStmt = $pdo->prepare($fetchClass);
                    $classStmt->execute();
                    while ($classRow = $classStmt->fetch(PDO::FETCH_ASSOC)) {
                        $allClass = $classRow['className'];

                        if ($allClass == $class) {
                          $slec = 'checked';
                        }else{
                          $slec ='';
                        }
                    ?>
                    <label class="class-item">
                        <input type="radio" name="class" <?=$slec?> value="<?=$allClass?>">
                        <span><?=$allClass?></span>
                    </label>

                    <?php } ?>
                  </div>
                </div>
              </div>

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

      

    </div>
   
  </div>
</div>
<?php

// update user
if (isset($_POST['edit-btn'])) {
 
  $title      = isset($_POST['title']) ? trim($_POST['title']) : '';
  $email      = isset($_POST['email']) ? trim($_POST['email']) : '';
  $name       = isset($_POST['othernames']) ? trim($_POST['othernames']) : '';
  $mobile     = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
  $role       = isset($_POST['role']) ? trim($_POST['role']) : '';
  $Dpassword  = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
  $confirm    = isset($_POST['confirm']) ? trim($_POST['confirm']) : '';
  $class      = isset($_POST['class']) ? trim($_POST['class']) : '';

  // Defensive: make sure we have staffId
  if (empty($staffId)) {
    $_SESSION['message'] = 'Missing staff identifier.';
    $_SESSION['type'] = 'error';
    // stop processing
  } else {
    // Fetch current password from DB (so we can compare later)
    $pstmt = $pdo->prepare("SELECT password FROM staff WHERE staffId = ?");
    $pstmt->execute([$staffId]);
    $currentPasswordInDb = $pstmt->fetchColumn(); // may be false if not found

    // 1) Password confirmation
    if ($Dpassword !== $confirm) {
      $_SESSION['message'] = 'Password does not match';
      $_SESSION['type'] = 'error';
    } else {
      // 2) If role requires class, validate class is provided
      if ($role == 'class_teacher') {
        if (empty($class)) {
          // stop processing and show error (this was the cause of your "keep loading" issue)
          // You were setting error but continuing the script; we must stop here.
          $_SESSION['message'] = 'Please select a class for class teacher';
          $_SESSION['type'] = 'error';
        } else {
          // role = class_teacher and class not empty -> process class_teacher assignment
          $getto = "SELECT * FROM class_teacher WHERE staffId = ?";
          $gettPdo = $pdo->prepare($getto);
          $gettPdo->execute([$staffId]);
          $counter = $gettPdo->rowCount();

          if ($counter > 0) {
            // update existing assignment
            $sql_update = "UPDATE class_teacher SET class = ? WHERE staffId = ?";
            $sql_pdo = $pdo->prepare($sql_update);
            $sql_pdo->execute([$class, $staffId]);
          } else {
            // ensure class not already assigned to some other staff
            $valdStmt = "SELECT * FROM class_teacher WHERE staffId != ? AND class = ?";
            $valdPdo = $pdo->prepare($valdStmt);
            $valdPdo->execute([$staffId, $class]);

            if ($valdPdo->rowCount() > 0) {
              $_SESSION['message'] = 'Class is already assigned to another teacher';
              $_SESSION['type'] = 'error';
            } else {
              // insert new assignment
              $sql_insrt = "INSERT INTO class_teacher(staffId, class) VALUES(?, ?)";
              $sql_insrt_pdo = $pdo->prepare($sql_insrt);
              $sql_insrt_pdo->execute([$staffId, $class]);
            }
          }
        } // end else class not empty
      } else {
        // role is NOT class_teacher -> remove any class_teacher rows for this staff
        $removeStaff = "DELETE FROM class_teacher WHERE staffId = ?";
        $remvStmt = $pdo->prepare($removeStaff);
        $remvStmt->execute([$staffId]);
      } // end role handling

      // Only proceed to update main staff table if no error set so far
      if (!isset($_SESSION['type']) || $_SESSION['type'] !== 'error') {

        // Decide password to save
        // If new password provided and it's different from stored (or stored empty), hash it.
        if ($Dpassword == $password) {
          $valPass = $password;
        }else{
          $valPass = password_hash($Dpassword, PASSWORD_DEFAULT);
        }

        // Update main staff record
        $updateStaff = "UPDATE staff SET email = ?, fullname = ?, phone_number = ?, roles = ?, title = ?, password = ? WHERE staffId = ?";
        $updateStmt = $pdo->prepare($updateStaff);
        $updateStmt->execute([$email, $name, $mobile, $role, $title, $valPass, $staffId]);

        $_SESSION['message'] = 'User Updated Successfully.';
        $_SESSION['type'] = 'success';
        ?>
        <script type="text/javascript">
          setTimeout("location.href='staff.php';", 2000);
        </script>
        <?php
      } // end update staff only when no error
    } // end password match else
  } // end staffId guard
}


?>

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

<script>
document.addEventListener("DOMContentLoaded", () => {
  const roleSelect = document.querySelector("select[name='role']");
  const boxOverall = document.querySelector(".box-overall");

  roleSelect.addEventListener("change", () => {
    if (roleSelect.value === "class_teacher") {
      boxOverall.style.display = "block"; // ✅ show when Class Teacher
    } else {
      boxOverall.style.display = "none";  // ✅ hide for others
    }
  });
});
</script>



<style type="text/css">

.class-box {
  display: flex;
  gap: 15px;
  overflow-x: auto;
  padding: 10px 0;
  scrollbar-width: thin;
}

.class-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  white-space: nowrap;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: all 0.2s ease;
}

.class-item:hover {
  background-color: #eef5ff;
  border-color: #5a9bff;
}

.class-item input[type="checkbox"] {
  accent-color: #007bff;
}

.class-item input[type="radio"] {
  accent-color: #007bff;
}

.box-overall {
  display: none; /* ✅ hidden initially */
  width: 100%;
  height: auto;
  border:1px solid #ccc;
  padding-left: 20px;
  padding-top: 10px;
  border-radius: 8px;
}


.box-overall span{
  font-weight: bold;
  color: #1E5F67;
  font-size: 15px;
}

.class-box{
  margin-top: 5px;
  width: 100%;
  height: 100px;
  display: flex;
  gap:25px;
  padding-bottom: 20px;
  overflow-x: auto;  
}
.sing-box{
  padding: 5px;
  border:1px solid #ccc;
  border-radius: 5px;
}
</style>
<?php include'includes/notification-alert-js.php';?>

