<?php
// POST /api/auth/change_password.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();

$currentPass = post('current_password', '');
$newPass     = post('new_password', '');
$confirmPass = post('confirm_password', '');

if (!$currentPass || !$newPass || !$confirmPass) apiError('All fields required.', 422);
if ($newPass !== $confirmPass) apiError('Passwords do not match.', 422);
if (strlen($newPass) < 8) apiError('Password must be at least 8 characters.', 422);

$stmt = $db->prepare("SELECT password_hash FROM users WHERE id = ?");
$stmt->execute([$user['id']]);
$row = $stmt->fetch();

if (!password_verify($currentPass, $row['password_hash'])) {
    apiError('Current password is incorrect.', 401);
}

$hash = password_hash($newPass, PASSWORD_BCRYPT, ['cost' => 12]);
$db->prepare("UPDATE users SET password_hash = ? WHERE id = ?")->execute([$hash, $user['id']]);

// Invalidate all other tokens
$db->prepare("DELETE FROM user_tokens WHERE user_id = ? AND token != ?")->execute([$user['id'], post('token')]);

apiSuccess([], 'Password changed successfully.');
