<?php
require_once '../includes/db.php';
require_once '../includes/functions.php';

if (!isLoggedIn()) redirect('login.php');

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $old_pass = $_POST['old_password'];
  $new_pass = $_POST['new_password'];
  $confirm_pass = $_POST['confirm_password'];

  $stmt = $pdo->query("SELECT * FROM admin WHERE id = 1");
  $admin = $stmt->fetch(PDO::FETCH_ASSOC);

  if (!password_verify($old_pass, $admin['password'])) {
    $msg = "<div class='alert alert-danger'>Old password incorrect!</div>";
  } elseif ($new_pass !== $confirm_pass) {
    $msg = "<div class='alert alert-warning'>New password and confirm password do not match!</div>";
  } else {
    $hashed = password_hash($new_pass, PASSWORD_BCRYPT);
    $update = $pdo->prepare("UPDATE admin SET password=? WHERE id=1");
    $update->execute([$hashed]);
    $msg = "<div class='alert alert-success'>Password changed successfully!</div>";
  }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Change Password</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<?php include 'nav.php'; ?>
<div class="container mt-4">
  <h4>Change Password</h4>
  <?= $msg ?>
  <form method="POST">
    <label>Old Password</label>
    <input type="password" name="old_password" class="form-control mb-3" required>

    <label>New Password</label>
    <input type="password" name="new_password" class="form-control mb-3" required>

    <label>Confirm Password</label>
    <input type="password" name="confirm_password" class="form-control mb-3" required>

    <button class="btn btn-primary w-100">Update Password</button>
  </form>
</div>
</body>
</html>
