use VK\Client\VKApiClient;
use VK\OAuth\VKOAuth;

global $config;
$file_check = $config['site_path'] . '/runtime/vk_msg';
if (file_exists($file_check)) {

    $vk = new VKApiClient();

    $scl_msg_token = sql_select_array($config['table_prefix'] . 'module_social_messages', 'messenger = "vk_group"');
    $access_token = $scl_msg_token['token'];

    if (!$access_token) return;

    $response = $vk->messages()->getConversations(
        $access_token,
        [
            'count' => 100,
            'filter' => 'unread'
        ]
    );

    $settings = sql_select_array($config['table_prefix'] . 'module_social_messages_settings');

    foreach ($response['items'] as $key => $val) {
        if ($val['conversation']['peer']['type'] != "group") {
            $user_id = (int)$val['conversation']['peer']['id'];
            $result = data_select_field($settings['user_table_id'],
                'id',
                'status = 0 AND f' . $settings['messenger_id_field'] . ' = ' . $user_id
            );
            if ($row = sql_fetch_assoc($result)) {
                $client_id = $row['id'];
            } else {
                $user_info = $vk->users()->get(
                $access_token,
                    [
                        'user_ids' => $user_id,
                        'fields' => 'bdate, city, photo_50, mobile_phone'
                    ]
                );

                $user_bdate_arr = explode('.', $user_info[0]['bdate']);
                $user_bdate = $user_bdate_arr['2'] . '-' . $user_bdate_arr['1'] . '-' . $user_bdate_arr['0'] . ' 00:00:00';

                if ($user_info[0]['first_name'] == 'DELETED') {
                    $user_name = 'Чат';
                } else {
                    $user_name = $user_info[0]['first_name'] . ' ' . $user_info[0]['last_name'];
                }

                $client_id = sql_insert($config['table_prefix'] . 'data' . $settings['user_table_id'],
                    [
                        'f' . $settings['fio_field'] => $user_name,
                        'f' . $settings['bdate_field'] => $user_bdate,
                        'f' . $settings['messenger_id_field'] => $user_id,
                        'f' . $settings['city_field'] => $user_info[0]['city']['title'],
                        'f' . $settings['photo_field'] => '<img src="' . $user_info[0]['photo_50'] . '">',
                        'f' . $settings['soc_logo_field'] => '<img src="images/vk.png">',
                        'f' . $settings['phone_field'] => $user_info[0]['mobile_phone'],
                        'f' . $settings['flag_field'] => 1,
                        'f' . $settings['user_status_field'] => 'Активен',
                    ]
                );
            }

            $msg = $vk->messages()->getHistory(
                $access_token,
                [
                    'user_id' => $user_id,
                    'count' => 20,
                ]
            );

            foreach ($msg['items'] as $msg_info) {
                if ($msg_info['out'] == 0) {
                    $res_msg = data_select_field($settings['msg_table_id'],
                        'id',
                        'status = 0 AND f' . $settings['msg_id_field'] . ' = ' .  $msg_info['id']
                    );
                    if (!$row_msg = sql_fetch_assoc($res_msg)) {
                        $res_client = data_select_field($settings['user_table_id'],
                            'f' . $settings['user_link_field'] . ' AS client_id',
                            'id = ' . $client_id
                        );
                        $row_client = sql_fetch_assoc($res_client);
                        data_insert($settings['msg_table_id'],
                            EVENTS_ENABLE,
                            [
                                'f' . $settings['message_field'] => $msg_info['text'],
                                'f' . $settings['msg_link_field'] => $client_id,
                                'f' . $settings['message_date_field'] => date('Y-m-d H:i:s', $msg_info['date']),
                                'f' . $settings['msg_id_field'] => $msg_info['id'],
                                'f' . $settings['msg_author_field'] => 'Клиент',
                                'f' . $settings['msg_soc_logo_field'] => '<img src="images/vk.png">',
                                'f' . $settings['msg_client_link_field'] => $row_client['client_id']
                            ]
                        );
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }
            }
        } else {
            continue;
        }
    }
}
