<?php
/**
 * Nesvra Ecosystem — Strategy Call Lead Processor 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;
}

// Support both JSON payload and FormData
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$name        = trim($input['name'] ?? $input['s1name'] ?? '');
$email       = trim($input['email'] ?? $input['s1email'] ?? '');
$phone       = trim($input['phone'] ?? $input['s1phone'] ?? '');
$company     = trim($input['company'] ?? $input['s1company'] ?? '');
$country     = trim($input['country'] ?? $input['s1country'] ?? 'United States');
$interests   = $input['interests'] ?? [];
$subject     = trim($input['subject'] ?? '');
$product     = trim($input['product'] ?? '');
$plan        = trim($input['plan'] ?? '');
$timeline    = trim($input['timeline'] ?? 'Ready to start immediately');
$budget      = trim($input['budget'] ?? '$10k – $25k');
$meetMethod  = trim($input['meeting_platform'] ?? 'Google Meet');
$prefDate    = trim($input['preferred_date'] ?? date('Y-m-d', strtotime('+2 days')));
$prefTime    = trim($input['preferred_time'] ?? '02:00 PM');
$timezone    = trim($input['timezone'] ?? 'EST (UTC-5)');
$description = trim($input['description'] ?? '');

if (empty($name) || empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Please provide a valid full name and email address.'
    ]);
    exit;
}

$leadId = 'STRAT-' . strtoupper(substr(bin2hex(random_bytes(4)), 0, 8));
$leadData = [
    'id'               => $leadId,
    'created_at'       => date('c'),
    'name'             => $name,
    'email'            => $email,
    'phone'            => $phone,
    'company'          => $company,
    'country'          => $country,
    'subject'          => $subject,
    'product'          => $product,
    'plan'             => $plan,
    'interests'        => is_array($interests) ? $interests : [$interests],
    'timeline'         => $timeline,
    'budget'           => $budget,
    'meeting_platform' => $meetMethod,
    'preferred_date'   => $prefDate,
    'preferred_time'   => $prefTime,
    'timezone'         => $timezone,
    'description'      => $description,
    'status'           => 'confirmed',
    'ip_address'       => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
];

$dataFile = __DIR__ . '/../data/strategy_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);

// Keep maximum 500 records
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,
    'lead_id'    => $leadId,
    'first_name' => explode(' ', $name)[0],
    'date'       => $prefDate,
    'time'       => $prefTime,
    'timezone'   => $timezone,
    'platform'   => $meetMethod,
    'message'    => 'Strategy call booked successfully.'
]);
