<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
echo "deniyorum<br>";
$rand = rand(0,1);
if($rand!=0) die();
echo "calistim<br>";
require_once '../../config.php';
require_once '../sehir.php';

$rows = get_messages_to_reply();
$scenarios = get_scenarios();
$user_ids = array_unique(array_column($rows, 'user_id'));
$scenario_ids = array_unique(array_column($scenarios, 'senaryo_id'));
$user_count  = array_count_values(array_column($rows, 'user_id'));
$select_count_f = get_grouped_scenarios();
$one_signal = array();
/*
echo "<pre>";
print_r(get_messages_to_reply());
echo "</pre>";*/

shuffle($rows);

foreach($rows as $row){
    //if($row['user_id']!=372881) continue;
    if(!in_array($row['user_id'], $user_ids)) continue;
    $insert_log = true;

    $user_logs = get_user_logs($row['user_id']);
    if(count($user_logs)>0){
        $log_bots_ids = array_unique(array_column($user_logs, 'bot_id'));

        if(in_array($row['bot_id'], $log_bots_ids)){
            $key = array_search($row['bot_id'], array_column($user_logs, 'bot_id'));
            $scenario_id =  $user_logs[$key]['senaryo_id'];
            $turn =  $user_logs[$key]['senaryo_sira']+1;

            $insert_log = false;
        }else{
            $log_scenarios_ids = array_unique(array_column($user_logs, 'senaryo_id'));

            $scenario_id =  get_next_scenario_id($log_scenarios_ids);
            $turn = 1;
            
            if(is_null($scenario_id))  continue;
        }
       
    }else{
        $key = array_rand($scenario_ids);
        $scenario_id =  $scenario_ids[$key];
        $turn = 1;
    }

    $message = get_one_scenario_message($scenario_id, $turn);

    update_readed($row['user_id'], $row['bot_id']);
    insert_message($row['user_id'], $row['bot_id'], $message);

    add_one_signal($row['bot_id'], $row['user_onesignal']);

    if($insert_log)
        insert_log($row['user_id'], $row['bot_id'], $scenario_id, $turn);
    else
        update_log($row['user_id'], $row['bot_id'], $scenario_id, $turn);

    if(get_check_scenario_end($row['user_id']))
        update_end($row['user_id']);

    $user_ids = array_diff($user_ids, [$row['user_id']]);
}

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 />";*/

    if(count($v)==0) continue;


    $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' => "ad1b405f-217b-47b5-b59b-770d801cb89b",
            'include_player_ids' => $v, 
            'data' => array("foo" => "bar"),
            'contents' => $content,
            'headings' => $heading,
            'large_icon' => $bot_resim,
            'ttl' => 1800,
            '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 add_one_signal($bot, $user){
    global $one_signal;

    if (!(array_key_exists($bot, $one_signal))) $one_signal[$bot] = array();

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


function insert_log($user_id, $bot_id, $scenario_id, $turn){
    global $db;
    
    $insert = $db->prepare("INSERT INTO jeton_senaryo_sifir_log (user_id, bot_id, senaryo_id, senaryo_sira) values(?, ?, ?, ?)");
    $insert->execute([$user_id, $bot_id, $scenario_id, $turn]);
}

function insert_message($user_id, $bot_id, $message){
    global $db;




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

    $isimver = explode(" ", $detail['user_fullname']);
    $isim2 = ucwords(strtolower($isimver[0]));
    $isimx = $isim2;

    $rando = rand(0,1);
    if($rando==1){
        $isimx = strtolower($isimx);
    }

    $sehirx = $detail['user_sehir'];
    $yasx = $detail['user_yas'];



    $degiskenler = ["{isim}", "{yas}","{sehirlimisin}", "{sehirdemi}","{sehirliyim}","{sehrinneresinden}"];
    $degisenler   = [$isimx,$yasx, sehirli($sehirx), sehirde($sehirx), sehirliyim($sehirx), sehrinneresinden($sehirx)];

    $yenimesaj = str_replace($degiskenler, $degisenler, $message);





    
    $insert = $db->prepare("INSERT INTO mesajlar (gonderen_id, alan_id, icerik, ip, zaman, okundu) values(?, ?, ?, ?, ?, ?)");
    $insert->execute([$bot_id, $user_id, $yenimesaj, "::2", time(), 0]);
}

function update_end($user_id){
    global $db;

    $update = $db->prepare("UPDATE bot_mesaj_bitenler SET durum = ? WHERE user_id = ? AND mesaj_tipi = ?");
    $update->execute([1, $user_id, 0]);
}

function update_log($user_id, $bot_id, $scenario_id, $turn){
    global $db;

    $update = $db->prepare("UPDATE jeton_senaryo_sifir_log SET senaryo_sira = ? WHERE user_id = ? AND bot_id = ? AND senaryo_id = ? ");
    $update->execute([$turn, $user_id, $bot_id, $scenario_id]);
}

