<?php

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

//include '../../config.php';

require_once 'keywords.php';
require_once 'answers.php';


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



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

    if($row['jeton']<=5){
        $answer_arr = [];

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

        $limit = 3;//Değiştebilirsiniz, gönderilecek mesaj limitidir
        for($i=0; $i<count($last_message_keyowrds); $i++){
            if(!(count($answer_arr)<$limit)) break;
            $keyword = $last_message_keyowrds[$i];

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

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

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

        echo "<pre>";
        print_r($answer_arr);
        echo "</pre>";
        
    }else{

    }

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

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_messages($user_id, $bot_id, $answer_arr){
    global $db;

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

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_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
                        FROM mesajlar
                        INNER JOIN kullanicilar ON mesajlar.gonderen_id = kullanicilar.user_id
                        WHERE mesajlar.alan_id IN (SELECT user_id FROM kullanicilar WHERE user_bot = 1) AND okundu = 0
                        GROUP BY mesajlar.gonderen_id, mesajlar.alan_id");

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

