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

apply_cors();

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

$admin = require_admin();
$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();
$stmt = $pdo->prepare('SELECT password_hash FROM users WHERE id = :id');
$stmt->execute([':id' => $admin['id']]);
$row = $stmt->fetch();

if (!$row || !password_verify($input['current_password'], $row['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' => $admin['id']]);

log_admin_action($admin['email'], 'ADMIN_CHANGE_PASSWORD', $admin['email'], 'Admin changed own password');

send_success(null, 'Password updated successfully.');
