<?php
// try{
// 	$db	= new PDO("mysql:host=localhost;dbname=cntapi_oto;charset=UTF8", "cntapi_oto", "123123asd");
// }catch(PDOException $err){
// 	//echo "err : " . $err->getMessage();
// 	die();
// }

try{
    $db = new PDO("mysql:host=localhost;dbname=cntapi_db;charset=utf8mb4", "cntapi_db", "1546237a");
}catch(PDOException $err){
    //echo "err : " . $err->getMessage();
    die();
}


$setting = $db->prepare("SELECT cron_time FROM settings WHERE id = ?");
$setting->execute([1]);
$settings = $setting->fetch(PDO::FETCH_ASSOC);

if(time()<$settings['cron_time']) die();

$rand = rand(4,8);

update_settings(time()+$rand*60);

$one_signal = array();

$bot = $db->prepare("SELECT user_id FROM sohbetler GROUP BY user_id ORDER BY id ASC");
$bot->execute();
$bots = array_column($bot->fetchAll(PDO::FETCH_ASSOC), 'user_id');


for($i = 0; $i<count($bots); $i++)
    $one_signal[$bots[$i]] = array();

$user = $db->prepare("SELECT user_id, user_onesignal FROM kullanicilar WHERE user_cinsiyet = ? AND user_songiris >= ?");
$user->execute(["erkek",time()-86400]);
$users = $user->fetchAll(PDO::FETCH_ASSOC);

/*
Mesajları Görme Amaçlı Silinebilir, Testlerde Çalıştırılabilir*/
 $message = $db->prepare("SELECT * FROM mesajlar WHERE alan_id = ?");
 $message->execute(["935638"]);
 $messages = $message->fetchAll(PDO::FETCH_ASSOC);

 echo $message->rowCount();

 foreach($messages as $m){
     echo $m['icerik'] . "<br />";
 }


foreach($users as $row){

   if($row['user_id']==935638);
    else if($row['user_id']==704748);
    else continue;

    $log = $db->prepare("SELECT * FROM sohbetlog WHERE user_id = ?");
    $log->execute([$row['user_id']]);
    $logs = $log->fetchAll(PDO::FETCH_ASSOC);

    // echo "<pre>";
    // print_r($logs);
    // echo "</pre>";

    $total_message = array_column($logs, 'sohbet_sira');

    if(array_sum($total_message)==get_all_bot_messages_count()) continue;


    if($log->rowCount()==0){
        insert_message_insert_log($row['user_id'], $bots[0], 1);
        add_one_signal($bots[0], $row['user_onesignal']);
        continue;
    }

    if(end($logs)['sohbet_sira']==1 && answered_message_count($row['user_id'], end($logs)['bot_id'])<1){
        insert_message_update_log_order($row['user_id'], end($logs)['bot_id'], 2);
        add_one_signal(end($logs)['bot_id'], $row['user_onesignal']);
        continue;
    }

    if(count($logs)==1){
        insert_message_insert_log($row['user_id'], $bots[1], 1);
        add_one_signal($bots[1], $row['user_onesignal']);
        continue;
    }


    if(end($logs)['sohbet_sira']==2 || count($logs)==count($bots)){
    	$last_bot = end($logs)['bot_id'];
        foreach($logs as $k => $v){
            if($v['sohbet_sira']>=get_bot_messages_count($v['bot_id']) 
                || answered_message_count($row['user_id'], $v['bot_id'])>0)
                unset($logs[$k]);
        }
        sort($logs);

        // print_r($logs);

        if(count($logs)>0){
	       	for($i = 0; $i<count($logs); $i++){
	            if($i==count($logs)-1){
	                insert_message_update_log_order($row['user_id'], $logs[$i]['bot_id'], $logs[$i]['sohbet_sira']+1);
	                add_one_signal($logs[$i]['bot_id'], $row['user_onesignal']);
	                break;
	            }

	            $diff = $logs[$i]['sohbet_sira']-$logs[$i+1]['sohbet_sira'];
	            
	            if($diff==0 || $diff==1 || $diff==-1){
	                insert_message_update_log_order($row['user_id'], $logs[$i]['bot_id'], $logs[$i]['sohbet_sira']+1);
	                add_one_signal($logs[$i]['bot_id'], $row['user_onesignal']);
	                break;
	            }
	        }
        }else{
        	if(isset($bots[array_search($last_bot, $bots)+1])){
                echo "çalıştı";
		        insert_message_insert_log($row['user_id'], $bots[array_search($last_bot, $bots)+1], 1);
		        add_one_signal($bots[array_search($last_bot, $bots)+1], $row['user_onesignal']);
			}
        }

 
    }else if(count($logs)<count($bots)){
        insert_message_insert_log($row['user_id'], $bots[array_search(end($logs)['bot_id'], $bots)+1], 1);
        add_one_signal($bots[array_search(end($logs)['bot_id'], $bots)+1], $row['user_onesignal']);
    }
}

