<?php
/**
 * Created by PhpStorm.
 * User: dkuzmichev
 * Date: 03.10.2017
 * Time: 13:03
 */

class I24HSettings
{
//
//  24часаТВ
//
    public static $VERSION          = '2.01';
    public static $API_SERVER       = 'http://api.24h.tv/';
    public static $PLATFORM         = '24htv';
    public static $WINDOW_CAPTION   = '24часаТВ';
    public static $SHOW_DOGOVOD_AFERTA = true;


    public static function get_login_defs($session, $handler, $add_params){

        $defs = array();

        if (!empty($session->provider_id)) {

            ControlFactory::add_label($defs,
                null, 'Смотрите более 200 каналов с 24часаТВ! Удобный выбор из архива передач',
                array('indent' => 0));
            ControlFactory::add_vgap($defs, -20);
            ControlFactory::add_label($defs,
                null, 'и фильмов за 2 недели. Плюс доступ к видеотекам Amediateka и ЦТ-Премьера!',
                array('indent' => 0));


            ControlFactory::add_vgap($defs, 5);
            ControlFactory::add_label($defs,
                null, 'Для получения бесплатного доступа ко всем каналам на 14 дней введите номер',
                array('indent' => 0));
            ControlFactory::add_vgap($defs, -20);
            ControlFactory::add_label($defs,
                null, 'мобильного телефона и нажмите "Далее" для получения кода авторизации по SMS:',
                array('indent' => 0));

            ControlFactory::add_vgap($defs, 5);
            ControlFactory::add_label($defs,
                null, 'По истечении 14 дней вы можете бесплатно продолжить просмотр 20 основных каналов, ',
                array('indent' => 0));
            ControlFactory::add_vgap($defs, -20);
            ControlFactory::add_label($defs,
                null, 'либо оплатить услугу со счета своего интернет-провайдера - всего от 99 рублей в месяц.',
                array('indent' => 0));

        } else {

            $str_arr = preg_split('/;/', wordwrap($session->get_provider_desc(), 160, ';', false));
            foreach ($str_arr as $s) {
                ControlFactory::add_label($defs,
                    null, $s,
                    array('indent' => 0));
                ControlFactory::add_vgap($defs, -20);

            }

        }
        ControlFactory::add_vgap($defs, 20);
        ControlFactory::add_text_field($defs,
            $handler, $add_params,
            'user_name', 'Телефон:',
            '', true, false, false, false, 500);

        ControlFactory::add_vgap($defs, 20);
        ControlFactory::add_button($defs,
            $handler, $add_params,
            'reg_show_agreement', ' ', 'Далее', 500);

        $defs[] = array
        (
            GuiControlDef::name => 'close',
            GuiControlDef::title => '',
            GuiControlDef::kind => GUI_CONTROL_BUTTON,
            GuiControlDef::specific_def =>
                array
                (
                    GuiButtonDef::caption => 'Отмена',
                    GuiButtonDef::width => 500,
                    GuiButtonDef::push_action =>
                        ActionFactory::close_dialog(),
                ),
            GuiControlDef::params => null,
        );

        ControlFactory::add_vgap($defs, 20);

        return $defs;
    }


    public static function get_password($session,&$plugin_cookies, &$user_input, &$handler)
    {
        if ($user_input->control_id == 'get_password' || $user_input->control_id == 'get_sms') {

            if ($user_input->user_name === '') {
                return array(
                    'need_close_dialog' => false,
                    'action' =>
                        ActionFactory::show_error(false,
                            'Запрос пароля',
                            array('Введите номер телефона для отправки пароля.')));
            }
            $user = $session->api_call($session->get_api_server() . I24hSession::I24H_USER, true, array(
                'username' => $user_input->user_name,
                'first_name' => $user_input->user_name,
                'email' => $user_input->user_name . '@24h.tv',
                'phone' => $user_input->user_name
            ));

            $plugin_cookies->user_name = empty($user_input->user_name)?null:$user_input->user_name;
            $plugin_cookies->password = empty($user_input->password)?null:$user_input->password;
            $session->set_mbr_phone($user_input->user_name);
            $session->set_mbr_username($user_input->user_name);

            if (!empty($user) && ($user->status_code == 400)) {

            } elseif (!empty($user) && ($user->status_code == 403)) {

                return array(
                    'need_close_dialog' => false,
                    'action' =>
                        ActionFactory::show_error(false,
                            'Ошибка!',
                            array('К сожалению, в вашем регионе работа приложения невозможна!', 'Страна: ' . $session->country, 'Город: ' . $session->city, 'IP: ' . $session->ip_address)));


            } else {
                $plugin_cookies->user_id = empty($user->id) ? 0 : $user->id;
                $plugin_cookies->provider = empty($user->provider) ? 0 : $user->provider;
            }

            $doc = $session->api_call($session->get_api_server() . I24hSession::I24H_OTPS_URL, true, array('phone' => preg_replace('/^8/', '7', $user_input->user_name)));

            if ($doc->status_code == 403) {

                return array(
                    'need_close_dialog' => true,
                    'action' =>
                        ActionFactory::show_error(false,
                            'Ошибка!',
                            array('К сожалению, в вашем регионе работа приложения невозможна!', 'Страна: ' . $session->country, 'Город: ' . $session->city, 'IP: ' . $session->ip_address)));
            }

            $defs = array();

            ControlFactory::add_label($defs,
                null, 'Введите код высланный по SMS,',
                array('indent' => 0));
            ControlFactory::add_vgap($defs, -20);
            ControlFactory::add_label($defs,
                null, 'На номер +' . $user_input->user_name,
                array('indent' => 0));
            ControlFactory::add_vgap($defs, 30);
            ControlFactory::add_text_field($defs, $handler, null, 'password', 'Код авторизации', '', true, true, false, true, 300);
            ControlFactory::add_vgap($defs, 30);
            ControlFactory::add_close_dialog_and_apply_button($defs, $handler, array(), 'apply_subscription', 'Применить', 300);

            return array(
                'need_close_dialog' => true,
                'action' =>
                    ActionFactory::show_dialog('Авторизация', $defs, true));


    }else{
        return false;
    }

}

