<?php

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

require_once '../../config.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'));
$select_count_f = get_grouped_scenarios();
$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;
    $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_user_is_in_finish($row['user_id']))) insert_end($row['user_id'], 0);

    
    /*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' => "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 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_end($user_id, $status){
    global $db;

    $update = $db->prepare("INSERT INTO bot_mesaj_bitenler (user_id, mesaj_tipi, durum) values(?, ?, ?)");
    $update->execute([$user_id, 1, $status]);
}

function insert_log($user_id, $bot_id, $scenario_id, $turn){
    global $db;
    
    $insert = $db->prepare("INSERT INTO jeton_senaryo_bes_fazla_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;
    
    $insert = $db->prepare("INSERT INTO mesajlar (gonderen_id, alan_id, icerik, ip, zaman, okundu) values(?, ?, ?, ?, ?, ?)");
    $insert->execute([$bot_id, $user_id, $message, "::1", time(), 0]);
}

function update_end($user_id){
    global $db;

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

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

    $update = $db->prepare("UPDATE jeton_senaryo_bes_fazla_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_bes_fazla 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_is_in_finish($user_id){
    global $db;

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

    return $select->rowCount() > 0 ? true : false;
}

function get_user_logs($user_id){
    global $db;

    $select = $db->prepare("SELECT * FROM jeton_senaryo_bes_fazla_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_bes_fazla WHERE senaryo_id = ? AND senaryo_sira = ?");
    $select->execute([$scenario_id, $turn]);

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

function get_scenarios(){
    global $db;

    $select = $db->prepare("SELECT * FROM jeton_senaryo_bes_fazla");
    $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_bes_fazla 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_bes_fazla_log.senaryo_sira as senaryo_sira,
                        jeton_senaryo_bes_fazla_log.senaryo_id  as senaryo_id
                        FROM jeton_senaryo_bes_fazla_log
                        WHERE user_id = ?
                        GROUP BY jeton_senaryo_bes_fazla_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
                        kullanicilar.user_id as user_id,
                        mesajlar.alan_id as bot_id,
                        kullanicilar.user_jeton AS jeton,
                        kullanicilar.user_onesignal AS user_onesignal,
                        jeton_senaryo_bes_fazla_log.senaryo_id AS senaryo_id,
                        jeton_senaryo_bes_fazla_log.senaryo_sira AS senaryo_sira,
                        (SELECT 
                            COUNT(jeton_senaryo_bes_fazla.senaryo_id) AS senaryo_sum
                            FROM jeton_senaryo_bes_fazla
                            WHERE jeton_senaryo_bes_fazla.senaryo_id = jeton_senaryo_bes_fazla_log.senaryo_id
                        ) AS senaryo_sum
                        FROM kullanicilar
                        INNER JOIN mesajlar ON kullanicilar.user_id = mesajlar.gonderen_id AND mesajlar.alan_id IN (SELECT user_id FROM kullanicilar WHERE user_bot = 1)
                        LEFT JOIN jeton_senaryo_bes_fazla_log ON kullanicilar.user_id = jeton_senaryo_bes_fazla_log.user_id AND mesajlar.alan_id = jeton_senaryo_bes_fazla_log.bot_id
                        WHERE 
                            kullanicilar.user_jeton > 5
                            AND
                            kullanicilar.user_deaktif = 0 
                            AND 
                            kullanicilar.user_ban = 0
                            AND
                            NOT kullanicilar.user_id IN (SELECT user_id FROM bot_mesaj_bitenler WHERE mesaj_tipi = 1 AND durum = 1)
                        GROUP BY kullanicilar.user_id, mesajlar.alan_id
                        HAVING (jeton_senaryo_bes_fazla_log.senaryo_sira < senaryo_sum OR COUNT(jeton_senaryo_bes_fazla_log.senaryo_sira) = 0)");

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