<?php
class Resourcemanager_live extends Controller
{
    function __construct()
    {
        parent::__construct();

        $this->load->library('session');
        $this->load->model('mresourcemanager');
        $this->load->library('Pagination');
        $this->load->helper('language');
        $this->lang->load('site');
        $this->load->helper('cookie');

        if (!isset($_SESSION['page_lang']))
            $_SESSION['page_lang'] = 'eng';

        if ($this->phpsession->get('access_id') == '' && isset($_COOKIE["access_id"]) && $this->uri->segment(2) != 'logout') {
            $this->phpsession->save('bugtracker_access', true);
            $this->phpsession->save('access_id', $_COOKIE["access_id"]);

            $cookie = array(
                'name'   => 'access_id',
                'value'  => get_cookie('access_id'),
                'expire' => time() + (10 * 365 * 24 * 60 * 60),
            );
            set_cookie($cookie);
        }

        if ($this->phpsession->get('access_id') == '' && $this->uri->segment(2) != 'login' && $this->uri->segment(2) != 'isSessionActive')
            redirect('resourcemanager_live/login');

        if ($this->uri->segment(2) == '')
            redirect('resourcemanager_live/index');

        $this->mresourcemanager->redirectInvalidUrl();
        $this->mresourcemanager->initialiseDb('resourcemanager_live');
    }

    function index()
    {
        if (!isset($_SESSION['page_number']) || !is_numeric($_SESSION['page_number']))
            $_SESSION['page_number'] = 10;

        $_SESSION['partner_id'] = $this->mresourcemanager->getPartnerID($this->uri->segment(3));
        $partner_id = $this->mresourcemanager->getPartnerID($this->uri->segment(3));

        $resData['user']    = $this->mresourcemanager->getSelectedPartner($partner_id);
        $resData['types']   = $this->mresourcemanager->getResourceTypes();

        $this->mresourcemanager->loadTemplate('resourcemanager_live/index.php', $resData, 'Home', true, 'index');
    }

    function reference()
    {
        if (!isset($_SESSION['page_number']) || !is_numeric($_SESSION['page_number']))
            $_SESSION['page_number'] = 10;

        $resData['types'] = $this->mresourcemanager->getResourceTypes();

        $this->mresourcemanager->loadTemplate('resourcemanager_live/admin/reference.php', $resData, 'Reference', true, 'reference');
    }

    function help()
    {
        $resData['help_text'] = $this->mresourcemanager->getHelpText();

        $this->mresourcemanager->loadTemplate('resourcemanager_live/help.php', $resData, 'Help', true, 'help');
    }

