<?php
/**
 * Общая библиотека рассылки заявок (центр заявок).
 * Привязки клиентов: /opt/leads-center/clients.json
 * Секреты: /etc/quiz-secrets/{max,telegram,email}.env
 */

const CLIENTS_FILE = '/opt/leads-center/clients.json';

function clients_all(): array {
    return json_decode(@file_get_contents(CLIENTS_FILE) ?: '{}', true) ?: [];
}

function clients_save(array $clients): void {
    @file_put_contents(CLIENTS_FILE, json_encode($clients, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
}

/** Привязка клиента по коду.
 *  Если клиент не найден или канал не привязан — НЕ слать в чужие группы.
 *  Fallback: только Telegram владельцу (админу), MAX/почта — только при явной привязке. */
function resolve_client(?string $code): array {
    $clients = clients_all();
    if ($code) {
        $c = strtoupper(trim($code));
        if (isset($clients[$c])) {
            $row = $clients[$c];
            return [
                'code'  => $c,
                'name'  => $row['name'] ?? $c,
                'tg'    => $row['tg'] ?? null,
                'max'   => $row['max'] ?? null,
                'email' => $row['email'] ?? null,
            ];
        }
    }
    return [
        'code'  => $code ?: 'DEFAULT',
        'name'  => 'default',
        'tg'    => secret('telegram.env', 'TELEGRAM_ALLOWED_USERS'), // админ (владелец сервиса)
        'max'   => null,   // без привязки — в MAX НЕ шлём
        'email' => null,   // без привязки — на почту НЕ шлём
    ];
}

function secret(string $file, string $key): ?string {
    $lines = @file('/etc/quiz-secrets/' . $file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ((array)$lines as $l) {
        if (strpos($l, $key . '=') === 0) { return trim(substr($l, strlen($key) + 1)); }
    }
    return null;
}

function http_post_json(string $url, string $json, array $headers = [], bool $verifySsl = true): array {
    $h = ['Content-Type: application/json', 'Content-Length: ' . strlen($json)];
    foreach ($headers as $v) { $h[] = $v; }
    $ssl = $verifySsl ? [] : ['verify_peer' => false, 'verify_peer_name' => false];
    $ctx = stream_context_create([
        'ssl'  => $ssl,
        'http' => ['method' => 'POST', 'header' => implode("\r\n", $h) . "\r\n",
                   'content' => $json, 'timeout' => 15, 'ignore_errors' => true, 'user_agent' => 'leads-center/1.0'],
    ]);
    $body = @file_get_contents($url, false, $ctx);
    $code = 0;
    if (isset($http_response_header[0]) && preg_match('#HTTP/\S+\s+(\d+)#', $http_response_header[0], $m)) { $code = (int)$m[1]; }
    return [$code, $body];
}

function send_max(string $text, $chatId): bool {
    $token = secret('max.env', 'MAX_BOT_TOKEN');
    if (!$token || !$chatId) { return false; }
    [$code] = http_post_json(
        'https://platform-api2.max.ru/messages?chat_id=' . urlencode($chatId),
        json_encode(['text' => $text], JSON_UNESCAPED_UNICODE),
        ['Authorization: ' . $token, 'Accept: application/json'],
        false
    );
    return $code >= 200 && $code < 300;
}

function send_telegram(string $text, $chatId): bool {
    // Доставка заявок — ботом «Лиды от Губтора» (тот же, что привязывает группы)
    $token = secret('link-bot.env', 'LINK_BOT_TOKEN');
    if (!$token) { $token = secret('telegram.env', 'TELEGRAM_BOT_TOKEN'); }
    if (!$token || !$chatId) { return false; }
    [$code] = http_post_json(
        'https://api.telegram.org/bot' . $token . '/sendMessage',
        json_encode(['chat_id' => $chatId, 'text' => $text], JSON_UNESCAPED_UNICODE)
    );
    return $code >= 200 && $code < 300;
}

function send_email(string $text, string $to): bool {
    if (!$to) { return false; }
    $from = secret('email.env', 'EMAIL_FROM') ?: 'no-reply@gubtor.ru';
    $subject = '🔔 Заявка с квиза — ' . date('d.m.Y H:i');
    $headers = 'From: ' . $from . "\r\n"
             . 'Content-Type: text/plain; charset=utf-8' . "\r\n"
             . 'MIME-Version: 1.0' . "\r\n";
    return @mail($to, $subject, $text, $headers);
}
