<?php
declare(strict_types=1);

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

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

$raw = file_get_contents('php://input');
$payload = json_decode($raw, true);

if (!is_array($payload)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
    exit;
}

$type = trim((string)($payload['type'] ?? 'Website Inquiry'));
$data = $payload['data'] ?? [];
$page = trim((string)($payload['page'] ?? ''));
$source = trim((string)($payload['source'] ?? 'colorjetbd.com'));

if (!is_array($data)) {
    $data = [];
}

$lead = [
    'id' => 'CJLEAD-' . date('Ymd-His') . '-' . bin2hex(random_bytes(3)),
    'type' => mb_substr($type, 0, 80),
    'data' => $data,
    'page' => mb_substr($page, 0, 200),
    'source' => mb_substr($source, 0, 100),
    'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
    'user_agent' => mb_substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 250),
    'created_at' => date('c'),
];

$dir = __DIR__ . '/../private-data';
$file = $dir . '/leads.json';

if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
}

$fp = fopen($file, 'c+');
if (!$fp) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Unable to open lead store']);
    exit;
}

flock($fp, LOCK_EX);
$existing = stream_get_contents($fp);
$leads = json_decode($existing ?: '[]', true);
if (!is_array($leads)) {
    $leads = [];
}

array_unshift($leads, $lead);
$leads = array_slice($leads, 0, 2000);

ftruncate($fp, 0);
rewind($fp);
fwrite($fp, json_encode($leads, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
fflush($fp);
flock($fp, LOCK_UN);
fclose($fp);

echo json_encode(['ok' => true, 'lead_id' => $lead['id']]);