foreach($one_signal as $k => $v){
    //Burasını Sizin Düzenlemeniz Gerekmektedir
    //Bot Kullanıcı Adı $k
    //Kullanıcılar $v dizisi
    /*echo "Bot Kullanıcı : " . $k;
    for($i = 0; $i<count($v); $i++)
        echo "Kullanıcı Id : " . $v[$i] . "<br />";

    echo "<br /><br />";*/


    $select = $db->prepare("SELECT user_fullname, user_picture FROM kullanicilar WHERE user_id = ?");
    $select->execute([$k]);
    $detail = $select->fetch(PDO::FETCH_ASSOC);


    $bot_resim = "https://".$_SERVER['SERVER_NAME']."/".$detail['user_picture'];

      $content = array(
            "en" => "💌 ".$detail['user_fullname']." size mesaj gönderdi."
        );
    
        $heading = array(
            "en" => "🔷Yeni Mesaj Geldi!🔷"
        );
    
        $fields = array(
            'app_id' => "69302624-ee42-4571-9f00-38d6f1248d5d",
            'include_player_ids' => $v, 
            'data' => array("foo" => "bar"),
            'contents' => $content,
            'headings' => $heading,
            '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);

echo $response;   
echo "<br><br>";     

$jsonObj = json_decode($response, true);

$iletimSayi = $jsonObj['recipients'];


}

function get_bot_message($bot, $number){
    global $db;

    $select = $db->prepare("SELECT * FROM sohbetler WHERE user_id = ? AND sohbet_sira = ?");
    $select->execute([$bot, $number]);

    return $select->fetch(PDO::FETCH_ASSOC);
}

function get_bot_messages_count($bot){
    global $db;

    $select = $db->prepare("SELECT id FROM sohbetler WHERE user_id = ?");
    $select->execute([$bot]);

    return $select->rowCount();
}

function get_all_bot_messages_count(){
    global $db;

    $select = $db->prepare("SELECT id FROM sohbetler");
    $select->execute();

    return $select->rowCount();
}

function answered_message_count($user, $bot){
    global $db;

    $select = $db->prepare("SELECT id FROM mesajlar WHERE gonderen_id = ? AND alan_id = ?");
    $select->execute([$user, $bot]);

    return $select->rowCount();
}

function insert_message_update_log_order($user, $bot, $number){
    global $db;

    $db->beginTransaction();
    $bot_message = get_bot_message($bot, $number);

    $insert_message = $db->prepare("INSERT INTO mesajlar (gonderen_id, alan_id, icerik, ip, zaman, okundu) values(?, ?, ?, ?, ?, ?)");
    $insert_message->execute([
        $bot_message['user_id'],
        $user,
        $bot_message['icerik'],
        "127.0.0.1",
        time(),
        0
    ]);

    $update_log = $db->prepare("UPDATE sohbetlog SET sohbet_sira = ? WHERE user_id = ? AND bot_id = ?");
    $update_log->execute([
        $bot_message['sohbet_sira'],
        $user, 
        $bot_message['user_id']
    ]);


    if($insert_message->rowCount()>0 && $update_log->rowCount()>0) $db->commit();
    else $db->rollBack();
}

function insert_message_insert_log($user, $bot, $number){
    global $db;

    $db->beginTransaction();
    $bot_message = get_bot_message($bot, $number);

    $insert_first_message = $db->prepare("INSERT INTO mesajlar (gonderen_id, alan_id, icerik, ip, zaman, okundu) values(?, ?, ?, ?, ?, ?)");
    $insert_first_message->execute([
        $bot_message['user_id'],
        $user,
        $bot_message['icerik'],
        "127.0.0.1",
        time(),
        0
    ]);

    $insert_first_message_log = $db->prepare("INSERT INTO sohbetlog (user_id, bot_id, sohbet_sira) values(?, ?, ?)");
    $insert_first_message_log->execute([
        $user, 
        $bot_message['user_id'],
        $bot_message['sohbet_sira']
    ]);


    if($insert_first_message->rowCount()>0 && $insert_first_message_log->rowCount()>0) $db->commit();
    else $db->rollBack();
}

function add_one_signal($bot, $user){
    global $one_signal;

    if(!in_array($user, $one_signal[$bot]) && strlen($user)==36) array_push($one_signal[$bot], $user);
}

function update_settings($time){
    global $db;

    $update_settings = $db->prepare("UPDATE settings SET cron_time = ? WHERE id = ?");
    $update_settings->execute([$time, 1]);
}


