<?php
include '../../config.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Performans ölçümü
$startTime = microtime(true);

$sonaktif = time() - 16 * 60 * 60;
$rand = rand(0, 5);

if ($rand !== 0) {
    die();
}

$onesignalArr = [];
$bot_id = $db->query("SELECT user_id FROM kullanicilar WHERE user_bot = 1 ORDER BY RAND() LIMIT 1")->fetchColumn();

$query = $db->prepare("SELECT k.user_id, k.user_onesignal, b.zaman 
                       FROM kullanicilar k 
                       LEFT JOIN (SELECT begenilen_id, MAX(zaman) as zaman FROM begeniler GROUP BY begenilen_id) b 
                       ON k.user_id = b.begenilen_id
                       WHERE k.user_songiris >= ? 
                       AND k.user_bot = 0 
                       AND k.user_cinsiyet = 'erkek' 
                       AND k.user_id != 663793
                       AND (b.zaman IS NULL OR b.zaman < ?)");

$query->execute([$sonaktif, time()]);

// OPTIMIZE: Batch insert için verileri topla
$insertData = [];
$currentTime = time();

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    // Özel kullanıcı kontrolü (663793)
    if ($row['user_id'] == 663793) {
        continue;
    }
    
    if (preg_match('/^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$/i', $row['user_onesignal'])) {
        $insertData[] = [$bot_id, $row['user_id'], $currentTime];
        $onesignalArr[] = $row['user_onesignal'];
    }
}

// OPTIMIZE: Tüm beğenileri tek query ile ekle (batch insert)
if (!empty($insertData)) {
    $placeholders = [];
    $values = [];
    
    foreach ($insertData as $data) {
        $placeholders[] = "(?, ?, ?)";
        $values[] = $data[0]; // begenen_id
        $values[] = $data[1]; // begenilen_id
        $values[] = $data[2]; // zaman
    }
    
    $sql = "INSERT INTO begeniler (begenen_id, begenilen_id, zaman) VALUES " . implode(', ', $placeholders);
    $stmt = $db->prepare($sql);
    $stmt->execute($values);
}

if (!empty($onesignalArr)) {
    // OPTIMIZE: SQL injection riski düzeltildi + sadece gerekli kolonlar
    $botStmt = $db->prepare("SELECT user_id, user_fullname, user_picture FROM kullanicilar WHERE user_id = ?");
    $botStmt->execute([$bot_id]);
    $botBilgisi = $botStmt->fetch(PDO::FETCH_ASSOC);
    
    $bot_resim = "https://app.heysen.net/" . $botBilgisi['user_picture'];
    $bot_isim = $botBilgisi['user_fullname'];
    $bildirim_icerik = "🥰 " . $bot_isim . " sizi beğendi.";

    $heading = array(
        "en" => "❤️Yeni Beğeniniz Var!❤️"
    );

    $content = array(
        "en" => $bildirim_icerik
    );

    $fields = array(
        'app_id' => "ad1b405f-217b-47b5-b59b-770d801cb89b",
        'include_player_ids' => $onesignalArr,
        'data' => array("foo" => "bar"),
        'contents' => $content,
        'ttl' => 2700,
        'headings' => $heading,
        'priority' => 10,
        'large_icon' => $bot_resim,
        'url' => 'https://' . $_SERVER['SERVER_NAME'] . '/profil.php?id=' . $botBilgisi['user_id']
    );

    $fields = json_encode($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = null; // Değişkeni başta tanımla

    if (rand(0, 3) === 0) {
        $response = curl_exec($ch);
    }

    // $response = curl_exec($ch); BİLDİRİMİ KAPATTIM
    curl_close($ch);

    if ($response) {
        echo $response;
    }
    echo "<br><br>";
} else {
    echo "No users to send notifications to.<br><br>";
}

// Performans raporu
$endTime = microtime(true);
$executionTime = round($endTime - $startTime, 3);
$totalLikes = count($insertData ?? []);
$totalNotifications = count($onesignalArr);

echo "<hr>";
echo "<h3>❤️ Beğenme Sistemi - Performans Raporu</h3>";
echo "<table border='1' cellpadding='10' style='border-collapse: collapse;'>";
echo "<tr><td><strong>⏱️ Çalışma Süresi</strong></td><td><strong style='color: green;'>{$executionTime} saniye</strong></td></tr>";
echo "<tr><td><strong>❤️ Gönderilen Beğeni</strong></td><td>{$totalLikes}</td></tr>";
echo "<tr><td><strong>🔔 Gönderilen Bildirim</strong></td><td>{$totalNotifications}</td></tr>";
echo "<tr><td><strong>🤖 Bot ID</strong></td><td>{$bot_id}</td></tr>";
if($totalLikes > 0) {
    $perLike = round($executionTime / $totalLikes, 4);
    echo "<tr><td><strong>⚡ Beğeni Başına</strong></td><td>{$perLike} saniye</td></tr>";
}
echo "</table>";
?>
