<?php
/**
 * Nesvra Ecosystem — General Lead Capture API
 */
header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$formType = trim($input['form_type'] ?? 'general_lead');
$name     = trim($input['name'] ?? $input['fullname'] ?? '');
$email    = trim($input['email'] ?? '');
$phone    = trim($input['phone'] ?? '');
$company  = trim($input['company'] ?? '');
$platform = trim($input['platform'] ?? $input['product'] ?? '');
$notes    = trim($input['notes'] ?? $input['message'] ?? '');

$leadData = [
    'id'         => 'LEAD-' . strtoupper(substr(bin2hex(random_bytes(4)), 0, 8)),
    'created_at' => date('c'),
    'form_type'  => $formType,
    'name'       => $name,
    'email'      => $email,
    'phone'      => $phone,
    'company'    => $company,
    'platform'   => $platform,
    'notes'      => $notes,
    'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
];

$dataFile = __DIR__ . '/../data/leads.json';
$leads = [];

if (file_exists($dataFile)) {
    $existing = json_decode(file_get_contents($dataFile), true);
    if (is_array($existing)) {
        $leads = $existing;
    }
}

array_unshift($leads, $leadData);
if (count($leads) > 500) {
    $leads = array_slice($leads, 0, 500);
}

@file_put_contents($dataFile, json_encode($leads, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

echo json_encode([
    'success' => true,
    'message' => 'Lead received successfully.'
]);