    function readData()
    {
        if ($this->phpsession->get('access_id') == '' && isset($_COOKIE["access_id"])) {
            $this->phpsession->save('bugtracker_access', true);
            $this->phpsession->save('access_id', $_COOKIE["access_id"]);
        }

        $url            = $_POST['curr_url'];
        $bestMatch      = '';
        $exact_match    = false;

        $where = $this->mresourcemanager->search($_POST);

        if (isset($_POST['search_name']) && $_POST['search_name'] != '') {
            $bestMatch = $_POST['search_name'];

            if (isset($_POST['extended_search']) && $_POST['extended_search'] == 'on')
                $exact_match = true;
        }

        $records        = isset($_POST['page_number']) ? $_POST['page_number'] : $_SESSION['page_number'];
        $pageSegment    = $_POST['page_segment'];
        $pagination     = new Pagination($records, $pageSegment, $url);
        $partner_id     = $_SESSION['partner_id'];

        if (isset($_POST['ordered_column']) && isset($_POST['order'])) {
            $sorted_table   = $_POST['ordered_column'];
            $sort           = $_POST['order'];
        }

        if ($sorted_table == '' || $sort == '') {
            $sorted_table   = $_SESSION['column'];
            $sort           = $_SESSION['sort'];
        }

        $offset     = $pagination->getOffset();
        $resDatas   = $this->mresourcemanager->getResourceDatas($_SESSION['partner_id'], $_POST['types'], $offset, $records, $where, $bestMatch, $exact_match, false, $sort, $sorted_table);
        $total      = ceil($this->mresourcemanager->getTotalRecords($_SESSION['partner_id'], $where) / $records);

        $_SESSION['page_number'] = $records;

        $pagination->setTotal($total);
        $pagination->setButtons(empty($resDatas));

        $table      = '';
        $paging     = '';
        $redirect   = false;
        $isDisabled = true;

        foreach ($resDatas as $res) {
            $gt_url     = $this->mresourcemanager->getGoogleTranslateUrl($res->ref_id, $partner_id);
            $dpl_url    = $this->mresourcemanager->getDeeplUrl($res->ref_id, $partner_id);
            $txt        = $res->lang_text == null || $res->lang_text == '' ? $res->ref_text : $res->lang_text;
            $ref_txt    = nl2br($res->ref_text);
            $warn_res   = $this->mresourcemanager->get_errors_and_warnings($res->ref_text, $res->lang_text);
            $ref_length = strlen($res->ref_text);
            $res_length = mb_strlen($res->lang_text);
            $cuttedKey  = mb_substr($res->key_id, 0, 20);
            $cuttedKey2 = mb_substr($res->key_id, 20, 40);
            $cuttedKey3 = mb_substr($res->key_id, 40, 60);

            if ($res->to_translate == 1)
                $isDisabled = false;

            $table .= '<tr class="mouse_over" id="' . $res->ref_id . '">';
            $table .= '<td class="col-md-2">';

            $table .= $cuttedKey;
            $table .= '<br/>';
            $table .= $cuttedKey2;
            $table .= '<br/>';
            $table .= $cuttedKey3;

            $table .= '<br/><br/>';

            if (strlen($res->type_name) > 20) {
                $table .= '<a class="type-tooltip" data-id="' . $res->type_id . '"><div class="tooltips info-tooltip">
                        ' . $this->mresourcemanager->cut_string($res->type_name, 20) . '
                        <div class="tooltiptext" style="width: 200px; padding: 20px 0px 20px 20px">' . $res->type_name . '</div>
                    </div></a>';
            } else {
                $table .= '<a class="type-tooltip" data-id="' . $res->type_id . '">
                        ' . $this->mresourcemanager->cut_string($res->type_name, 20) . '
                        </a>';
            }

            $table .= '</td>';

            $table .= '<td class="col-md-4">
                    <div class="col-md-1 counter">
                        <div id="ref_res_counter_' . $res->ref_id . '">' . $ref_length . '</div>
                    </div>
                    <div class="col-md-9">
                        <p style="width: 115%;" id="ref_' . $res->ref_id . '">' . $ref_txt . '</p>
                    </div>';

            $table .= '<div class="col-md-1" style="margin-left: 10px !important;">';

            if ($res->comment != '') {
                $table .= '<div class="tooltips info-tooltip">
                    <img class="context-img" alt="" src="/public/img/resourcemanager/context_filled.png" />
                    <div class="tooltiptext" style="padding: 10px 10px 10px 10px">' . $res->comment . '</div>
                </div>';
            } else {
                $table .= '<div class="tooltips info-tooltip">';

                if ($res->context == 0) {
                    $table .= '<input class="context-img" alt="" id="img_' . $res->ref_id . '" type="image" onclick="showModal(' . $res->ref_id . ')" src="/public/img/resourcemanager/context.png" />
                        <div class="tooltiptext" style="padding: 10px 10px 10px 10px">Click here to provide an optional context - an explanation about when and where on the interface this specific resource will appear. - Context must be written in English.</div>';
                } else {
                    $table .= '<img class="context-img" alt="" src="/public/img/resourcemanager/context_request_filled_qm.png" />
                        <div class="tooltiptext" style="padding: 10px 10px 10px 10px">This resource already has a context requested.</div>';
                }

                $table .= '</div>';
            }

            $table .= '</div>';
            $table .= '</td>';

            $table .= '<td>';
            $table .= '<a href="' . $gt_url . '" title="Google Translate" target="_blank">';
            $table .= '<img alt="" id="ggl_translate" class="logo" src="/public/img/resourcemanager/1024px-Google_Translate_logo.svg_.webp" />';
            $table .= '</a>';

            if (array_key_exists($partner_id, $this->mresourcemanager->deepl_aliases)) {
                $table .= '<a href="' . $dpl_url . '" title="DeepL Translate" target="_blank">';
                $table .= '<img alt="" class="logo right" src="/public/img/resourcemanager/DeepL_Logo_2018.png" />';
                $table .= '</a>';
            }

            $table .= '</td>';

            $table .= '<td><img alt="" class="logo swap-icon" title="Use reference as translation" src="/public/img/resourcemanager/2560px-Arrow_east.svg.png" onclick="changeText(' . $res->ref_id . ')" /></td>';

            $table .= '<td class="col-md-5">
                    <div class="col-md-1 counter" style="margin-left: -15px;">
                        <div id="res_counter_' . $res->res_id . '">' . $res_length . '</div>
                    </div>
                    <div class="col-md-10">
                        <textarea style="width: 315px;" oninput="checkCharacters(' . $res->res_id . ', 1)" id="txt_' . $res->res_id . '" class="form-control dinamic-txt" cols="50" rows="3">' . $txt . '</textarea>
                    </div>';

            $table .= '<div class="col-md-1" style="margin-left: 15px;">';

            if ($warn_res['error'] != '') {
                $table .= '<div id="error_tooltip_' . $res->ref_id . '" class="tooltips error-tooltip">
                        <i class="fa fa-times-circle" style="color: #D9534F;"></i>
                        <div class="tooltiptext"><ul>' . $warn_res['error'] . '</ul></div>
                    </div>';
            }

            if ($warn_res['warning'] != '') {
                $table .= '<div id="warning_tooltip_' . $res->ref_id . '" class="tooltips warning-tooltip">
                        <i class="fa fa-exclamation-triangle" style="color: orange;"></i>
                        <div class="tooltiptext"><ul>' . $warn_res['warning'] . '</ul></div>
                    </div>';
            }
            $table .= '</div>';
            $table .= '</td>';

            $table .= '<td class="col-md-1">';

            if ($res->to_translate == 1)
                $table .= '<button id="save_' . $res->res_id . '" class="btn btn-info save-btn save-ref-btn custom-btn" onclick="save(' . $res->res_id . ')">Save</button>';
            else
                $table .= '<button id="save_' . $res->res_id . '" disabled class="btn grey-btn save-btn save-ref-btn custom-btn" onclick="save(' . $res->res_id . ')">Save</button>';

            $table .= '<button id="undo_' . $res->ref_id . '" disabled class="btn grey-btn reset-btn custom-btn" onclick="resetText(' . $res->ref_id . ')"><i class="fa fa-undo"></i></button>';

            if ($this->mresourcemanager->isAdmin()) {
                if ($res->lang_text !== '' && $res->lang_text !== null) {
                    if ($res->to_translate == 0) {
                        $approved = $res->approved == 0 ? 'disabled' : '';
                        $table .= '<button onclick="reject(' . $res->res_id . ', ' . $res->ref_id . ')" id="reject_' . $res->ref_id . '" class="btn btn-danger reject-btn custom-btn" ' . $approved . '>Reject</button>';
                    }
                }
            }

            $table .= '</td>';
            $table .= '</tr>';
        }

        if (empty($resDatas)) {
            $table      .= '<tr><td colspan="6" style="text-align: center;"><h4>No Result Found</h4></td></tr>';
            $redirect   = true;
        } else {
            $disabled    = $pagination->pageno <= 1 ? 'disabled' : '';
            $disabled2   = $pagination->pageno >= $pagination->total ? 'disabled' : '';
            $total       = '<br/> Total pages: ' . $pagination->total;

            $paging .= '<li><a href="' . $pagination->first_btn . '">First</a></li>';
            $paging .= '<li class="' . $disabled . '"> <a href="' . $pagination->back_btn . '">Prev</a></li>';

            for ($i = $pagination->prev_page; $i <= $pagination->next_page; $i++) {
                $active = $i == $pagination->pageno ? 'active' : '';
                $paging .= '<li class="' . $active . '"><a href="' . $pagination->pageURL . '/' . $i . '">' . $i . '</a></li>';
            }

            $paging .= '<li class="' . $disabled2 . '"><a href="' . $pagination->next_btn . '">Next</a></li>';
            $paging .= '<li><a href="' . $pagination->total_btn . '">Last</a></li>';
        }

        $response['isDisabled'] = $isDisabled;
        $response['table']      = $table;
        $response['pagination'] = $paging;
        $response['total']      = $total;
        $response['redirect']   = $redirect;

        echo json_encode($response);
    }

