<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';

apply_cors();

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

$user = require_user();
$input = get_json_input();
require_fields($input, ['current_password', 'new_password']);

if (strlen($input['new_password']) < 8) {
    send_error('New password must be at least 8 characters.', 422);
}

$pdo = getDbConnection();
$row = $pdo->prepare('SELECT password_hash FROM users WHERE id = :id');
$row->execute([':id' => $user['id']]);
$hashRow = $row->fetch();

if (!$hashRow || !password_verify($input['current_password'], $hashRow['password_hash'])) {
    send_error('Current password is incorrect.', 401);
}

$newHash = password_hash($input['new_password'], PASSWORD_DEFAULT);
$upd = $pdo->prepare('UPDATE users SET password_hash = :hash WHERE id = :id');
$upd->execute([':hash' => $newHash, ':id' => $user['id']]);

send_success(null, 'Password updated.');
