<?php
require_once __DIR__ . '/token.php';
require_once __DIR__ . '/v.php';

date_default_timezone_set('Europe/Istanbul');

$now = date('Y-m-d H:i:s');
$logFile = __DIR__ . '/log_webhook.txt';
file_put_contents($logFile, "\n\n📩 Webhook geldi @ $now\n", FILE_APPEND);

// === GET verilerini al ve logla
$data = $_GET;
file_put_contents($logFile, "[GET VERİSİ]:\n" . print_r($data, true), FILE_APPEND);

// === Parametreler
$sorumluAd = $data['sorumlu'] ?? 'Bilinmiyor';
$rawPhone  = $data['sorumlu_tel'] ?? '';
$hastaTel  = $data['hasta_tel'] ?? '-';
$formAdi   = $data['form'] ?? '-';
$promptId  = 'bitrix_webhook';

// === Telefon temizleme
$phone = preg_replace('/\D+/', '', $rawPhone);
if (empty($phone)) {
    file_put_contents($logFile, "❌ Telefon boş veya hatalı: $rawPhone → $phone\n", FILE_APPEND);
    exit("❌ Telefon numarası geçersiz.");
}


// === WHATSAPP mesajı (sorumluya gidecek)
$whatsappMessage = "👤 *New patient request assigned!*\n\n";
$whatsappMessage .= "🔸 *Responsible:* $sorumluAd\n";
$whatsappMessage .= "📞 *Patient:* +$hastaTel\n";
$whatsappMessage .= "📋 *Form:* $formAdi\n\n";
$whatsappMessage .= "ℹ️ *Please contact the patient as soon as possible.*";

// === TELEGRAM mesajı (yöneticiye log amaçlı)
$telegramMessage = "📥 <b>$sorumluAd için Yeni Lead Atandı.</b>\n"
    . "👤 <b>Sorumlu:</b> $sorumluAd\n"
    . "📞 <b>Hasta:</b> $hastaTel\n"
    . "📋 <b>Form:</b> $formAdi\n"
    . "⏰ <b>Zaman:</b> $now";

// === Gönderimler
sendWhatsappMessage($promptId, $sorumluAd, $phone, $whatsappMessage);
sendTelegramMessage($telegramMessage);

echo "✅ Webhook mesajı gönderildi.";

// === WhatsApp gönderici fonksiyonu
function sendWhatsappMessage($promptId, $recipientName, $phone, $message) {
    $config = require __DIR__ . '/token.php';

    $productId  = $config['whatsapp']['access_tokens'];
    $phoneId    = $config['whatsapp']['phone_number_id'];
    $maytapiKey = $config['whatsapp']['maytapi_key'];

    $url = "https://api.maytapi.com/api/{$productId}/{$phoneId}/sendMessage";

    $payload = [
        "to_number" => $phone,
        "type"      => "text",
        "message"   => $message,
        "typing"    => "typing",
        "duration"  => 2
    ];

    $headers = [
        "Accept: application/json",
        "Content-Type: application/json",
        "x-maytapi-key: $maytapiKey"
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => $headers
    ]);

    $response  = curl_exec($ch);
    $error     = curl_error($ch);
    $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    file_put_contents(__DIR__ . "/log_webhook.txt", "🌐 HTTP Kodu: $httpCode\n", FILE_APPEND);
    file_put_contents(__DIR__ . "/log_webhook.txt", "📨 API Yanıtı:\n$response\n", FILE_APPEND);
    file_put_contents(__DIR__ . "/log_webhook.txt", "⚠️ CURL Hata:\n$error\n", FILE_APPEND);

    if ($error || !$response) {
        file_put_contents(__DIR__ . "/log_webhook.txt", "❌ WhatsApp gönderim hatası!\n", FILE_APPEND);
    } else {
        file_put_contents(__DIR__ . "/log_webhook.txt", "✅ WhatsApp gönderildi → $phone\n", FILE_APPEND);
    }
}
