<?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);

$rand = rand(0,4);

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

$zaman = time();
$sonaktif = time()-16*60*60;

function randBot(){
	global $db;
	// OPTIMIZE: SELECT * yerine sadece user_id
	$bot_id = $db->query("SELECT user_id FROM kullanicilar WHERE user_bot = 1 ORDER BY RAND() LIMIT 1")->fetchColumn();
	return $bot_id;
}


$onesignalArr = array();
$bot_id = randBot();

// OPTIMIZE: SQL injection riski düzeltildi + sadece gerekli kolonlar
$userStmt = $db->prepare("SELECT user_id, user_onesignal FROM kullanicilar 
                          WHERE user_songiris >= ? AND user_bot = 0 AND user_cinsiyet = 'erkek' AND user_id != 663793");
$userStmt->execute([$sonaktif]);
$users = $userStmt->fetchAll(PDO::FETCH_ASSOC);

// OPTIMIZE: Bu bot'un daha önce ziyaret ettiği kullanıcıları toplu çek
$user_ids = array_column($users, 'user_id');
$existing_visits = [];

if(!empty($user_ids)) {
    $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
    $visitStmt = $db->prepare("SELECT u_to FROM ziyaretler WHERE u_from = ? AND u_to IN ($placeholders)");
    $visitStmt->execute(array_merge([$bot_id], $user_ids));
    $existing_visits = array_column($visitStmt->fetchAll(PDO::FETCH_ASSOC), 'u_to');
}

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

foreach($users as $row){
    // Özel kullanıcı kontrolü (663793)
    if ($row['user_id'] == 663793) {
        continue;
    }
    
    // Daha önce ziyaret edilmemişse
    if(!in_array($row['user_id'], $existing_visits)){
        $insertData[] = [$bot_id, $row['user_id'], $currentTime];
        
        if(strlen($row['user_onesignal'])==36){
            $onesignalArr[] = $row['user_onesignal'];
        }
    }
}

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

//print_r($onesignalArr);

$rand = rand(0,1);

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

// 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_ismi = explode(" ",$botBilgisi['user_fullname']);

$bildirim_icerik = "👀".$bot_ismi[0]." Profilinize Baktı👀";


      $heading = array(
            "en" => "👄1 Yeni Profil Ziyareçisi!👄"
        );
    
        $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'].'/hesabim.php?visitor=1' 
        );
    

    // 'url' => 'https://'.$_SERVER['SERVER_NAME'].'/mesajlar.php?id='.$bot['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
      //  $response = curl_exec($ch); BİLDİRİMİ DURDURDUM
        curl_close($ch);

        if ($response) {
            echo $response;
        }   
echo "<br><br>";

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

echo "<hr>";
echo "<h3>👀 Profil Ziyareti 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 Ziyaret</strong></td><td>{$totalVisits}</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($totalVisits > 0) {
    $perVisit = round($executionTime / $totalVisits, 4);
    echo "<tr><td><strong>⚡ Ziyaret Başına</strong></td><td>{$perVisit} saniye</td></tr>";
}
echo "</table>";
?>