<?php
error_reporting(0);
ini_set('display_errors', 0);

// --- AYARLAR ---
$telegram_token = "8242539862:AAFWMB7Bo-M8sXwU8JZAYl4fjDh2vBsy0Pg"; 
$chat_ids = ["-1003583842274", "-5156659664"]; 

// --- META (FACEBOOK) CAPI AYARLARI ---
$pixel_id = "1293676979245075"; 
$access_token = "EAAUiQ9PmfNwBQuT6CV51DqZAnLauknrwuDf7YedZBztPGZCFJZA3yJDoQokq4z7Ek1f35NhZAIBmD4tcPNQQYb6W6EZAE70zDc6ZC1ZAz90aqYNwtqldXxwls8R2u10I8oHqwiEynloZChAnkIfbK6jOkxiekxBxWxj7LQf0g7irZAT9wxuvReAXZAK2EvBflEawHB8WgZDZD";

date_default_timezone_set('Europe/Istanbul');

// Gelen Veriyi Al
$input = file_get_contents('php://input');
$json_data = json_decode($input, true);
$data = $json_data ? $json_data : $_POST;

if ($data) {
    // 1. VERİ TEMİZLEME VE FORMATLAMA
    $raw_phone = isset($data['phone']) ? $data['phone'] : (isset($data['gsm']) ? $data['gsm'] : '');
    $phone_digits = preg_replace('/[^0-9]/', '', $raw_phone);
    $check_phone = substr($phone_digits, -10); // Son 10 hane (5xx...)
    
    // EspoCRM için uluslararası format (+90...)
    $formatted_phone = "+90" . $check_phone; 
    
    $name = isset($data['fname']) ? strip_tags($data['fname']) : 'İsimsiz';
    $surname = isset($data['lname']) ? strip_tags($data['lname']) : '';

    // Ad ve Soyad birleşimi
    $full_name = $surname ? $name . ' ' . $surname : $name;

    // --- 409 ÇAKIŞMASINI ÖNLEYİCİ İSİM DÜZENLEME ---
    // İsmin sonuna rastgele iki basamaklı sayı ekler: "Testullah Yıldırım (42)"
    // Bu, CRM kilitli olduğu için mükerrer hatasını aşmamızı sağlar.
    $unique_name = $full_name . " (" . rand(10, 99) . ")"; 

    $source = !empty($data['utm_source']) ? strip_tags($data['utm_source']) : 'Organik';
    $utm_medium = !empty($data['utm_medium']) ? strip_tags($data['utm_medium']) : '';
    $utm_campaign = !empty($data['utm_campaign']) ? strip_tags($data['utm_campaign']) : '';
    $utm_content = !empty($data['utm_content']) ? strip_tags($data['utm_content']) : '';
    $utm_term = !empty($data['utm_term']) ? strip_tags($data['utm_term']) : '';
    $fbclid = !empty($data['fbclid']) ? strip_tags($data['fbclid']) : '';

    // 2. MÜKERRER KONTROLÜ (DOSYA BAZLI - CRM'DEN ÖNCE BİZ ENGELLİYORUZ)
    $db_file = 'finans_registered_numbers.txt'; 
    if (file_exists($db_file)) {
        $existing_numbers = file($db_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (in_array($check_phone, $existing_numbers)) {
            header('Content-Type: application/json');
            echo json_encode(['status' => 'error', 'message' => 'Mükerrer!']);
            exit;
        }
    }
    file_put_contents($db_file, $check_phone . PHP_EOL, FILE_APPEND | LOCK_EX);

    // 3. ESPOCRM GÖNDERİMİ (GARANTİ FORMAT)
    $espo_url = "https://crm.ulusalfinans.org/api/v1/Lead";
    $api_key  = "15bac204b6d7e873a8684636ca116b94";

    $espo_payload = json_encode([
        "lastName"        => $unique_name, 
        "phoneNumberData" => [
            [
                "phoneNumber" => $formatted_phone,
                "primary"     => true,
                "type"        => "Mobile",
                "optOut"      => false,
                "invalid"     => false
            ]
        ],
        "description" => $source . " | utm_medium: " . $utm_medium . " | utm_campaign: " . $utm_campaign . " | fbclid: " . $fbclid . " - AI",
        "status"      => "New"
    ]);

    $ch_espo = curl_init($espo_url);
    curl_setopt($ch_espo, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch_espo, CURLOPT_POST, true);
    curl_setopt($ch_espo, CURLOPT_POSTFIELDS, $espo_payload);
    curl_setopt($ch_espo, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json', 
        'X-Api-Key: ' . $api_key
    ]);
    
    $espo_res = curl_exec($ch_espo);
    $espo_code = curl_getinfo($ch_espo, CURLINFO_HTTP_CODE);
    curl_close($ch_espo);

    // 4. TELEGRAM MESAJI
    $text = "🔔 <b>AI</b>\n";
    $text .= "👤 <b>İsim:</b> $full_name\n";
    $text .= "📞 <b>Tel:</b> $formatted_phone\n";
    $text .= "🎯 <b>Kaynak:</b> $source\n";
    $text .= "⚙️ <b>CRM Durum:</b> $espo_code";

    foreach ($chat_ids as $chat_id) {
        $tg_url = "https://api.telegram.org/bot$telegram_token/sendMessage?chat_id=$chat_id&text=" . urlencode($text) . "&parse_mode=HTML";
        file_get_contents($tg_url);
    }

    // 5. FACEBOOK CAPI
    $capi_url = "https://graph.facebook.com/v18.0/$pixel_id/events?access_token=$access_token";

    // Build user_data для CAPI
    $user_data = ["ph" => hash('sha256', $check_phone)];

    // Email обработка для CAPI (если предоставлен)
    $email = isset($data['email']) ? strtolower(trim($data['email'])) : '';
    if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $user_data["em"] = hash('sha256', $email);
    }

    if (!empty($_SERVER['REMOTE_ADDR'])) {
        $user_data["client_ip_address"] = $_SERVER['REMOTE_ADDR'];
    }
    if (!empty($_SERVER['HTTP_USER_AGENT'])) {
        $user_data["client_user_agent"] = $_SERVER['HTTP_USER_AGENT'];
    }

    $capi_payload = json_encode([
        "data" => [[
            "event_name" => "Lead",
            "event_time" => time(),
            "action_source" => "website",
            "user_data" => $user_data
        ]]
    ]);
    $ch_fb = curl_init($capi_url);
    curl_setopt($ch_fb, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch_fb, CURLOPT_POST, true);
    curl_setopt($ch_fb, CURLOPT_POSTFIELDS, $capi_payload);
    curl_setopt($ch_fb, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_exec($ch_fb);
    curl_close($ch_fb);

    header('Content-Type: application/json');
    echo json_encode(['status' => 'success']);
    exit;
} else {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Geçersiz veri.']);
    exit;
}
?>