function update_readed($user_id, $bot_id){
    global $db;

    $update = $db->prepare("UPDATE mesajlar SET okundu = ? WHERE gonderen_id = ? AND alan_id = ?");
    $update->execute([1, $user_id, $bot_id]);
}

function get_next_scenario_id($different){
    global $db;

 
    $select = $db->prepare("SELECT senaryo_id FROM jeton_senaryo_sifir WHERE senaryo_id NOT IN ( '" . implode( "', '" , $different ) . "' )");
    $select->execute();
    $select = array_unique($select->fetchAll(PDO::FETCH_COLUMN));

    shuffle($select);

    return count($select) > 0 ? $select[0] : NULL; 
}

function get_user_logs($user_id){
    global $db;

    $select = $db->prepare("SELECT * FROM jeton_senaryo_sifir_log WHERE user_id = ?");
    $select->execute([$user_id]);

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

function get_one_scenario_message($scenario_id, $turn){
    global $db;

    $select = $db->prepare("SELECT senaryo_mesaj FROM jeton_senaryo_sifir WHERE senaryo_id = ? AND senaryo_sira = ?");
    $select->execute([$scenario_id, $turn]);

    return $select->fetch(PDO::FETCH_ASSOC)['senaryo_mesaj'];
}

function get_one_scenario($scenario_id){
    global $db;

    $select = $db->prepare("SELECT * FROM jeton_senaryo_sifir WHERE senaryo_id = ?");
    $select->execute([$scenario_id]);

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

function get_scenarios(){
    global $db;

    $select = $db->prepare("SELECT * FROM jeton_senaryo_sifir");
    $select->execute();

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

function get_grouped_scenarios(){
    global $db;

    $select = $db->prepare("SELECT COUNT(id) as count, senaryo_id FROM jeton_senaryo_sifir GROUP BY senaryo_id");
    $select->execute();
    return $select->fetchAll(PDO::FETCH_ASSOC);
}

function get_check_scenario_end($user_id){
    global $db;
    global $select_count_f;

    $select = $db->prepare("SELECT
                        jeton_senaryo_sifir_log.senaryo_sira as senaryo_sira,
                        jeton_senaryo_sifir_log.senaryo_id  as senaryo_id
                        FROM jeton_senaryo_sifir_log
                        WHERE user_id = ?
                        GROUP BY jeton_senaryo_sifir_log.senaryo_id
                        ");
    $select->execute([$user_id]);
    $select_f = $select->fetchAll(PDO::FETCH_ASSOC);

    if(count($select_count_f)==$select->rowCount()){
        foreach($select_f as $r){
            $key = array_search($r['senaryo_id'], array_column($select_count_f, 'senaryo_id'));
            if($select_count_f[$key]['count']!=$r['senaryo_sira']) return false;
        }
        return true;
    }

    return false;
}


function get_messages_to_reply(){
    global $db;

    $select = $db->prepare("SELECT
                        bot_mesaj_bitenler.user_id AS user_id,
                        bot_mesaj_bitenler.mesaj_tipi AS mesaj_tipi,
                        kullanicilar.user_jeton AS jeton,
                        kullanicilar.user_deaktif AS deaktif,
                        kullanicilar.user_ban AS ban,
                        kullanicilar.user_onesignal AS user_onesignal,
                        mesajlar.icerik AS mesaj,
                        mesajlar.alan_id AS bot_id,
                        jeton_senaryo_sifir_log.senaryo_id AS senaryo_id,
                        jeton_senaryo_sifir_log.senaryo_sira AS senaryo_sira,
                        (SELECT 
                            COUNT(jeton_senaryo_sifir.senaryo_id) AS senaryo_sum
                            FROM jeton_senaryo_sifir
                            WHERE jeton_senaryo_sifir.senaryo_id = jeton_senaryo_sifir_log.senaryo_id
                        ) AS senaryo_sum
                        FROM bot_mesaj_bitenler
                        INNER JOIN kullanicilar ON bot_mesaj_bitenler.user_id = kullanicilar.user_id AND kullanicilar.user_deaktif = 0 AND kullanicilar.user_ban = 0
                        INNER JOIN mesajlar ON bot_mesaj_bitenler.user_id = mesajlar.gonderen_id
                        LEFT JOIN jeton_senaryo_sifir_log ON bot_mesaj_bitenler.user_id = jeton_senaryo_sifir_log.user_id AND  mesajlar.alan_id = jeton_senaryo_sifir_log.bot_id
                        WHERE mesaj_tipi = 0 AND durum = 0
                        GROUP BY bot_mesaj_bitenler.user_id, mesajlar.alan_id
                        HAVING
                            bot_id IN (SELECT user_id FROM kullanicilar WHERE user_bot = 1)
                            AND
                            jeton = 0 
                            AND
                            (jeton_senaryo_sifir_log.senaryo_sira < senaryo_sum OR COUNT(jeton_senaryo_sifir_log.senaryo_sira) = 0)");


    $select->execute();
    return $select->fetchAll(PDO::FETCH_ASSOC);
}
//321524