<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

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

// Sanitize input values
$name = trim($data['name']);
$email = trim($data['email']);
$source = trim($data['source'] ?? "Unknown");
$referrer = trim($data['ref']);
$share_code = trim($data['code']);

if (empty($share_code)) {
    error_log("❌ Share code is missing from request.");
    echo json_encode(["error" => "Missing share code."]);
    exit;
}

// Fetch the referring user's ID
$stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$stmt->execute([$referrer]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    error_log("❌ Referrer not found: $referrer");
    echo json_encode(["error" => "Referrer not found."]);
    exit;
}

$user_id = $user['id'];
error_log("✅ Referrer ID found: $user_id");

// Fetch page_id from lead_capture_pages using share_code
$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("❌ ERROR: No Lead Capture Page found for share_code: " . var_export($share_code, true));
    echo json_encode(["error" => "Invalid share code. Please check if the lead capture page exists."]);
    exit;
}

$page_id = $page['id'];
error_log("✅ Found Lead Capture Page ID: $page_id");

// Check if lead already exists
$checkStmt = $pdo->prepare("SELECT id FROM leads WHERE email = ? AND page_id = ?");
$checkStmt->execute([$email, $page_id]);
$existingLead = $checkStmt->fetch(PDO::FETCH_ASSOC);

if ($existingLead) {
    error_log("⚠️ Duplicate lead detected: $email for page_id $page_id.");
    echo json_encode(["error" => "Lead already exists."]);
    exit;
}

// Insert new lead
try {
    $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 successfully.");
    echo json_encode(["success" => "Lead stored successfully."]);
} catch (PDOException $e) {
    error_log("❌ Database error: " . $e->getMessage());
    echo json_encode(["error" => "Database error: " . $e->getMessage()]);
}


// ✅ Fetch the referrer's email & name
$stmt = $pdo->prepare("SELECT first_name, email FROM users WHERE id = ? LIMIT 1");
$stmt->execute([$user_id]);
$referrerData = $stmt->fetch(PDO::FETCH_ASSOC);

if ($referrerData) {
    $referrerEmail = $referrerData['email'];
    $referrerName = $referrerData['first_name'];

    // ✅ Include send-email.php
    require_once 'send-email.php';

    // ✅ Send Lead Notification Email
    sendLeadNotificationEmail($referrerEmail, $referrerName, $name);
    
    error_log("📧 Lead notification email sent to: $referrerEmail");
}

?>