<?php
/**
 * MAX webhook: приём команд привязки групп к клиентам.
 * Команда в группе MAX: /link <КОД КЛИЕНТА>
 * (например: /link GREENLINE) — бот записывает chat_id группы в clients.json.
 */
error_reporting(E_ALL & ~E_DEPRECATED & ~E_WARNING);
header('Content-Type: application/json; charset=utf-8');

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

$raw = file_get_contents('php://input');
if ($raw === '' || $raw === false) {
    http_response_code(200);
    echo '{"ok":true}';
    exit;
}

$ev = json_decode($raw, true);
if (!is_array($ev)) { $ev = []; }

// Собираем текст и chat_id из события (формат MAX может различаться)
$text = '';
$chatId = null;

// Рекурсивный поиск
$stack = [$ev];
while ($stack) {
    $node = array_pop($stack);
    if (!is_array($node)) { continue; }
    foreach ($node as $k => $v) {
        if (is_array($v)) { $stack[] = $v; continue; }
        if (($k === 'chat_id' || $k === 'chatId') && $chatId === null && is_numeric($v)) { $chatId = (int)$v; continue; }
        if (!is_string($v)) { continue; }
        if ($k === 'text' && $text === '' && stripos($v, '/link') !== false) { $text = $v; }
    }
}

if ($text === '') { http_response_code(200); echo '{"ok":true,"note":"no command"}'; exit; }

// Парсим /link <КОД>
if (preg_match('#/link\s+([A-Za-z0-9_-]+)#i', $text, $m)) {
    $code = strtoupper($m[1]);
    if ($chatId === null) { http_response_code(200); echo '{"ok":false,"error":"no chat_id"}'; exit; }
    $clients = json_decode(@file_get_contents(CLIENTS_FILE) ?: '{}', true) ?: [];
    if (!isset($clients[$code])) {
        $clients[$code] = ['name' => $code, 'site' => null, 'tg' => null, 'max' => null, 'email' => null];
    }
    $clients[$code]['max'] = $chatId;
    @file_put_contents(CLIENTS_FILE, json_encode($clients, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
    // Подтверждение в группу
    $maxEnv = file('/etc/quiz-secrets/max.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $token = '';
    foreach ((array)$maxEnv as $l) { if (strpos($l, 'MAX_BOT_TOKEN=') === 0) { $token = trim(substr($l, 14)); } }
    if ($token !== '') {
        $msg = '✅ Группа привязана к клиенту ' . $code . '. Заявки будут приходить сюда.';
        $body = json_encode(['text' => $msg], JSON_UNESCAPED_UNICODE);
        $ctx = stream_context_create([
            'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
            'http' => ['method' => 'POST', 'timeout' => 15, 'ignore_errors' => true,
                       'header' => "Authorization: $token\r\nContent-Type: application/json\r\nContent-Length: " . strlen($body) . "\r\n",
                       'content' => $body],
        ]);
        @file_get_contents('https://platform-api2.max.ru/messages?chat_id=' . urlencode($chatId), false, $ctx);
    }
    echo '{"ok":true,"client":"' . $code . '","max_chat_id":' . $chatId . '}';
    exit;
}

http_response_code(200);
echo '{"ok":true,"note":"no /link command"}';
