<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_admin_auth.php';

golder_require_method('POST');
$adminUser = golder_api_admin_auth();
$master = golder_master_pdo();
golder_ensure_payment_tables($master);

$input = golder_api_input();
$requestId = trim((string)($input['payment_request_id'] ?? ''));
$message = trim((string)($input['admin_message'] ?? 'Rejected'));
if ($requestId === '') {
    golder_json_response(['status' => 'error', 'message' => 'payment_request_id is required'], 400);
}

$st = $master->prepare('UPDATE payment_requests SET status = :st, admin_message = :msg, rejected_at = UTC_TIMESTAMP(), reviewed_by = :rb, updated_at = UTC_TIMESTAMP() WHERE id = :id AND status = :pending');
$st->execute([
    ':st' => 'rejected',
    ':msg' => $message,
    ':rb' => $adminUser,
    ':id' => $requestId,
    ':pending' => 'pending',
]);
if ((int)$st->rowCount() <= 0) {
    golder_json_response(['status' => 'error', 'message' => 'Payment request not found or not pending'], 404);
}

$master->prepare('INSERT INTO payment_request_messages (payment_request_id, sender_type, sender_name, message_text) VALUES (:id, :st, :sn, :msg)')->execute([
    ':id' => $requestId,
    ':st' => 'admin',
    ':sn' => $adminUser,
    ':msg' => $message,
]);

golder_json_response(['status' => 'ok']);


