<?php



//$rand = rand(0,1);
//if($rand!=0) die();

require_once '../../config.php';

require_once 'answers.php';
require_once '../sehir.php';


$rows = get_messages_to_reply();
$user_ids = array_unique(array_column($rows, 'user_id'));
$one_signal = array();
shuffle($rows);

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

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

        $answer_arr = [];

        $last_message = unique_string($row['mesaj']);
        $last_message_keyowrds = array_map('trim', explode(' ', $last_message));

        $limit = 1;//Değiştebilirsiniz, gönderilecek mesaj limitidir
        for($i=0; $i<count($last_message_keyowrds); $i++){
            if(!(count($answer_arr)<$limit)) break;
            $keyword = preg_replace('/[^A-Za-zıİüÜşŞöÖçÇğĞ\-]/', '', $last_message_keyowrds[$i]);

            if(in_array($keyword, $keywords)){
                $answer = find_answer($keyword);
                if($answer!=NULL) array_push($answer_arr, $answer);
            }
        }

        if(count($answer_arr)>0){
            $readed = 1;
            $answer_arr = edit_answers($row['user_id'], $answer_arr);
            insert_messages($row['user_id'], $row['bot_id'], $answer_arr);

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

            echo "çalıştı<br/>";
        }else{
            $readed = 1; // okundu
        }

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

        if($row['jeton']==0 && get_not_readed_messages($row['user_id'])==0)
            insert_finish($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,
            'priority' => 10,
            '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 find_answer($keyword){
    global $answers;

    if(array_key_exists($keyword, $answers)){
        $key = array_rand($answers[$keyword]);
        return $answers[$keyword][$key];
    }

   return NULL;
}

function unique_string($string) {
    $string = explode(' ', strtolower($string));
    $words = array_unique($string);
    return implode(' ', $words);
}

function edit_answers($user_id, $answers){
    $result = [];
    $user = get_user_data($user_id);

    for($i=0; $i<count($answers); $i++){
        $str = "";
        $string_exp = array_map('trim', explode('|@|', $answers[$i]));

        for($j=0; $j<count($string_exp); $j++){
            if(mb_substr($string_exp[$j], 0, 2) == '->'){
                $column = mb_substr($string_exp[$j], 2);
                $str .= " ". $user[$column];
            }else{
                $str .= " ". $string_exp[$j];
            }
        }

        if($str!="")
            array_push($result, trim($str));
        
    }
    return $result;
}

function insert_finish($user_id){
    global $db;

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

    if($select->rowCount()<1){
        $insert = $db->prepare("INSERT INTO bot_mesaj_bitenler (user_id, mesaj_tipi, durum) values(?, ?, ?)");
        $insert->execute([$user_id, 0, 0]);
    }
}

function insert_messages($user_id, $bot_id, $answer_arr){
    global $db;

    for($i=0; $i<count($answer_arr); $i++){






$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);
    }

    $mesaj  = $bot_message['icerik'];
    $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, $answer_arr[$i]);









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

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

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

function get_not_readed_messages($user_id){
    global $db;

    $select = $db->prepare("SELECT * FROM mesajlar WHERE gonderen_id = ? AND alan_id IN (SELECT user_id FROM kullanicilar WHERE user_bot = 1) AND okundu = ?");
    $select->execute([$user_id, 0]);

    return $select->fetchColumn(); 
}

function get_user_data($user_id){
    global $db;

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

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

function get_messages_to_reply(){
    global $db;

    $select = $db->prepare("SELECT  
                        mesajlar.id AS mesaj_id,
                        mesajlar.gonderen_id AS user_id,
                        GROUP_CONCAT(mesajlar.icerik SEPARATOR ' ') AS mesaj,
                        mesajlar.alan_id AS bot_id,
                        kullanicilar.user_jeton AS jeton,
                        kullanicilar.user_onesignal AS user_onesignal,
                        mesajlar.zaman AS zaman
                        FROM mesajlar
                        INNER JOIN kullanicilar ON mesajlar.gonderen_id = kullanicilar.user_id AND kullanicilar.user_deaktif = 0 AND kullanicilar.user_ban = 0
                        WHERE 
                            mesajlar.alan_id IN (SELECT user_id FROM kullanicilar WHERE user_bot = 1) 
                            AND
                            NOT mesajlar.gonderen_id IN (SELECT user_id FROM bot_mesaj_bitenler) 
                            AND 
                            okundu = 0
                            AND
                            zaman > ?
                        GROUP BY mesajlar.gonderen_id, mesajlar.alan_id
                        HAVING jeton <= 5");

    $select->execute([time()-172800]);
    return $select->fetchAll(PDO::FETCH_ASSOC);
}