<?php
// POST /api/change-password

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendError('Method not allowed', 405);
}

$authPayload = $GLOBALS['auth_user'];
$input       = json_decode(file_get_contents('php://input'), true);
$oldPassword = trim($input['old_password'] ?? '');
$newPassword = trim($input['new_password'] ?? '');

if (!$oldPassword || !$newPassword) {
    sendError('old_password and new_password are required');
}

if (strlen($newPassword) < 6) {
    sendError('new_password must be at least 6 characters');
}

$db   = getDB();
$stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
$stmt->bind_param("i", $authPayload['user_id']);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user || !password_verify($oldPassword, $user['password'])) {
    $db->close();
    sendError('Current password is incorrect', 401);
}

$hashed = password_hash($newPassword, PASSWORD_DEFAULT);
$stmt   = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
$stmt->bind_param("si", $hashed, $authPayload['user_id']);
$stmt->execute();
$stmt->close();
$db->close();

sendSuccess([], 'Password changed successfully');
