<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

golder_sales_require_post();
$master = golder_master_pdo();
$user = golder_portal_api_require_login($master);
$userId = (int)($user['id'] ?? 0);
$senderName = trim((string)($user['full_name'] ?? $user['email'] ?? 'customer'));

$input = golder_portal_api_payload();
$type = strtolower(trim((string)($input['type'] ?? 'payment')));
$requestId = trim((string)($input['id'] ?? ''));
$message = trim((string)($input['message'] ?? ''));
if ($requestId === '' || $message === '') {
    golder_json_error(400, 'INVALID_REQUEST', 'id and message are required.');
}

if ($type === 'demo') {
    $demo = golder_demo_request_by_id($master, $requestId);
    if (!$demo || (int)($demo['portal_user_id'] ?? 0) !== $userId) {
        golder_json_error(404, 'NOT_FOUND', 'Demo request not found.');
    }
    golder_add_demo_request_message($master, $requestId, 'customer', $senderName, $message);
    golder_json_response(['status' => 'ok']);
}

if ($type === 'support') {
    $thread = golder_support_thread_by_id($master, $requestId);
    if (!$thread || (int)($thread['portal_user_id'] ?? 0) !== $userId) {
        golder_json_error(404, 'NOT_FOUND', 'Support thread not found.');
    }
    golder_add_support_thread_message($master, $requestId, 'customer', $senderName, $message);
    golder_json_response(['status' => 'ok']);
}

$st = $master->prepare(
    'SELECT id
     FROM payment_requests
     WHERE id = :id AND portal_user_id = :uid
     LIMIT 1'
);
$st->execute([':id' => $requestId, ':uid' => $userId]);
if (!$st->fetch()) {
    golder_json_error(404, 'NOT_FOUND', 'Payment request not found.');
}

$master->prepare(
    'INSERT INTO payment_request_messages (payment_request_id, sender_type, sender_name, message_text, created_at)
     VALUES (:id, :st, :sn, :msg, UTC_TIMESTAMP())'
)->execute([
    ':id' => $requestId,
    ':st' => 'customer',
    ':sn' => substr($senderName, 0, 120),
    ':msg' => $message,
]);

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


