<?php
require_once __DIR__ . '/header.php';
require_login();

$user = current_user();
$msg  = '';
$err  = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_require();

    $old     = (string)($_POST['old_password'] ?? '');
    $new     = (string)($_POST['new_password'] ?? '');
    $confirm = (string)($_POST['confirm_password'] ?? '');

    if ($old === '' || $new === '' || $confirm === '') {
        $err = 'All fields are required.';
    } elseif ($new !== $confirm) {
        $err = 'New password and confirmation do not match.';
    } else {
        $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([$user['id']]);
        $dbUser = $stmt->fetch();

        if (!$dbUser || !password_verify($old, $dbUser['password_hash'])) {
            $err = 'Old password is incorrect.';
            audit_log($pdo, 'password_change_failed', ['reason' => 'bad_old']);
        } else {
            $issues = v_password_strong($new);
            if ($issues) {
                $err = 'New password: ' . implode(', ', $issues) . '.';
            } elseif (hash_equals($dbUser['password_hash'], password_hash($old, PASSWORD_DEFAULT)) || $new === $old) {
                $err = 'New password must be different from old password.';
            } else {
                $hash = password_hash($new, PASSWORD_DEFAULT);
                $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?')->execute([$hash, $user['id']]);
                csrf_rotate();
                audit_log($pdo, 'password_changed', []);
                $msg = 'Password updated successfully.';
            }
        }
    }
}
?>
<h2>Change Password</h2>

<?php if ($msg): ?><div class="alert alert-success"><?php echo h($msg); ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger"><?php echo h($err); ?></div><?php endif; ?>

<form method="post" style="max-width:420px;">
    <?php echo csrf_field(); ?>
    <div class="field mb-2">
        <label>Old Password</label>
        <input type="password" name="old_password" required autocomplete="current-password">
    </div>
    <div class="field mb-2">
        <label>New Password</label>
        <input type="password" name="new_password" required autocomplete="new-password">
        <small class="muted">Min <?php echo (int)osce_env('PASSWORD_MIN_LENGTH', 10); ?> chars, with upper, lower, and digit.</small>
    </div>
    <div class="field mb-2">
        <label>Confirm New Password</label>
        <input type="password" name="confirm_password" required autocomplete="new-password">
    </div>
    <button type="submit" class="btn btn-primary">Update Password</button>
</form>

<?php require __DIR__ . '/footer.php'; ?>
