<?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;
}
$default_tariff = \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::getInstance()->from('tariff_plan')->where(['user_default' => 1])->get()->first();
$tariffs_notifications = \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::getInstance()->select('tariffs_notifications.*, messages_templates.header, messages_templates.body, messages_templates.url')->from('tariffs_notifications')->join('messages_templates', 'tariffs_notifications.template_id', 'messages_templates.id', 'INNER')->get()->all();
$tariffs_notifications_map = [];
foreach ($tariffs_notifications as $tariffs_notification) {
    if (!isset($tariffs_notifications_map[$tariffs_notification['tariff_id']])) {
        $tariffs_notifications_map[$tariffs_notification['tariff_id']] = [];
    }
    $tariffs_notifications_map[$tariffs_notification['tariff_id']][] = $tariffs_notification;
}
$users = \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::getInstance()->from('users')->where(['tariff_expired_date!=' => '', 'tariff_expired_date != ' => '0000-00-00 00:00:00'])->get();
while ($user = $users->next()) {
    if ($user['tariff_plan_id'] == 0 && !$default_tariff) {
        continue;
    }
    $tariff_plan_id = $user['tariff_plan_id'] == 0 ? $default_tariff['id'] : $user['tariff_plan_id'];
    if (isset($tariffs_notifications_map[$tariff_plan_id])) {
        foreach ($tariffs_notifications_map[$tariff_plan_id] as $notification) {
            $tariff_expired_time = \strtotime($user['tariff_expired_date']);
            if ($tariff_expired_time < \time() + $notification['notification_delay_in_hours'] * 3600 && $tariff_expired_time > \time() + ($notification['notification_delay_in_hours'] - 1) * 3600) {
                $event = new \Ministra\Lib\SysEvent();
                $event->setUserListById([(int) $user['id']]);
                $user_o = \Ministra\Lib\User::getInstance((int) $user['id']);
                if ($notification['url']) {
                    $event->sendMsgWithUrl($notification['body'], $notification['url'], $notification['header']);
                } else {
                    $event->sendMsg($notification['body'], $notification['header']);
                }
                \Ministra\Lib\User::clear();
            }
        }
    }
}
