<?php
require_once 'lib/abstract_preloaded_regular_screen.php';


class I24hAddPacketScreen extends AbstractPreloadedRegularScreen
    implements UserInputHandler
{
    const ID = 'add_packets';
    private $curr_base_tariff_id;
    private $plugin;

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

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

        $this->plugin = $plugin;

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

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

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

    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'),
        );
    }

    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();
        $curr_packets = array();
        $curr_base_tariff_id = 0;
        $curr_tariff_id = array();
        foreach ($session->get_current_packets() as $p) {

            $curr_tariff_id[$p->packet->id]['name'] = $p->packet->name;
            $curr_tariff_id[$p->packet->id]['renew'] = $p->renew;
            $curr_tariff_id[$p->packet->id]['id'] = $p->id;

            $curr_packets[$p->packet->id]['name'] = $p->packet->name;
            if (!$p->packet->base) {
            }else{
                $curr_base_tariff_id = $p->packet->id;
                $this->curr_base_tariff_id = $curr_base_tariff_id;
            }
        }
        $items = array();

        foreach ($service_list as $srv)
        {
            if ($srv->id == $curr_base_tariff_id) {
                foreach ($srv->available as $dop) {

                    $details_common = "";
                    $dop_packets = "";
                    $details_common .= "Подключенные пакеты:";
                    foreach ($session->get_current_packets() as $p){
                        $curr_packets[$p->packet->id]['name'] = $p->packet->name;

                        if (!$p->packet->base){
                            $this->user_curr_tariff_id = $p->packet->id;
                            $details_common .= "|- ".$p->packet->name;
                            $details_common .= $curr_tariff_id[$p->packet->id]['renew']?"|По ":"|До ";
                            $details_common .= "".date("H:i d.m.y",strtotime($p->end_at));
                            if ($p->is_paused) $details_common .= "|Тариф приостановлен";
                            $details_common .= "||";
                        }

                    }

                    $item_detailed_info = $details_common;
                    $icon_url = !empty($curr_packets[$dop->id]) ?
                        'gui_skin://special_icons/included.aai' :
                        'gui_skin://special_icons/excluded.aai';
                    $icon_scale_factor = !empty($curr_packets[$dop->id]) ? 1 : 1.5;

                    $items[] = array
                    (
                        PluginRegularFolderItem::media_url =>
                            self::get_item_media_url_str($media_url->pin, 'service', $dop->id),
                        PluginRegularFolderItem::caption => $dop->name." (".$dop->price." руб.)",
                        PluginRegularFolderItem::view_item_params => array
                        (
                            ViewItemParams::icon_path => $icon_url,
                            ViewItemParams::icon_scale_factor => $icon_scale_factor,
                            ViewItemParams::item_detailed_icon_path => 'none:',
                            ViewItemParams::item_detailed_info => $item_detailed_info,
                        )
                    );


                }
            }
        }


        return $items;
    }

    public function handle_user_input(&$user_input, &$plugin_cookies)
    {
        $session = $this->plugin->get_session($plugin_cookies);
        $session->ensure_logged_in($plugin_cookies);
        $media_url = MediaURL::decode($user_input->selected_media_url);
        $base_srv = $session->getServiceById($this->curr_base_tariff_id);
        $curr_tariff_id = array();
        foreach ($session->get_current_packets() as $t) {
            $curr_tariff_id[$t->packet->id]['name'] = $t->packet->name;
            $curr_tariff_id[$t->packet->id]['renew'] = $t->renew;
            $curr_tariff_id[$t->packet->id]['id'] = $t->id;
        }
        try
        {
            $balance = $session->getBalance();
        }
        catch (I24hException $e)
        {
            return ActionFactory::show_error(
                false,
                'Ошибка проверки баланса',
                array('Обратитесь в тех-поддержку.'));
        }

        foreach ($base_srv->available as $dop) {

            if ($dop->id == $media_url->service_id) $srv = $dop;
        }
        if (isset($user_input->control_id)) {
            if ($user_input->control_id == 'handle_enter') {
//                hd_print("curr_tariff_id[media_url->service_id]".print_r($curr_tariff_id[$media_url->service_id],true));
                if (!empty($curr_tariff_id[$media_url->service_id])) {
//                    if ($curr_tariff_id[$media_url->service_id]['renew']) {
                    $ps_arr = array();
                    return $this->get_confirm_dialog_action(
                        $media_url->service_id,
                        $user_input->selected_media_url,
                        'Подтверждение',
                        array
                        (
                            'Вы уверены, что хотите отключить',
//                                'со следующего периода?',
                            'дополнительный пакет: "' . $curr_tariff_id[$media_url->service_id]['name'] . '"?',
                        ),
                        'renew_unsubscribe',
                        true,
                        $ps_arr);
//                    }else{
//                        $ps_arr = array();
//                        return $this->get_confirm_dialog_action(
//                            $media_url->service_id,
//                            $user_input->selected_media_url,
//                            'Подтверждение',
//                            array
//                            (
//                                'Вы уверены, что хотите включить',
////                                'со следующего периода?',
//                                'дополнительный пакет: "' . $curr_tariff_id[$media_url->service_id]['name'] . '"?',
//                            ),
//                            'renew_subscribe',
//                            true,
//                            $ps_arr);
//                    }

                }else {
                    $ps_arr = array();
                    if (empty($balance)){
                        $text = array
                        (
                            'Подтвердите подписку на тариф',
                            '"' . $srv->name . '"',
                            'Стоимость подписки: ' . $srv->price . ' руб. в месяц',
                        );
                    }else{
                        $text = array
                        (
                            'Подтвердите подписку на тариф',
                            '"' . $srv->name . '"',
                            'Текущий баланс: ' . $balance . ' руб',
                            'Стоимость подписки: ' . $srv->price . ' руб. в месяц',
                        );
                    }
                    return $this->get_pay_dialog_action(
                        $media_url->service_id,
                        $user_input->selected_media_url,
                        'Подтверждение',
                        $text,
                        'apply_subscribe',
                        true,
                        $ps_arr);
                }

            } 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);

                return ActionFactory::show_dialog("Состав пакета ТВ-каналов \"$srv->name\"",
                    $defs, true, 1000);
            } else if ($user_input->control_id == 'apply_subscribe') {


                try {
                    $res = $session->addServiceToSubscription(
                        $user_input->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');
                }

            } else if ($user_input->control_id == 'apply_reload') {
                return ActionFactory::open_folder(I24hPrivateScreen::get_media_url_str(''),'Управление тарифами');
            } else if ($user_input->control_id == 'renew_subscribe') {
//                removeServiceFromSubscription
//                if ($session->patchServiceToSubscription($curr_tariff_id[$media_url->service_id]["id"],true)){
                if ($session->removeServiceFromSubscription($curr_tariff_id[$media_url->service_id]["id"])){
                    return ActionFactory::show_error(
                        false,
                        'Внимание!',
                        array('Дополнительный пакет со следующего периода подключен!'));

                }else{
                    return ActionFactory::show_error(
                        false,
                        'Невозможно изменить подписку',
                        array('Обратитесь в тех-поддержку.'));

                }

            } else if ($user_input->control_id == 'renew_unsubscribe') {
                if ($session->removeServiceFromSubscription($curr_tariff_id[$media_url->service_id]["id"])){
//                if ($session->patchServiceToSubscription($curr_tariff_id[$media_url->service_id]["id"],false)){
                    return ActionFactory::show_error(
                        false,
                        'Внимание!',
                        array('Дополнительный пакет со следующего периода отключен!'));

                }else{
                    return ActionFactory::show_error(
                        false,
                        'Невозможно изменить подписку',
                        array('Обратитесь в тех-поддержку.'));

                }
            }
        }
    }

    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 get_confirm_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 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));
    }

}


?>