    function readRefData()
    {
        if ($this->mresourcemanager->isAdmin()) {
            $url            = $_POST['curr_url'];
            $bestMatch      = '';
            $exact_match    = false;

            $where = $this->mresourcemanager->search($_POST);

            if (isset($_POST['search_name']) && $_POST['search_name'] != '') {
                $bestMatch = $_POST['search_name'];

                if (isset($_POST['extended_search']) && $_POST['extended_search'] == 'on')
                    $exact_match = true;
            }

            $records        = isset($_POST['page_number']) ? $_POST['page_number'] : $_SESSION['page_number'];
            $pageSegment    = $_POST['page_segment'];
            $pagination     = new Pagination($records, $pageSegment, $url);

            if (isset($_POST['ordered_column']) && isset($_POST['order'])) {
                $sorted_table   = $_POST['ordered_column'];
                $sort           = $_POST['order'];
            }

            if ($sorted_table == '' || $sort == '') {
                $sorted_table   = $_SESSION['column'];
                $sort           = $_SESSION['sort'];
            }

            $offset     = $pagination->getOffset();
            $refDatas   = $this->mresourcemanager->getResourceDatas(36, $_POST['types'], $offset, $records, $where, $bestMatch, $exact_match, true, $sort, $sorted_table);
            $total      = ceil($this->mresourcemanager->getTotalRecords(36, $where, true) / $records);

            $_SESSION['page_number'] = $records;

            $pagination->setTotal($total);
            $pagination->setButtons(empty($resDatas));

            $table      = '';
            $paging     = '';
            $total      = '';
            $redirect   = false;
            $isDisabled = true;

            foreach ($refDatas as $ref) {
                $ref_key    = "'" . $ref->key_id . "'";
                $gt_url     = $this->mresourcemanager->getGoogleTranslateUrl($ref->ref_id, 36);
                $dpl_url    = $this->mresourcemanager->getDeeplUrl($ref->ref_id, 36);
                $warn_res   = $this->mresourcemanager->get_errors_and_warnings($ref->ref_text, $ref->lang_text);
                $ref_length = strlen($ref->ref_text);
                $res_length = mb_strlen($ref->lang_text);
                $cuttedKey  = substr($ref->key_id, 0, 21);
                $cuttedKey2 = substr($ref->key_id, 21, 31);
                $cuttedKey3 = substr($ref->key_id, 31, 60);

                if ($ref->to_translate == 1)
                    $isDisabled = false;

                $table .= '<tr id="' . $ref->ref_id . '" class="data-row">';
                $table .= '<td class="col-md-1">';
                $table .= '<button class="btn btn-danger delete-ref-btn" onclick="deleteRef(' . $ref->ref_id . ', ' . $ref_key . ')"><i class="fa fa-trash"></i></button>';
                $table .= '</td>';
                $table .= '<td class="col-md-1">';
                $table .= $cuttedKey;

                if ($cuttedKey2 != '')
                    $table .= '<div style="width: 10px !important;">' . $cuttedKey2 . '</div>';

                if ($cuttedKey3 != '')
                    $table .= '<div style="width: 10px !important;">' . $cuttedKey3 . '</div>';

                $table .= '<br/><br/>';

                if (strlen($ref->type_name) > 20) {
                    $table .= '<a class="type-tooltip" data-id="' . $ref->type_id . '"><div class="tooltips info-tooltip">
                            ' . $this->mresourcemanager->cut_string($ref->type_name, 20) . '
                            <div class="tooltiptext" style="width: 200px; padding: 20px 0px 20px 20px">' . $ref->type_name . '</div>
                        </div></a>';
                } else {
                    $table .= '<a class="type-tooltip" data-id="' . $ref->type_id . '">
                            ' . $this->mresourcemanager->cut_string($ref->type_name, 20) . '
                            </a>';
                }

                if ($ref->type_id > 3) {
                    $table .= '<br/><br/>';

                    $table .= '<select id="alternative_' . $ref->ref_id . '" class="form-control alt_select" onchange="changeAlt(' . $ref->ref_id . ')" style="margin-left: -40px; width: 150px;">';
                    $table .= '<option value="ref">Alternatives</option>';

                    if ($ref->defines != '') {
                        $json = json_decode($ref->defines);

                        $alternatives = array_filter($json->defines, function ($define) {
                            return $define->lang == 'hun';
                        });

                        if (!empty($alternatives)) {
                            foreach ($alternatives as $alternative) {
                                $table .= '<option value="' . $alternative->ext_key . '">' . $alternative->ext_key . '</option>';
                            }
                        }
                    }

                    $table .= '<option value="add_alt">Add new alternative</option>';
                    $table .= '</select>';
                }

                $table .= '</td>';
                $table .= '<td class="col-md-5">
                        <div class="col-md-1 counter">
                            <div id="ref_counter_' . $ref->ref_id . '">' . $ref_length . '</div>
                        </div>
                        <div class="col-md-9">
                            <div class="highlights"></div>
                            <input type="hidden" id="txt_ref_val_' . $ref->ref_id . '" value="' . $ref->ref_text . '" />
                            <textarea oninput="checkCharacters(' . $ref->ref_id . ', 0)" id="txt_ref_' . $ref->ref_id . '" class="form-control dinamic-txt" cols="50" rows="3">' . $ref->ref_text . '</textarea>
                        </div>';

                $table .= '<div class="col-md-1" style="margin-left: -20px !important;">';
                if ($ref->comment != '') {
                    $table .= '<div class="tooltips info-tooltip">
                            <input class="context-img" alt="" id="img_' . $ref->ref_id . '" type="image" onclick="showModal(' . $ref->ref_id . ')" src="/public/img/resourcemanager/context_filled.png" />
                            <div class="tooltiptext" style="padding: 10px 10px 10px 10px">Click here to provide an optional context - an explanation about when and where on the interface this specific resource will appear. - Context must be written in English.</div>
                        </div>';
                } else {
                    if ($ref->context == 0)
                        $img = 'context.png';
                    else
                        $img = 'context_request_filled_qm.png';

                    $table .= '<div class="tooltips info-tooltip">
                            <input class="context-img" alt="" id="img_' . $ref->ref_id . '" type="image" onclick="showModal(' . $ref->ref_id . ')" src="/public/img/resourcemanager/' . $img . '" />
                            <div class="tooltiptext" style="padding: 10px 10px 10px 10px">Click here to provide an optional context - an explanation about when and where on the interface this specific resource will appear. - Context must be written in English.</div>
                        </div>';
                }
                $table .= '</div>';
                $table .= '</td>';

                $table .= '<td class="col-md-1">';
                $table .= '<a href="' . $gt_url . '" title="Google Translate" target="_blank">';
                $table .= '<img alt="" id="ggl_translate" class="logo" src="/public/img/resourcemanager/1024px-Google_Translate_logo.svg_.webp" />';
                $table .= '</a> &nbsp;';
                $table .= '<a href="' . $dpl_url . '" title="DeepL Translate" target="_blank">';
                $table .= '<img alt="" class="logo" src="/public/img/resourcemanager/DeepL_Logo_2018.png" />';
                $table .= '</a>';
                $table .= '<td class="col-md-4">
                        <div class="col-md-1 counter" style="margin-left: -10px">
                            <div id="res_counter_' . $ref->ref_id . '">' . $res_length . '</div>
                        </div>
                        <div class="col-md-10">
                        <input type="hidden" id="txt_val_' . $ref->ref_id . '" value="' . $ref->ref_text . '" />
                            <textarea oninput="checkCharacters(' . $ref->ref_id . ', 1)" id="txt_' . $ref->ref_id . '" class="form-control dinamic-txt">' . $ref->lang_text . '</textarea>
                        </div>';

                $table .= '<div class="col-md-1" style="margin-left: -20px !important;">';

                if ($warn_res['error'] != '') {
                    $table .= '<div id="error_tooltip_' . $ref->ref_id . '" class="tooltips error-tooltip">
                            <i class="fa fa-times-circle" style="color: #D9534F;"></i>
                            <div class="tooltiptext"><ul>' . $warn_res['error'] . '</ul></div>
                        </div>';
                }

                if ($warn_res['warning'] != '') {
                    $table .= '<div id="warning_tooltip_' . $ref->ref_id . '" class="tooltips warning-tooltip">
                            <i class="fa fa-exclamation-triangle" style="color: orange;"></i>
                            <div class="tooltiptext"><ul>' . $warn_res['warning'] . '</ul></div>
                        </div>';
                }
                $table .= '</div>';

                $table .= '</td>';

                $table .= '<td class="col-md-1">';

                if ($ref->to_translate == 1)
                    $table .= '<button id="save_' . $ref->ref_id . '" class="btn btn-info save-btn save-ref-btn custom-btn" onclick="saveRef(' . $ref->ref_id . ')">Save</button>';
                else
                    $table .= '<button id="save_' . $ref->ref_id . '" disabled class="btn grey-btn save-btn save-ref-btn custom-btn" onclick="saveRef(' . $ref->ref_id . ')">Save</button>';

                $table .= '<button id="undo_' . $ref->ref_id . '" disabled class="btn grey-btn reset-btn custom-btn" onclick="resetText(' . $ref->ref_id . ')"><i class="fa fa-undo"></i></button>';
                $table .= '</td>';
                $table .= '</tr>';
            }

            if (empty($refDatas)) {
                $table .= '<tr><td colspan="6" style="text-align: center;"><h4>No Result Found</h4></td></tr>';
                $redirect = true;
            } else {
                $disabled   = $pagination->pageno <= 1 ? 'disabled' : '';
                $disabled2  = $pagination->pageno >= $pagination->total ? 'disabled' : '';
                $total      = '<br/> Total pages: ' . $pagination->total;

                $paging .= '<li><a href="' . $pagination->first_btn . '">First</a></li>';
                $paging .= '<li class="' . $disabled . '"> <a href="' . $pagination->back_btn . '">Prev</a></li>';

                for ($i = $pagination->prev_page; $i <= $pagination->next_page; $i++) {
                    $active = $i == $pagination->pageno ? 'active' : '';
                    $paging .= '<li class="' . $active . '"><a href="' . $pagination->pageURL . '/' . $i . '">' . $i . '</a></li>';
                }

                $paging .= '<li class="' . $disabled2 . '"><a href="' . $pagination->next_btn . '">Next</a></li>';
                $paging .= '<li><a href="/resourcemanager/reference/' . $pagination->total . '">Last</a></li>';
            }

            $response['isDisabled'] = $isDisabled;
            $response['table']      = $table;
            $response['pagination'] = $paging;
            $response['total']      = $total;
            $response['redirect']   = $redirect;
            $response['asd'] = $_SESSION['query_test'];
        } else {
            $response = array();
        }

        echo json_encode($response);
    }
}
