<?php
session_start();
include('includes/config.php');
error_reporting(0);

if (strlen($_SESSION['alogin']) == 0) {
  header('location:index.php');
  exit;
}

$msg = $error = '';

if (isset($_POST['change'])) {
  $username = $_SESSION['alogin'];
  $currentPassword = $_POST['password'];
  $newPassword = $_POST['newpassword'];

  // Fetch stored hashed password
  $sql = "SELECT Password FROM admin WHERE UserName = :username";
  $query = $dbh->prepare($sql);
  $query->bindParam(':username', $username, PDO::PARAM_STR);
  $query->execute();
  $row = $query->fetch(PDO::FETCH_ASSOC);

  if ($row) {
    $storedPassword = $row['Password'];

    // Verify only hashed password
    if (password_verify($currentPassword, $storedPassword)) {

      // Hash new password securely
      $newHashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

      $update = "UPDATE admin SET Password = :newpassword WHERE UserName = :username";
      $stmt = $dbh->prepare($update);
      $stmt->bindParam(':username', $username, PDO::PARAM_STR);
      $stmt->bindParam(':newpassword', $newHashedPassword, PDO::PARAM_STR);
      $stmt->execute();

      $msg = "Your password was changed successfully.";
    } else {
      $error = "Your current password is incorrect.";
    }
  }
}


?>

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

<head>
  <meta charset="UTF-8">
  <title>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">
          <h5 class="header-line" style="color:#0d6efd; font-size:20px;"><i class="fas fa-key mr-2"></i>CHANGE PASSWORD
          </h5>
        </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 position-relative">
                  <label for="password">Current Password</label>
                  <input type="password" name="password" id="password" class="form-control pr-5" required
                    autocomplete="off">
                  <i class="fa-solid fa-eye-slash toggle-password" data-target="#password"
                    style="position:absolute; right:10px; top:38px; cursor:pointer; color:#666;"></i>
                </div>
                <div class="form-group position-relative">
                  <label for="newpassword">New Password</label>
                  <input type="password" name="newpassword" id="newpassword" class="form-control pr-5" required
                    autocomplete="off">
                  <i class="fa-solid fa-eye-slash toggle-password" data-target="#newpassword"
                    style="position:absolute; right:10px; top:38px; cursor:pointer; color:#666;"></i>
                </div>
                <div class="form-group position-relative">
                  <label for="confirmpassword">Confirm New Password</label>
                  <input type="password" name="confirmpassword" id="confirmpassword" class="form-control pr-5" required
                    autocomplete="off">
                  <i class="fa-solid fa-eye-slash toggle-password" data-target="#confirmpassword"
                    style="position:absolute; right:10px; top:38px; cursor:pointer; color:#666;"></i>
                </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>
  <script>
    $(document).ready(function () {

      // 🔹 Eye toggle feature (modern simple way)
      $(".toggle-password").on("click", function () {
        const input = $($(this).data("target"));
        const type = input.attr("type") === "password" ? "text" : "password";
        input.attr("type", type);
        $(this).toggleClass("fa-eye fa-eye-slash");
      });

    });
  </script>
</body>

</html>