<?php

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

include '../config.php';
$zaman = time();


function botSec(){ // json olarak herhangi bir botu çekiyoruz

	global $db;

	$query = $db->query("SELECT * FROM kullanicilar WHERE user_bot = 1 AND user_send = 0 ORDER BY RAND() LIMIT 1", PDO::FETCH_ASSOC);

	foreach ($query as $veri) {
		return $veri['user_id'];
	}

}

function botSecLike(){ // json olarak herhangi bir botu çekiyoruz

	global $db;

	$query = $db->query("SELECT * FROM kullanicilar WHERE user_bot = 1 AND user_like = 0 ORDER BY RAND() LIMIT 1", PDO::FETCH_ASSOC);

	foreach ($query as $veri) {
		return $veri['user_id'];
	}

}

function kullaniciCek(){ // array olarak onesignal_id alıyoruz

	global $db;

	$suan = time();
	$yirmidort = time()-172800;

	$query = $db->query("SELECT * FROM kullanicilar WHERE user_bot = 0 AND user_onay = 0 AND user_cinsiyet = 'erkek' AND user_songiris >= $yirmidort AND user_onesignal IS NOT NULL ORDER BY id DESC", PDO::FETCH_ASSOC);

	$userListArr = array();
	$useridArr = array();

	foreach ($query as $veri) {
		if(strlen($veri['user_onesignal'])==36){
		$userListArr[] = $veri['user_onesignal'];
		$useridArr[] = $veri['user_id'];
	}
	}
	return $userListArr;
	return $useridArr;

}


function idCek(){ // array olarak onesignal_id alıyoruz

	global $db;

	$suan = time();
	$yirmidort = time()-172800;


	$query = $db->query("SELECT * FROM kullanicilar WHERE user_bot = 0 AND user_onay = 0 AND user_cinsiyet = 'erkek' AND user_songiris >= $yirmidort AND user_onesignal IS NOT NULL ORDER BY id DESC", PDO::FETCH_ASSOC);

	$useridArr = array();

	foreach ($query as $veri) {
		if(strlen($veri['user_onesignal'])==36){
		$useridArr[] = $veri['user_id'];
	}
	}
	return $useridArr;

}

//$botGel = botSec();

// print_r(idCek());
// die();



if($_POST['type']=="bildhistory"){

	$query = $db->query("SELECT * FROM mesajlar WHERE ip = '127.0.0.1' GROUP BY zaman HAVING COUNT(*) > 20 ORDER BY id DESC LIMIT 50", PDO::FETCH_ASSOC);


	foreach ($query as $veri) {
		echo $veri['gonderen_id'];
		echo "<br>";

									echo '<option value="'.$veri['gonderen_id'].'">'.$veri['gonderen_id'].' | '.date('H:i',$veri['zaman']).' => '.$veri['icerik'].'</option>';

	}


}







