<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'message' => 'Metodo nao permitido.']);
    exit;
}

if (GOOGLE_SHEETS_WEBHOOK_URL === '') {
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => 'Webhook Google Sheets nao configurado.']);
    exit;
}

$rawBody = file_get_contents('php://input');
$input = json_decode($rawBody ?: '{}', true);
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'message' => 'Payload invalido.']);
    exit;
}

$lead = [
    'nome' => trim((string)($input['nome'] ?? '')),
    'empresa' => trim((string)($input['empresa'] ?? '')),
    'email' => trim((string)($input['email'] ?? '')),
    'telefone' => trim((string)($input['telefone'] ?? '')),
    'setor' => trim((string)($input['setor'] ?? '')),
    'aplicacao' => trim((string)($input['aplicacao'] ?? '')),
    'mensagem' => trim((string)($input['mensagem'] ?? '')),
    'timestamp' => trim((string)($input['timestamp'] ?? gmdate('c'))),
    'origem' => trim((string)($input['origem'] ?? 'LP Osmose Reversa')),
    'pagina' => trim((string)($input['pagina'] ?? '')),
];

if ($lead['nome'] === '' || $lead['empresa'] === '' || $lead['email'] === '' || $lead['telefone'] === '') {
    http_response_code(422);
    echo json_encode(['ok' => false, 'message' => 'Campos principais obrigatorios nao informados.']);
    exit;
}

$jsonPayload = json_encode($lead);
if ($jsonPayload === false) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => 'Falha ao montar payload.']);
    exit;
}

$ch = curl_init(GOOGLE_SHEETS_WEBHOOK_URL);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS => $jsonPayload,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 15,
]);

$responseBody = curl_exec($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($responseBody === false || $curlError !== '') {
    http_response_code(502);
    echo json_encode(['ok' => false, 'message' => 'Falha ao enviar para Google Sheets.']);
    exit;
}

if ($httpCode < 200 || $httpCode >= 300) {
    http_response_code(502);
    echo json_encode(['ok' => false, 'message' => 'Resposta invalida do Google Sheets.']);
    exit;
}

echo json_encode(['ok' => true]);

