<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'db.php';
header("Content-Type: application/json");

$data = json_decode(file_get_contents("php://input"), true);
error_log("📥 Received data: " . json_encode($data));

if (!$data || empty($data['name']) || empty($data['email']) || empty($data['ref']) || empty($data['code']) || empty($data['source'])) {
    error_log("❌ Missing required fields: " . json_encode($data));
    echo json_encode(["error" => "Missing required fields."]);
    exit;
}

$name = trim($data['name']);
$email = trim($data['email']);
$source = trim($data['source']);
$referrer = trim($data['ref']);
$share_code = trim($data['code']);

// Get referrer user ID
$stmt = $pdo->prepare("SELECT id, leadsleap_user_id, leadsleap_list_id, leadsleap_list_id_referrals, first_name, email FROM users WHERE user_id = ?");
$stmt->execute([$referrer]);
$referrerData = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$referrerData || empty($referrerData['leadsleap_user_id'])) {
    error_log("❌ Referrer not found or missing LeadsLeap ID.");
    echo json_encode(["error" => "Referrer not found or missing LeadsLeap ID."]);
    exit;
}

$user_id = $referrerData['id'];
$referrerEmail = $referrerData['email'];
$referrerName = $referrerData['first_name'];

$stmt = $pdo->prepare("SELECT id FROM lead_capture_pages WHERE share_code = ?");
$stmt->execute([$share_code]);
$page = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$page) {
    error_log("❌ Invalid share code: $share_code");
    echo json_encode(["error" => "Invalid share code."]);
    exit;
}

$page_id = $page['id'];

// Only insert into leads table for lead_capture
if ($source === "lead_capture") {
    $checkStmt = $pdo->prepare("SELECT id FROM leads WHERE email = ? AND page_id = ?");
    $checkStmt->execute([$email, $page_id]);
    if ($checkStmt->fetch()) {
        error_log("⚠️ Duplicate lead: $email for page_id $page_id.");
        echo json_encode(["error" => "Lead already exists."]);
        exit;
    }

    $stmt = $pdo->prepare("INSERT INTO leads (user_id, page_id, name, email, source, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
    $stmt->execute([$user_id, $page_id, $name, $email, $source]);
    error_log("✅ Lead stored in MySQL.");
}

// ✅ Send email notification
require_once 'send-email.php';
sendLeadNotificationEmail($referrerEmail, $referrerName, $name);
error_log("📧 Lead notification sent to $referrerEmail");

// ✅ Determine correct LeadsLeap List ID
$leadsleap_list_id = ($source === "user_registration") ? $referrerData['leadsleap_list_id_referrals'] : $referrerData['leadsleap_list_id'];

if (empty($leadsleap_list_id)) {
    error_log("❌ Missing LeadsLeap list ID for source: $source");
    echo json_encode(["error" => "Missing LeadsLeap list ID"]);
    exit;
}

// ✅ Prepare and send to LeadsLeap
$postData = [
    "n" . $leadsleap_list_id => $name,
    "e" . $leadsleap_list_id => $email,
    "lllid" => $leadsleap_list_id,
    "lluid" => $referrerData['leadsleap_user_id']
];

$ch = curl_init("https://www.sendsteed.com/subscribe/");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

error_log("📤 Sent to LeadsLeap. Response: $response");

echo json_encode(["success" => true, "leadsleap_response" => $response]);
exit;
