<?php

use idoit\Component\Logger;

/**
 * i-doit
 *
 * Popup for JDisc profile duplication
 *
 * @package     i-doit
 * @subpackage  Popups
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class isys_popup_duplicate_jdisc_profile extends isys_component_popup
{
    /**
     * Instance of module DAO.
     *
     * @var  isys_jdisc_dao
     */
    protected $m_dao;

    /**
     * Handles Smarty inclusion.
     *
     * @global  array                   $g_config
     *
     * @param   isys_component_template $p_tplclass (unused)
     * @param   mixed                   $p_params   (unused)
     *
     * @return  string
     */
    public function handle_smarty_include(isys_component_template $p_tplclass, $p_params)
    {
        // This is never used - the popup will directly be triggered via JS callback.
        return '';
    }

    /**
     * Handles module request.
     *
     * @param   isys_module_request $p_modreq
     *
     * @return  isys_component_template
     */
    public function &handle_module_request(isys_module_request $p_modreq)
    {
        try {
            $l_posts = $p_modreq->get_posts();
            if (!isset($l_posts['id']) || !is_array($l_posts['id']) || count($l_posts['id']) === 0) {
                throw new Exception($this->language->get('LC__MODULE__JDISC__POPUP__ERROR__NO_SELECTED_PROFILE'));
            }

            $l_ids = array_map('intval', $l_posts['id']);

            $l_selections = [
                'id',
                'title'
            ];

            $l_all_profiles = isys_jdisc_dao::instance($this->database, new Logger('JDisc Duplicate'))->get_profiles($l_selections);
            $l_profiles = [];

            foreach ($l_all_profiles as $l_profile) {
                if (in_array($l_profile['id'], $l_ids)) {
                    $l_profiles[] = [
                        'id'    => 'C__PROFILE__' . $l_profile['id'],
                        'title' => $l_profile['title']
                    ];
                }
            }

            if (count($l_profiles) === 0) {
                throw new isys_exception_general('No profile found.');
            }

            $this->template->assign('profiles', $l_profiles);
        } catch (Exception $e) {
            $this->template->assign('error', $e->getMessage());
        }

        $this->template
            ->activate_editmode()
            ->display(isys_module_synetics_jdisc::getPath() . 'templates/popup/duplicate_jdisc_profile.tpl');
        die;
    }
}
