<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

golder_sales_require_post();
$master = golder_master_pdo();
golder_sales_rate_limit($master, 'portal_register', 10, 300);

$input = golder_portal_api_payload();
$fullName = trim((string)($input['full_name'] ?? ''));
$email = trim((string)($input['email'] ?? ''));
$phone = trim((string)($input['phone'] ?? ''));
$password = (string)($input['password'] ?? '');

$res = golder_portal_register($master, $fullName, $email, $phone, $password);
if (empty($res['ok'])) {
    golder_json_error(400, 'INVALID_REQUEST', (string)($res['message'] ?? 'Portal register failed.'));
}

$scheme = (!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off') ? 'https' : 'http';
$host = trim((string)($_SERVER['HTTP_HOST'] ?? 'localhost'));
$baseUrl = rtrim(golder_env('GOLDER_SALES_BASE_URL', $scheme . '://' . $host), '/');
$verifyUrl = $baseUrl . '/portal.php?verify_token=' . urlencode((string)($res['verification_token'] ?? ''));

$mail = golder_portal_send_verification_email($email, $fullName, $verifyUrl);

golder_json_response([
    'status' => 'ok',
    'message' => 'Portal account created. Please verify your email.',
    'email_sent' => !empty($mail['ok']),
    'email_error' => !empty($mail['ok']) ? null : (string)($mail['message'] ?? 'mail failed'),
]);