if($_POST['type']=="message"){


if(!empty($_POST['message'])){





if($_POST['again']==1){
$userIdList = array();
$userList = array();
// neden cevap vermiyorsun botu basla

$zaman = time();
$onikisaat = time()-43200;



$botGel = $_POST['userid'];


$query = $db->query("SELECT * FROM mesajlar WHERE gonderen_id = $botGel", PDO::FETCH_ASSOC);


foreach ($query as $veri) {
	
//	echo $veri['alan_id'];
//	echo "<br>";

$alan_id = $veri['alan_id'];



	$varMi1 = $db->query("SELECT COUNT(*) FROM mesajlar WHERE gonderen_id = $botGel AND alan_id = $alan_id")->fetchColumn();
	$varMi2 = $db->query("SELECT COUNT(*) FROM mesajlar WHERE gonderen_id = $alan_id AND alan_id = $botGel")->fetchColumn();

// echo $varMi1;
// echo "<br>";
// echo $varMi2;
// echo "<br><br>";


if($varMi1 > 0 AND $varMi2 == 0){
	//echo "var gibi<br />";
$usRow = $db->query("SELECT * FROM kullanicilar WHERE user_id = '$alan_id'")->fetch(PDO::FETCH_ASSOC);
$userIdList[] = $usRow['user_id'];
$userList[] = $usRow['user_onesignal'];
}else{
	//echo "yok gibi<br />";
}


}


// neden cevap vermiyorsun botu bitir

}else{
$userIdList = idCek();
$botGel = botSec();
$userList = kullaniciCek();
}

// $mesaj = $_POST['message'];

$bot = $db->query("SELECT * FROM kullanicilar WHERE user_id='$botGel'")->fetch(PDO::FETCH_ASSOC);

$bot_isim = $bot['user_fullname'];
$bot_resim = "https://".$_SERVER['SERVER_NAME']."/".$bot['user_picture'];

$userIdList = array_unique($userIdList);
$userList = array_keys(array_flip($userList));


foreach ($userIdList as $veri) {


$mesaj = $_POST['message'];
$user1row = $db->query("SELECT * FROM kullanicilar WHERE user_id = '{$veri}'")->fetch(PDO::FETCH_ASSOC);

$yas = $user1row['user_yas'];
$sehir = $user1row['user_sehir'];
$isimver = explode(" ", $user1row['user_fullname']);
$isim2 = ucwords(strtolower($isimver[0]));
$isim = $isim2;

$find = ['{yas}','{sehir}','{isim}'];
$replace = compact('yas', 'sehir', 'isim');

$mesaj = str_replace($find, $replace, $mesaj);

	
			$query = $db->prepare("INSERT INTO mesajlar SET
			gonderen_id = ?,
			alan_id = ?,
			icerik = ?,
			ip = ?,
			zaman = ?
		");

		$insert = $query->execute(array(
		     $bot['user_id'], $veri, $mesaj, "127.0.0.1", $zaman
		));

}




        $content = array(
            "en" => "💌 ".$bot_isim." size mesaj gönderdi."
        );
    
        $heading = array(
            "en" => "🔷Yeni Mesaj Geldi!🔷"
        );
    
        $fields = array(
            'app_id' => "ad1b405f-217b-47b5-b59b-770d801cb89b",
            'include_player_ids' => $userList,
            'data' => array("foo" => "bar"),
            'contents' => $content,
            'headings' => $heading,
            'ttl' => 7200,
            'large_icon' => $bot_resim,
            'url' => 'https://'.$_SERVER['SERVER_NAME'].'/mesajlar.php'
        );
    

    // '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 = curl_exec($ch);
        curl_close($ch);
        




$jsonObj = json_decode($response, true);

$iletimSayi = $jsonObj['recipients'];

// $error_goster = $jsonObj['errors']['0'];

$zaman = time();

$query = $db->prepare("UPDATE kullanicilar SET
user_send = :yeni_send
WHERE user_id = :user_id");
$update = $query->execute(array(
     "yeni_send" => $zaman,
     "user_id" => $bot['user_id']
));






$ciktim = count($userList)." Kişiden {$iletimSayi} Tanesine Mesaj Gönderildi.";

  $array = array("result" => "1", "cevap" => $ciktim);
  echo json_encode($array); // başarılı üyelik

}else{
  $array = array("result" => "0", "cevap" => "Boş Mesaj Gönderilemez");
  echo json_encode($array); // başarılı üyelik
}

}elseif($_POST['type']=="like"){



$botGel = botSecLike();
$userList = kullaniciCek();
$userIdList = idCek();

$bot = $db->query("SELECT * FROM kullanicilar WHERE user_id='$botGel'")->fetch(PDO::FETCH_ASSOC);

$bot_isim = $bot['user_fullname'];
$bot_resim = "https://".$_SERVER['SERVER_NAME']."/".$bot['user_picture'];


foreach ($userIdList as $veri) {
	
			$query = $db->prepare("INSERT INTO begeniler SET
			begenen_id = ?,
			begenilen_id = ?,
			zaman = ?
		");

		$insert = $query->execute(array(
		     $bot['user_id'], $veri, $zaman
		));

}




        $content = array(
            "en" => "💌 ".$bot_isim." sizi beğendi."
        );
    
        $heading = array(
            "en" => "❤️Yeni Beğeniniz Var!❤️"
        );
    
        $fields = array(
            'app_id' => "ad1b405f-217b-47b5-b59b-770d801cb89b",
            'include_player_ids' => $userList,
            'data' => array("foo" => "bar"),
            'contents' => $content,
            'headings' => $heading,
            'ttl' => 7200,
            'large_icon' => $bot_resim,
            'url' => 'https://'.$_SERVER['SERVER_NAME'].'/profil.php?id='.$bot['user_id']
        );
    

    // '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 = curl_exec($ch);
        curl_close($ch);
        

$jsonObj = json_decode($response, true);

$iletimSayi = $jsonObj['recipients'];

// $error_goster = $jsonObj['errors']['0'];



$query = $db->prepare("UPDATE kullanicilar SET
user_like = :yeni_send
WHERE user_id = :user_id");
$update = $query->execute(array(
     "yeni_send" => 1,
     "user_id" => $bot['user_id']
));

$zaman = time();

$query = $db->prepare("UPDATE settings SET
like_time = :yeni_time
WHERE id = :m_id");
$update = $query->execute(array(
     "yeni_time" => $zaman,
     "m_id" => 1
));





$ciktim = count($userList)." Kişiden {$iletimSayi} Tanesine Beğeni Gönderildi.";

  $array = array("result" => "1", "cevap" => $ciktim);
  echo json_encode($array); // başarılı üyelik




}

?>