<?php
require_once __DIR__ . '/config/config.php';
if (!is_logged_in()) redirect('login.php');

$u = current_user();
$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current = $_POST['current_password'] ?? '';
    $new = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
    $stmt->execute([$u['id']]);
    $hash = $stmt->fetchColumn();

    if (!password_verify($current, $hash) && $current !== $hash) {
        $error = 'Current password is incorrect.';
    } elseif (strlen($new) < 6) {
        $error = 'New password must be at least 6 characters.';
    } elseif ($new !== $confirm) {
        $error = 'New password and confirmation do not match.';
    } else {
        $newHash = password_hash($new, PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE users SET password = ?, must_change_password = 0 WHERE id = ?")
            ->execute([$newHash, $u['id']]);
        $_SESSION['user']['must_change_password'] = 0;
        $success = 'Password updated successfully.';
    }
}

$pageTitle = 'Change Password';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-1">Change Password</h1>
<p class="text-slate-500 mb-6 text-sm">
  <?= !empty($u['must_change_password']) ? 'You must change your password before continuing.' : 'Update your account password.' ?>
</p>

<div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 max-w-md">
  <?php if ($error): ?><div class="mb-4 bg-red-50 border border-red-200 text-red-700 text-sm px-4 py-2.5 rounded-lg"><?= e($error) ?></div><?php endif; ?>
  <?php if ($success): ?><div class="mb-4 bg-emerald-50 border border-emerald-200 text-emerald-700 text-sm px-4 py-2.5 rounded-lg"><?= e($success) ?></div><?php endif; ?>
  <form method="POST" class="space-y-4">
    <div>
      <label class="block text-sm font-medium mb-1">Current Password</label>
      <input type="password" name="current_password" required class="w-full border border-slate-300 rounded-lg px-3 py-2">
    </div>
    <div>
      <label class="block text-sm font-medium mb-1">New Password</label>
      <input type="password" name="new_password" required class="w-full border border-slate-300 rounded-lg px-3 py-2">
    </div>
    <div>
      <label class="block text-sm font-medium mb-1">Confirm New Password</label>
      <input type="password" name="confirm_password" required class="w-full border border-slate-300 rounded-lg px-3 py-2">
    </div>
    <button class="bg-blue-700 hover:bg-blue-800 text-white font-medium px-5 py-2.5 rounded-lg">Update Password</button>
  </form>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
