<?php

\set_time_limit(0);
require __DIR__ . '/common.php';
use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\K131970f0a776522b1a53ba419cd5e32c;
use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e;
use Ministra\Lib\SysEvent;
use Ministra\Lib\User;
if (!\Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\K131970f0a776522b1a53ba419cd5e32c::get('enable_tariff_plans')) {
    exit;
}
$need_to_switch = \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::getInstance()->from('users')->where(['tariff_expired_date!=' => '', 'tariff_expired_date != ' => '0000-00-00 00:00:00', 'tariff_expired_date<=' => \date(\Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::f7c1a00e2e85e35c3eab86d1e76eefa5)])->get();
$tariffs = \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::getInstance()->from('tariff_plan')->get()->all();
$tariffs_map = [];
foreach ($tariffs as $tariff) {
    $tariffs_map[$tariff['id']] = $tariff;
}
$default_tariff = \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::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\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::getInstance()->update('users', ['tariff_plan_id' => $tariff_plan_id, 'tariff_expired_date' => !isset($days_to_expires) || $days_to_expires == 0 ? \null : \date(\Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::f7c1a00e2e85e35c3eab86d1e76eefa5, \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();
    }
}
