<?php
declare(strict_types=1);

// Satış API'sinden (public_html/api) -> APP Common'a (public_html/app/common) gidiş
require_once __DIR__ . '/../app/common/customer_provision.php';
require_once __DIR__ . '/../app/common/auth_middleware.php';
require_once __DIR__ . '/../app/common/portal_auth.php';
require_once __DIR__ . '/../app/common/demo_request_service.php';
require_once __DIR__ . '/../app/common/customer_cleanup.php';

function golder_sales_require_post(): void
{
    if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
        golder_json_error(405, 'METHOD_NOT_ALLOWED', 'Method not allowed.');
    }
}

function golder_sales_payload(): array
{
    return golder_read_json_body_strict();
}

function golder_sales_rate_limit(PDO $master, string $bucket, int $maxRequests, int $windowSeconds): void
{
    golder_apply_default_rate_limit($master, $bucket, $maxRequests, $windowSeconds);
}

function golder_sales_validate_contact(string $fullName, string $email, string $phone): void
{
    if ($fullName === '') {
        golder_json_error(400, 'INVALID_REQUEST', 'full_name is required.');
    }
    if ($email === '' && $phone === '') {
        golder_json_error(400, 'INVALID_REQUEST', 'email or phone is required.');
    }
    if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        golder_json_error(400, 'INVALID_REQUEST', 'email is invalid.');
    }
    if ($phone !== '' && preg_match('/^[0-9+()\\-\\s]{7,20}$/', $phone) !== 1) {
        golder_json_error(400, 'INVALID_REQUEST', 'phone is invalid.');
    }
}

function golder_sales_validate_plan_request(array $payload): array
{
    $planType = trim((string)($payload['plan_type'] ?? golder_default_plan_type()));
    $pcDevices = (int)($payload['pc_devices'] ?? 1);
    $webSessions = (int)($payload['web_sessions'] ?? 0);
    $durationKey = 'yearly';

    if (!in_array(golder_normalize_plan_type($planType), golder_plan_codes(), true)) {
        golder_json_error(400, 'INVALID_REQUEST', 'plan_type is invalid.');
    }
    if ($pcDevices < 1 || $pcDevices > 250) {
        golder_json_error(400, 'INVALID_REQUEST', 'pc_devices must be between 1 and 250.');
    }
    if ($webSessions < 0 || $webSessions > 250) {
        golder_json_error(400, 'INVALID_REQUEST', 'web_sessions must be between 0 and 250.');
    }

    return [
        'plan_type' => $planType,
        'pc_devices' => $pcDevices,
        'web_sessions' => $webSessions,
        'duration_key' => $durationKey,
        'normalized' => golder_normalize_plan_limits($planType, $pcDevices, $webSessions),
    ];
}








