<?php

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/helpers.php';
require_once __DIR__ . '/../../middleware/auth.php';

if (getMethod() !== 'POST') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

global $pdo;
$user = requireAuth();
$input = getJsonInput();

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

if ($currentPassword === '' || $newPassword === '') {
    jsonResponse(false, 'Current password and new password are required', null, 422);
}

$stmt = $pdo->prepare('SELECT password FROM users WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $user['id']]);
$row = $stmt->fetch();

if (!$row || !password_verify($currentPassword, $row['password'])) {
    jsonResponse(false, 'Current password is incorrect', null, 401);
}

$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
$update = $pdo->prepare('UPDATE users SET password = :password, updated_at = NOW() WHERE id = :id');
$update->execute([
    'password' => $hashedPassword,
    'id' => $user['id'],
]);

jsonResponse(true, 'Password changed successfully');
