<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

golder_sales_require_post();
$master = golder_master_pdo();
golder_portal_session_start();
$portalUserId = golder_portal_current_user_id();
if ($portalUserId <= 0) {
    golder_json_error(401, 'UNAUTHORIZED', 'Portal login is required.');
}

$portalUser = golder_portal_user_by_id($master, $portalUserId);
if (!$portalUser || trim((string)($portalUser['email_verified_at'] ?? '')) === '') {
    golder_json_error(403, 'FORBIDDEN', 'Portal account is not verified.');
}

golder_sales_rate_limit($master, 'sales_demo_request', 20, 60);
golder_ensure_payment_tables($master);

$payload = golder_sales_payload();
$fullName = trim((string)($payload['full_name'] ?? (string)($portalUser['full_name'] ?? '')));
$email = trim((string)($payload['email'] ?? (string)($portalUser['email'] ?? '')));
$phone = trim((string)($payload['phone'] ?? (string)($portalUser['phone'] ?? '')));
golder_sales_validate_contact($fullName, $email, $phone);

// web/api/demo-request.php içine eklenecek:
$check = $master->prepare("SELECT id FROM demo_requests WHERE portal_user_id = :uid OR email = :e LIMIT 1");
$check->execute([':uid' => $portalUserId, ':e' => $email]);
if ($check->fetch()) {
    golder_json_error(400, 'ALREADY_REQUESTED', 'Bu e-posta adresi ile zaten bir demo talebi oluşturulmuş.');
}

$res = golder_create_demo_request(
    $master,
    $portalUserId,
    $fullName,
    $email,
    $phone,
    'A-COMPLEX',
    1,
    1
);
if (empty($res['ok'])) {
    golder_json_error(409, 'STATE_CONFLICT', (string)($res['message'] ?? 'Demo request failed.'));
}

golder_json_response([
    'status' => 'ok',
    'request_id' => (string)($res['request_id'] ?? ''),
    'request_status' => 'pending',
    'message' => 'Demo request has been created and is pending admin approval.',
]);








