<?php

require_once 'lib/abstract_preloaded_regular_screen.php';

$month_arr = array('01' => 'янв','02' => 'фев','03' => 'мар','04' => 'апр',
                   '05' => 'мая','06' => 'июн','07' => 'июл','08' => 'авг',
                   '09' => 'сен','10' => 'окт','11' => 'ноя','12' => 'дек'
                  );

class I24hPrivateScreen extends AbstractPreloadedRegularScreen
    implements UserInputHandler
{
    const ID = 'private';
    private $user_curr_tariff_id;
    private $count_dop_packets;
    private $plugin;

    public static function get_media_url_str($pin)
    {
        return MediaURL::encode(
            array('screen_id' => self::ID, 'pin' => $pin));
    }

    public static function get_item_media_url_str($pin, $type, $service_id, $subscription_id)
    {
        return MediaURL::encode(
            array(
                'screen_id' => self::ID,
                'type' => $type,
                'pin' => $pin,
                'service_id' => $service_id,
                'subscription_id' => empty($subscription_id)?null:$subscription_id));
    }

    public function get_control_defs(MediaURL $media_url, &$plugin_cookies)
    {
        return $this->do_get_control_defs($plugin_cookies);
    }


    public function get_handler_id()
    {
        return self::ID;
    }

    public function __construct(I24hPlugin $plugin)
    {
        parent::__construct(self::ID, I24hConfig::GET_PRIVATE_FOLDER_VIEWS());

        $this->plugin = $plugin;

        UserInputHandlerRegistry::get_instance()->register_handler($this);
    }

    public function get_action_map(MediaURL $media_url, &$plugin_cookies)
    {
        return array
        (
            GUI_EVENT_KEY_ENTER =>
                UserInputHandlerRegistry::create_action(
                    $this, 'handle_enter'),
            GUI_EVENT_KEY_INFO =>
                UserInputHandlerRegistry::create_action(
                    $this, 'handle_info'),
        );
    }

    private function info_dialog_action(
        $service_id, $selected_media_url,
        $title, $msg_lines, $apply_name)
    {
        $defs = array();

        foreach ($msg_lines as $line)
            ControlFactory::add_label($defs, null, $line);

        ControlFactory::add_vgap($defs, 30);

        $add_params = array(
            'service_id' => $service_id,
            'selected_media_url' => $selected_media_url);

        ControlFactory::add_close_dialog_and_apply_button($defs,
            $this, $add_params,
            $apply_name, 'OK', 200);

        return ActionFactory::show_dialog($title, $defs, true, 0,
            array('initial_sel_ndx' => 0));
    }

    
    private function get_yes_no_dialog_action(
        $service_id, $selected_media_url,
        $title, $msg_lines, $apply_name, $yes_by_default)
    {
        $defs = array();

        foreach ($msg_lines as $line)
            ControlFactory::add_label($defs, null, $line);

        ControlFactory::add_vgap($defs, 30);

        $add_params = array(
            'service_id' => $service_id,
            'selected_media_url' => $selected_media_url);

        ControlFactory::add_close_dialog_and_apply_button($defs,
            $this, $add_params,
            $apply_name, 'Да', 200, true);

        ControlFactory::add_vgap($defs, -3);

        ControlFactory::add_close_dialog_button($defs,
            'Нет', 200, true);

        $initial_sel_ndx = $yes_by_default ? 0 : 1;
        return ActionFactory::show_dialog($title, $defs, true, 0,
            array('initial_sel_ndx' => $initial_sel_ndx));
    }

    private function get_pay_dialog_action(
        $service_id, $selected_media_url,
        $title, $msg_lines, $apply_name, $yes_by_default, $ps_arr)
    {
        $defs = array();

        foreach ($msg_lines as $line)
            ControlFactory::add_label($defs, null, $line);

        ControlFactory::add_vgap($defs, 30);
        
        $add_params = array(
            'service_id' => $service_id,
            'selected_media_url' => $selected_media_url);

        ControlFactory::add_close_dialog_and_apply_button($defs,
            $this, $add_params,
            $apply_name, 'Подписаться', 200, array('button_caption_centered'=>true));

        ControlFactory::add_vgap($defs, -3);

        ControlFactory::add_close_dialog_button($defs,
            '    Отмена    ', 200, array('button_caption_centered'=>true));

        $initial_sel_ndx = $yes_by_default ? 0 : 1;
        return ActionFactory::show_dialog($title, $defs, true, 0,
            array('initial_sel_ndx' => $initial_sel_ndx));
    }

    private function renew_dialog_action(
        $service_id, $selected_media_url,
        $title, $msg_lines, $apply_name, $yes_by_default, $ps_arr)
    {

//        hd_print('renew_dialog_action: service_id = '.$service_id);

        $defs = array();

        foreach ($msg_lines as $line)
            ControlFactory::add_label($defs, null, $line);

        ControlFactory::add_vgap($defs, 30);

        $add_params = array(
            'service_id' => $service_id,
            'selected_media_url' => $selected_media_url);

        ControlFactory::add_close_dialog_and_apply_button($defs,
            $this, $add_params,
            $apply_name, 'Отключить ', 200, array('button_caption_centered'=>true));

        ControlFactory::add_vgap($defs, -3);

        ControlFactory::add_close_dialog_button($defs,
            '   Отмена   ', 200, array('button_caption_centered'=>true));

        $initial_sel_ndx = $yes_by_default ? 0 : 1;
        return ActionFactory::show_dialog($title, $defs, true, 0,
            array('initial_sel_ndx' => $initial_sel_ndx));
    }


    private function do_edit_pin_action()
    {
        $defs = array();

        ControlFactory::add_text_field($defs, $this, null,
            'current_pin', 'Текущий PIN-код:',
            '', true, true, false, false, 500);

        ControlFactory::add_text_field($defs, $this, null,
            'new_pin', 'Новый PIN-код:',
            '', true, true, false, false, 500);

        ControlFactory::add_text_field($defs, $this, null,
            'new_pin_copy', 'Подтверждение:',
            '', true, true, false, false, 500);

        ControlFactory::add_vgap($defs, 50);

        ControlFactory::add_button($defs, $this, null,
            'apply_pin', null, 'Применить', 300, true);

        ControlFactory::add_vgap($defs, -3);

        ControlFactory::add_close_dialog_button($defs,
            'Отмена', 300, array('button_caption_centered'=>true));

        return ActionFactory::show_dialog('Смена PIN-кода', $defs, true);
    }

    private function do_reset_auth_settings_action()
    {
        $defs = array();

        ControlFactory::add_label($defs, null,
            'Вы уверены, что хотите сбросить настройки авторизации?');

        ControlFactory::add_vgap($defs, 30);
        
        ControlFactory::add_close_dialog_and_apply_button($defs, $this, null,
            'apply_reset_auth_settings', 'Да', 200, true);

        ControlFactory::add_vgap($defs, -3);

        ControlFactory::add_close_dialog_button($defs,
            'Нет', 200, true);

        return ActionFactory::show_dialog(
            'Подтверждение', $defs, true, 0,
            array('initial_sel_ndx' => 2));
    }

    private function apply_pin($user_input, $plugin_cookies)
    {
        if ($user_input->new_pin !== $user_input->new_pin_copy)
        {
            return ActionFactory::show_error(
                false, 'Ошибка', array('Новый PIN-код и его подтверждение не совпадают'));
        }

        $session = $this->plugin->get_session($plugin_cookies);
        $session->ensure_logged_in($plugin_cookies);
        
        $m = $session->getMemberByPin($user_input->current_pin);
        if (is_null($m))
        {
            return ActionFactory::show_error(
                false, 'Ошибка', array('Неверный текущий PIN-код'));
        }

        try
        {
            $session->editMember(
                $m->id, $user_input->new_pin,
                $m->name, $m->spendingLimit, $m->prLevel);
        }
        catch (I24hException $e)
        {
            $error_message = 'Обратитесь в тех-поддержку.';

            if ($e->getCode() === I24hException::OPERATION_FAILED)
            {
                switch ($e->getApiErrorCode())
                {
                    case 302:
                        $error_message = 'Неправильный формат PIN-кода.';
                        break;

                    case 600:
                        $error_message = 'PIN-код уже используется.';
                        break;
                }
            }

            return ActionFactory::show_error(
                false, 'Невозможно сменить PIN-код', array($error_message));
        }

        return ActionFactory::close_dialog();
    }

    private function apply_reset_auth_settings(&$plugin_cookies)
    {
//        hd_print("Setup: applying reset auth settings");
        unset($plugin_cookies->user_name);
        unset($plugin_cookies->user_password);
        $this->plugin->close_session();
        return ActionFactory::show_error(
            true, 'Настройки авторизации сброшены.');
    }

    private function handle_reset_auth_user_input(
        &$user_input, &$plugin_cookies)
    {
        $media_url = MediaURL::decode($user_input->selected_media_url);
        return null;
    }

    public function handle_user_input(&$user_input, &$plugin_cookies)
    {
//        hd_print('TvSubscriptions: handle_user_input:');
//        foreach ($user_input as $key => $value)
//            hd_print("  $key => $value");
        if (isset($user_input->control_id))
        {
            if ($user_input->control_id === 'apply_pin')
                return $this->apply_pin($user_input, $plugin_cookies);
            if ($user_input->control_id === 'apply_reset_auth_settings')
                return $this->apply_reset_auth_settings($plugin_cookies);
        }
        if (!isset($user_input->selected_media_url))
            return null;
        $media_url = MediaURL::decode($user_input->selected_media_url);
        
        if ($media_url->screen_id == 'setup') {
            return ActionFactory::open_folder();
        }
        if ($media_url->type == 'edit_pin')
            return $this->do_edit_pin_action();
        if ($media_url->type == 'reset_auth')
            return $this->do_reset_auth_settings_action();

        $session = $this->plugin->get_session($plugin_cookies);
        $session->ensure_logged_in($plugin_cookies);
        $srv = $session->getServiceById($media_url->service_id);
        $curr_triff = $session->get_current_packets();
        try
        {
            $balance = $session->getBalance();
        }
        catch (I24hException $e)
        {
            return ActionFactory::show_error(
                false,
                'Ошибка проверки баланса',
                array('Обратитесь в тех-поддержку.'));
        }
        if ($user_input->control_id == 'handle_enter')
        {

//           hd_print("*************** handle_enter *******************");
//           hd_print("user_input->control_id = ".$user_input->control_id);
//           hd_print("media_url->service_id = ".$media_url->service_id);
           if ($media_url->service_id == 'add_packets') {

//               hd_print("*************** add_packets *******************");

               if (empty($this->count_dop_packets) or ($this->count_dop_packets == 0)) {
                   return ActionFactory::show_error(
                       false,
                       'Предупреждение',
                       array('У текущего основного пакета нет дополнительных пакетов!'));

               } else {
                   return ActionFactory::open_folder(I24hAddPacketScreen::get_media_url_str(''), 'Дополнительные пакеты');
               }

           } else if ($media_url->service_id == 'reset_to_main_screen'){
               $post_action = ActionFactory::open_folder(MediaURL::encode(array('screen_id'=>I24hTopScreen::ID)),I24HSettings::$WINDOW_CAPTION);
               return $post_action;
           }else{

            if ($this->user_curr_tariff_id == $media_url->service_id){
//                return ActionFactory::show_error(
//                    false, 'Ошибка', array('Данный тариф уже подключен!'));
                $ps_arr = array();

//                hd_print('media_url->subscription_id = '.$media_url->subscription_id);

                return $this->renew_dialog_action(
                    $media_url->subscription_id,
                    $user_input->selected_media_url,
                    'Подтверждение',
                    array('Вы уверены, что хотите отключить пакет?'),
                    'apply_unsubscribe',
                    true,
                    $ps_arr);
            }

            $ps_arr = array();

            if (empty($balance)){
                $array_text = array
                (
                    'Подтвердите подписку на тариф',
                    '"' . $srv->name . '"',
                    'Стоимость подписки: ' . $srv->price . ' руб. в месяц',
                );
            }else{
                $array_text = array
                (
                    'Подтвердите подписку на тариф',
                    '"' . $srv->name . '"',
                    'Текущий баланс: ' . $balance . ' руб',
                    'Стоимость подписки: ' . $srv->price . ' руб. в месяц',
                );
            }
            return $this->get_pay_dialog_action(
                $media_url->service_id,
                $user_input->selected_media_url,
                'Подтверждение',
                $array_text,
                'apply_subscribe',
                true,
                $ps_arr);
            }
        }
//        else if ($user_input->control_id == 'renew_subscribe'){
//            removeServiceFromSubscription
//
//        }
        else if ($user_input->control_id == 'apply_subscribe')
        {
            try
            {
                $res = $session->addServiceToSubscription(
                    $media_url->service_id);
            }
            catch (I24hException $e)
            {
                return ActionFactory::show_error(
                    false,
                    'Невозможно добавить подписку',
                    array('Обратитесь в тех-поддержку.'));
            }

            if (!empty($res->status_code)) {
            	$balance = $session->getBalance();

                return $this->info_dialog_action(
                    $media_url->service_id,
                    $user_input->selected_media_url,
                    'Ошибка',
                    $res->detail,
                    'apply_noreload');

            } else {

                $text_info = array();
                foreach ($res as $r){
                    $t = array("Вы подключили тариф: ".$r->packet->name,"С ".date("H:i d.m.y",strtotime($r->start_at)).
                        " По ".date("H:i d.m.y",strtotime($r->end_at)),"");
                    $text_info = array_merge($text_info,$t);
                }
                return $this->info_dialog_action(
                    $media_url->service_id,
                    $user_input->selected_media_url,
                    'Информация',
                    $text_info,
                    'apply_reload');
                
            }
            
            $this->plugin->get_tv()->unload_channels();
            
            $items = $this->get_all_folder_items(
                $media_url, $plugin_cookies);
            return ActionFactory::update_regular_folder(
                HD::create_regular_folder_range($items), true);
        }
        else if ($user_input->control_id == 'apply_unsubscribe')
        {

            hd_print('$media_url = '.print_r($media_url,true));

            try
            {
                $session->removeServiceFromSubscription(
                    $media_url->subscription_id);
            }
            catch (I24hException $e)
            {
                return ActionFactory::show_error(
                    false,
                    'Невозможно удалить подписку',
                    array('Обратитесь в тех-поддержку.')); 
            }

            $this->plugin->get_tv()->unload_channels();

            $items = $this->get_all_folder_items(
                $media_url, $plugin_cookies);
            return ActionFactory::update_regular_folder(
                HD::create_regular_folder_range($items), true);
        }
        else if ($user_input->control_id == 'apply_reload')
        {
//            hd_print("apply_reload !!!!!");

            $this->plugin->get_tv()->unload_channels();
	        $this->plugin->get_tv()->ensure_channels_loaded($plugin_cookies);

            $items = $this->get_all_folder_items($media_url, $plugin_cookies);

//            hd_print("FOLDER ITEMS: ".print_r($items,true));
            return ActionFactory::update_regular_folder(
                HD::create_regular_folder_range($items), true);
        }
        else if ($user_input->control_id == 'handle_info')
        {
            $chans = "\nСостав пакета ТВ-каналов \"$srv->name\":\n";
            $n = 1;
            $ar = array();
            foreach ($srv->channels as $c){
                $ar[] = $c->name;
            }
            asort($ar);
            foreach ($ar as $ch)
            {
                $chans .= "$n. $ch \n";
                $n++;
            }

            $defs = array();

            if (!preg_match('/^\s*$/', $srv->description))
            {
//                hd_print($srv->description);
                ControlFactory::add_multiline_label($defs,
                    '', 'Управление: "P+" - пролистать вверх, "P-" - пролистать вниз.'."\n\n".strip_tags(html_entity_decode(str_replace('&ndash;', '-',$srv->description), ENT_NOQUOTES))."\n".$chans, 17);

                ControlFactory::add_vgap($defs, 30);
            }
            ControlFactory::add_close_dialog_button($defs,'Закрыть', 300);

            if (!empty($srv->name)) {
                return ActionFactory::show_dialog("Состав пакета ТВ-каналов \"$srv->name\"",
                    $defs, true, 1000);
            }else{
                $defs = array();
                ControlFactory::add_close_dialog_button($defs,'Закрыть', 300);
                return ActionFactory::show_dialog("Выберите пакет для просмотра",
                    $defs, true, 1000);
            }
        }
        return null;
    }

    public function do_get_control_defs(&$plugin_cookies)
    {
        $defs = array();

        ControlFactory::add_button($defs,$this,array(),'Ghsadas1','','ssadas1',500,true);
        ControlFactory::add_button($defs,$this,array(),'Ghsadas2','','ssadas2',500,true);

        $this->add_label($defs, 'Профиль', '');

        $this->add_button($defs,
            'data_path',
            '',
            'Тариф', 500
            );

        $this->add_button($defs,
            'data_path',
            '',
            'Род. контроль', 500
            );
        $this->add_button($defs,
            'data_path',
            '',
            'Видео', 500
            );
        return $defs;
    }

    public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
    {
        $session = $this->plugin->get_session($plugin_cookies);
        $session->ensure_logged_in($plugin_cookies);
        $service_list = $session->getServiceList();
        try
        {
            $balance = $session->getBalance();
        }
        catch (I24hException $e)
        {
            throw new DuneException(
                'Can not retrieve balance', 0,
                ActionFactory::show_error(
                    false,
                    'Ошибка проверки баланса',
                    array('Обратитесь в тех-поддержку.')));
        }
        $phone = $session->get_phone();
        $username = $session->get_username();
        $user_name = !empty($phone)?$phone:$username;
        $items = array();
        $this->user_curr_tariff_id = "";
        $details_common = "";
//        $details_common = "Текущий пользователь:|". I24HSettings->get_setup_user_name($user_name)."||";
        if (!empty($balance)) $details_common .= "Текущий баланс:|$balance руб||";
        
        setlocale(LC_ALL, "ru_RU.UTF-8");

        $dop_packets = null;
        $count_dop_packets = 0;
        $count_curr_dop_packets = 0;
        $curr_packets = array();
        foreach ($session->get_current_packets() as $p){
            $curr_packets[$p->packet->id]['name'] = $p->packet->name;
            $curr_packets[$p->packet->id]['subscribtion_id'] = $p->id;

            if ($p->packet->base){
                $this->user_curr_tariff_id = $p->packet->id;
                $details_common .= "Текущий тариф:";
                $details_common .= "|".$p->packet->name;
                if ($p->is_paused){
                    $details_common .= "|Тариф приостановлен||";
                }else {
                    $details_common .= $p->renew ? "|По " : "|До ";
                    $details_common .= date("H:i d.m.y", strtotime($p->end_at)) . "||";
                }
//                $details_common .= "Автопродление: ".($p->renew?'Да':'Нет')."||";

            }else{$dop_packets .= "|".$p->packet->name;  }

        }
         if (!empty($dop_packets)){$details_common .= "||||Подключенные||дополнительные пакеты:".$dop_packets;$count_curr_dop_packets++;}

        foreach ($service_list as $srv)
        {
            $icon_url = !empty($curr_packets[$srv->id]) ?
                'gui_skin://special_icons/included.aai' :
                'gui_skin://special_icons/excluded.aai';
            $icon_scale_factor = !empty($curr_packets[$srv->id]) ? 1 : 1.5;
            if (!empty($curr_packets[$srv->id])){
                $count_dop_packets = count($srv->available);
            }
            $item_detailed_info = $details_common;
            $items[] = array
            (
                PluginRegularFolderItem::media_url => 
                    self::get_item_media_url_str($media_url->pin, 'service', $srv->id,empty($curr_packets[$srv->id]['subscribtion_id'])?$srv->id:$curr_packets[$srv->id]['subscribtion_id']),// $srv->id),
                PluginRegularFolderItem::caption => $srv->name." (".$srv->price." руб.)",
                PluginRegularFolderItem::view_item_params => array
                (
                    ViewItemParams::icon_path => $icon_url,
                    ViewItemParams::icon_scale_factor => $icon_scale_factor,
                    ViewItemParams::item_detailed_icon_path => 'gui_skin://large_icons/tv.aai',
                    ViewItemParams::item_detailed_info => $item_detailed_info,
                )
            );
        }

        $items[] = array
        (
            PluginRegularFolderItem::media_url => self::get_item_media_url_str('add_channels', 'service', 'add_packets', null),
            PluginRegularFolderItem::caption => "[ Подключить дополнительные пакеты ]",
            PluginRegularFolderItem::view_item_params => array
            (
                ViewItemParams::icon_path => 'missing://',
                ViewItemParams::icon_scale_factor => 1,
                ViewItemParams::item_detailed_icon_path => 'gui_skin://large_icons/tv.aai',
                ViewItemParams::item_detailed_info => 'Подключите доп.пакеты|| для увеличения||списка каналов!',
            )
        );
        $this->count_dop_packets = $count_dop_packets;
        return $items;
    }

}

?>
