<?php
/**
 * POST /api/auth/change_password.php
 * Body (JSON): { current_password, new_password }
 * Works for any logged-in account type. Requires the current password as
 * proof of identity, same as any normal "change password while logged in"
 * flow - separate from the email-link reset flow for a forgotten password.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
$userId = require_login();

$input = get_json_input();
$currentPassword = (string) ($input['current_password'] ?? '');
$newPassword = (string) ($input['new_password'] ?? '');

if ($currentPassword === '' || $newPassword === '') {
    send_error('Current and new password are both required.', 422);
}
if (strlen($newPassword) < 8) {
    send_error('New password must be at least 8 characters.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT password_hash FROM users WHERE id = ?');
$stmt->execute([$userId]);
$hash = $stmt->fetchColumn();

if (!$hash) {
    send_error('This account has no password set (signed up via social login) - nothing to change here yet.', 422);
}
if (!password_verify($currentPassword, $hash)) {
    send_error('Current password is incorrect.', 403);
}

$newHash = password_hash($newPassword, PASSWORD_BCRYPT);
$stmt = $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
$stmt->execute([$newHash, $userId]);

send_json(true, 'Password updated.');
