<?php

use Database\{Botads, Users};

if (Botads::hasAdss()) {
    $getAds = Botads::getAllAds();
    $getInfoUser = Users::getUser($chatidForAds);
    $getUserAds = $getInfoUser->ads;
    $getUserAdsArray = json_decode($getUserAds);
    $i = 0;
    $adsarr_for = [];
    if ($getUserAds != null and $getUserAds != 'null') {
        foreach ($getAds as $ads) {
            $getUserAdsArray = (array)$getUserAdsArray;
            $GetUserKey = $getUserAdsArray[$ads->id];
            $GetUserKey = (array)$GetUserKey;
            $tm = time() - 3600;
            if ($GetUserKey['time'] < $tm) {
                $adsarr_for[] = $getAds[$i];
            }
            $i++;
        }
    } else {
        $adsarr_for = $getAds;
    }

    if ($adsarr_for != []) {
        $rand_keys = array_rand($adsarr_for, 1);
        $adsArray = $getAds[$rand_keys];
        $keys = $adsArray->id;
        $count = $adsArray->view;
        $max_view = $adsArray->max_view;
        $btn_title = $adsArray->btn_title;
        $btn_url = $adsArray->btn_url;
        $btn = null;
        if ($btn_title != null) {
            $btn = ['inline_keyboard' => [[["text" => $btn_title, "url" => $btn_url]]], 'resize_keyboard' => true];
        }
        if($adsArray->chatid){
        $Telegram->copyMessageNonCaption($chatidForAds, $adsArray->chatid, $adsArray->msgid, 'html', $btn);
        $new_view = $count + 1;
        if ($new_view >= $max_view) {
            Botads::RemoveAds($keys);
            unset($getUserAdsArra[$keys]);
        } else {
            Botads::updateView($keys, $new_view);
            $new = [$keys => ['time' => time(), 'id' => $keys]];
            $getUserAdsArra = $getUserAdsArra = array_merge((array)$new,(array)$getUserAdsArray);
        }
        Users::updateAds($chatidForAds,json_encode($getUserAdsArra));
        }
    }

}

