<?php

\set_time_limit(0);
include __DIR__ . '/common.php';
use Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\k8281faec2a4a41f470b00112682ddabf;
use Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2;
use Ministra\Lib\SysEvent;
use Ministra\Lib\User;
if (!\Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\k8281faec2a4a41f470b00112682ddabf::get('enable_tariff_plans')) {
    exit;
}
$need_to_switch = \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::getInstance()->from('users')->where(['tariff_expired_date!=' => '', 'tariff_expired_date != ' => '0000-00-00 00:00:00', 'tariff_expired_date<=' => \date(\Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::DATETIME_FORMAT)])->get();
$tariffs = \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::getInstance()->from('tariff_plan')->get()->all();
$tariffs_map = [];
foreach ($tariffs as $tariff) {
    $tariffs_map[$tariff['id']] = $tariff;
}
$default_tariff = \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::getInstance()->from('tariff_plan')->where(['user_default' => 1])->get()->first();
while ($user = $need_to_switch->next()) {
    if (isset($tariffs_map[$user['tariff_id_instead_expired']])) {
        $days_to_expires = $tariffs_map[$user['tariff_id_instead_expired']]['days_to_expires'];
    } elseif ($default_tariff) {
        $days_to_expires = $default_tariff['days_to_expires'];
    }
    $tariff_plan_id = isset($tariffs_map[$user['tariff_id_instead_expired']]) ? $user['tariff_id_instead_expired'] : 0;
    \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::getInstance()->update('users', ['tariff_plan_id' => $tariff_plan_id, 'tariff_expired_date' => !isset($days_to_expires) || $days_to_expires == 0 ? \null : \date(\Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::DATETIME_FORMAT, \time() + $days_to_expires * 24 * 3600), 'tariff_id_instead_expired' => 0], ['id' => $user['id']]);
    if ($tariff_plan_id != $user['tariff_plan_id']) {
        $event = new \Ministra\Lib\SysEvent();
        $event->setUserListById([(int) $user['id']]);
        $user_o = \Ministra\Lib\User::getInstance((int) $user['id']);
        $event->sendMsgAndReboot($user_o->getLocalizedText('Tariff plan is changed, please restart your STB'));
        \Ministra\Lib\User::clear();
    }
}
