<?php
session_start();
include('includes/config.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
// Check if staff is logged in
if (strlen($_SESSION['staff_login']) == 0) {
  header('location:index.php');
  exit;
}

$msg = $error = '';

if (isset($_POST['change'])) {

  $currentpassword = $_POST['password'];  // raw entered password
  $newpasswordHash = password_hash($_POST['newpassword'], PASSWORD_DEFAULT);
  $staffid = $_SESSION['staffid'];

  // 1. Fetch current hashed password from DB
  $sql = "SELECT Password FROM tblstaff WHERE StaffId = :staffid LIMIT 1";
  $query = $dbh->prepare($sql);
  $query->bindParam(':staffid', $staffid, PDO::PARAM_STR);
  $query->execute();
  $result = $query->fetch(PDO::FETCH_OBJ);

  if ($result) {

    // 2. Verify current password
    if (password_verify($currentpassword, $result->Password)) {

      // 3. Update new hashed password
      $update = "UPDATE tblstaff SET Password = :newpassword WHERE StaffId = :staffid";
      $chngpwd = $dbh->prepare($update);
      $chngpwd->bindParam(':staffid', $staffid, PDO::PARAM_STR);
      $chngpwd->bindParam(':newpassword', $newpasswordHash, PDO::PARAM_STR);
      $chngpwd->execute();

      $msg = "Your password was successfully changed.";

    } else {
      $error = "Your current password is incorrect.";
    }

  } else {
    $error = "User not found.";
  }
}
?>

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

<head>
  <meta charset="UTF-8">
  <title>Staff Change Password | Library System</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">

  <!-- Bootstrap 4.6 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <style>
    .main-content {
      margin-left: 180px;
      margin-top: 50px;
      padding: 20px;
    }

    .square-card {
      background-color: #f8f9fa;
      border: 1px solid #dee2e6;
      border-radius: 6px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    }

    .header-line {
      font-size: 22px;
      font-weight: 600;
      color: #2258d5;
    }
  </style>
  <script>
    function valid() {
      if (document.chngpwd.newpassword.value !== document.chngpwd.confirmpassword.value) {
        alert("New Password and Confirm Password do not match!");
        document.chngpwd.confirmpassword.focus();
        return false;
      }
      return true;
    }
  </script>
</head>

<body>
  <div class="d-flex flex-column min-vh-100">
    <?php include('includes/header.php'); ?>

    <div class="main-content flex-grow-1">
      <div class="row mb-4">
        <div class="col-md-12 d-flex justify-content-between align-items-center">
          <h6 class="header-line" style="color:#0d6efd; font-size:20px;"><i class="fas fa-key mr-2"></i>CHANGE PASSWORD
          </h6>
        </div>
      </div>

      <div class="row justify-content-center">
        <div class="col-md-4">
          <div class="card square-card mb-4">
            <div class="card-header bg-secondary text-light">
              <i class="fas fa-lock mr-2"></i> Update Password
            </div>
            <div class="card-body">
              <?php if ($error): ?>
                <div class="alert alert-danger"><strong>ERROR:</strong> <?= htmlentities($error); ?></div>
              <?php elseif ($msg): ?>
                <div class="alert alert-success"><strong>SUCCESS:</strong> <?= htmlentities($msg); ?></div>
              <?php endif; ?>

              <form method="post" name="chngpwd" onsubmit="return valid();">
                <div class="form-group">
                  <label>Current Password</label>
                  <div class="input-group">
                    <input type="password" name="password" id="password" class="form-control" required
                      autocomplete="off">
                    <div class="input-group-append">
                      <span class="input-group-text toggle-password" data-target="password">
                        <i class="fas fa-eye"></i>
                      </span>
                    </div>
                  </div>
                </div>

                <div class="form-group">
                  <label>New Password</label>
                  <div class="input-group">
                    <input type="password" name="newpassword" id="newpassword" class="form-control" required
                      autocomplete="off">
                    <div class="input-group-append">
                      <span class="input-group-text toggle-password" data-target="newpassword">
                        <i class="fas fa-eye"></i>
                      </span>
                    </div>
                  </div>
                </div>

                <div class="form-group">
                  <label>Confirm New Password</label>
                  <div class="input-group">
                    <input type="password" name="confirmpassword" id="confirmpassword" class="form-control" required
                      autocomplete="off">
                    <div class="input-group-append">
                      <span class="input-group-text toggle-password" data-target="confirmpassword">
                        <i class="fas fa-eye"></i>
                      </span>
                    </div>
                  </div>
                </div>
                <div class="d-flex justify-content-end">
                  <button type="submit" name="change" class="btn btn-primary">
                    <i class="fas fa-save"></i> Change Password
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

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

  <!-- Scripts -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>
<script>
  document.querySelectorAll('.toggle-password').forEach(function (toggle) {
    toggle.addEventListener('click', function () {
      const input = document.getElementById(this.dataset.target);
      const icon = this.querySelector('i');

      if (input.type === "password") {
        input.type = "text";
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
      } else {
        input.type = "password";
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
      }
    });
  });
</script>