    public static function get_setup_user_name($session){
        return 'Учетная запись: +' . $session->get_phone();
    }

    public static function get_top_menu($session,&$plugin_cookies,$amedia){
        $items = array();
        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => TvGroupListScreen::ID
                    )),
            PluginRegularFolderItem::caption => 'Каналы',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/air.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hAmediaListScreen::SCREEN_ID
                    )),
            PluginRegularFolderItem::caption => 'Амедиатека',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/amediateka1.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hCtprimeraListScreen::SCREEN_ID
                    )),
            PluginRegularFolderItem::caption => 'ЦТ Премьера',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/ct.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url => VodSearchScreen::get_media_url_str(),
            PluginRegularFolderItem::caption => 'Поиск',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/search.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hSetupScreen::ID
                    )),
            PluginRegularFolderItem::caption => 'Личный кабинет',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/settings.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hTopcatListScreen::ID,
                        'xcat_id' => 1,
                    )),
            PluginRegularFolderItem::caption => 'Фильмы',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/film.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hTopcatListScreen::ID,
                        'xcat_id' => 2,
                    )),
            PluginRegularFolderItem::caption => 'Сериалы',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/serial.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url => MediaURL::encode(
                array(
                    'screen_id' => I24hTopcatListScreen::ID,
                    'xcat_id' => 3,
                )),
            PluginRegularFolderItem::caption => 'Детям',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/kids.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hTopcatListScreen::ID,
                        'xcat_id' => 4,
                    )),
            PluginRegularFolderItem::caption => 'peredaci',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/peredaci.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hTopcatListScreen::ID,
                        'xcat_id' => 5,
                    )),
            PluginRegularFolderItem::caption => 'Спорт',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/sport.png'
            )
        );


        $atop = $amedia->make_top_list(5);

        $itemshist = array();

//        hd_print('!!!!!!prodhist', print_r($plugin_cookies, true));

        if (isset($plugin_cookies->prodhist)) {
            $prodhist = json_decode($plugin_cookies->prodhist, true);
            $n = 0;
            foreach ($prodhist as $prod) {
                if ($n >= 5) break;

                if (empty($prod['type'])) continue;
                if ($prod['type'] == 1) {

                    if (empty($prod['product_id'])) continue;

                    $movie = $session->load_movie($prod['product_id']);

                    if (empty($movie['id'])) continue;

//                    hd_print('ICON PATH ' . $movie['poster']);

                    $vip = array(ViewItemParams::icon_path => $movie['poster']);

                    $itemshist[] = array
                    (
                        PluginRegularFolderItem::media_url =>
                            VodMovieScreen::get_media_url_str($movie['id']), // XXX: alik: hack!!
                        PluginRegularFolderItem::caption => $movie['name'],
                        PluginRegularFolderItem::view_item_params => $vip,
                    );
                }
                if ($prod['type'] == 2) {
                    if (empty($prod['serial_id'])) continue;
                    $amedia_hist = $amedia->make_single_item($prod['serial_id']);

                    if (empty($amedia_hist['media_url'])) continue;
                    $itemshist[] = $amedia_hist;
                }
                $n++;

            }
        }

        return array_merge($items, $atop, $itemshist);

    }

    public static function get_top_action_map($session)
    {
        $top_action =
            UserInputHandlerRegistry::create_action(
                $session, 'top_action');
        return array
        (
            GUI_EVENT_KEY_ENTER => $top_action,
            GUI_EVENT_KEY_PLAY => $top_action
        );
    }

}
