<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}


use Mnv\Core\AdminMnv;
use Mnv\Core\JSONParser\JSONFactory;

/**
 * Class TranslationsAdmin
 * @package Mnv\Admin\Controllers
 */
class TranslationsAdmin extends AdminMnv
{

    protected $template;
    protected $jsonFile;

    private $translations;
    private $translationId;
    private $defaultLang = '';

    private $draw;
    private $start;
    private $length;
    private $search;
    private $searchValue;
    private $columnName;
    private $columnSortOrder;

    private $index;
    private $name;
    private $value;
    private $langCode;

    public $flags;


    public function fetch()
    {
        $this->smarty->assign('activeItem','translations');
        $this->smarty->assign('title', lang('translations:name'));
        $this->jsonFile = new JSONFactory('JSON');

        /* table list */

        $this->draw     = $this->request->get('draw', '1');
        $this->start    = $this->request->get('start', 0);
        $this->length   = $this->request->get('length', 10); //getRequestVar('length', '10');
        $this->search	= $this->request->get('search', '0'); // getRequestVar('search', '');

        $this->searchValue = $this->request->get('search', ''); // getRequestVar('search'); //$_POST['search']['value'];

        $this->columnName = $this->request->get('columns', 0); //getRequestVar('columns'); //$_POST['columns'][$columnIndex]['data'];
        $this->columnSortOrder = $this->request->get('order', '');// $_POST['order'][0]['dir'];


        $this->action = $this->request->get('action', 'read'); //getRequestVar('action', 'read');
        $this->translations = $this->request->get('translations', ''); //getRequestVar('translations', '', $noEscape = true);
        $this->translationId = $this->request->get('id', 1); // getRequestVar('id', '1');

        $this->index = $this->request->get('index', ''); //getRequestVar('index', '');
        $this->name = $this->request->get('name', ''); // getRequestVar('name', '');
        $this->value = $this->request->get('value', ''); // getRequestVar('value', '');
        $this->langCode = $this->request->get('langCode', ''); // getRequestVar('langCode', '');

        $LANGUAGES = include GLOBAL_ROOT . '/includes/global-languages.inc.php';
        foreach ($LANGUAGES as $language) {
            if ($language['isDefault'] == 1) {
                $this->defaultLang = $language['codename'];
            }
        }

        if ($languages = connect()->table('languages')->getAll('array')) {
            foreach ($languages as $language) {
                $this->flags[$language['languageId']]         = $language;
                $this->flags[$language['languageId']]['image']  = GLOBAL_URL . '/admin/assets/flags/' . $language['codename'] . '.svg';
            }
        }

        switch ($this->action) {
            case 'add_row':
                if (empty($this->langCode)) $this->langCode = $this->defaultLang;
                $this->jsonFile->parser->loadFile(GLOBAL_ROOT . '/includes/languages/' . $this->langCode . '.json');

                $this->jsonFile->convertTo('JSON');
                $this->jsonFile->writer->addRow(['name' => $this->name, 'value' => $this->value], false);
                $this->jsonFile->writer->saveFile($this->langCode, GLOBAL_ROOT . '/includes/languages/'.$this->langCode.'.json');

                $response = array("code" => 200);
                response()->json($response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
                break;
            case 'edit_row':

                $this->jsonFile->parser->loadFile(GLOBAL_ROOT . '/includes/languages/' . $this->langCode . '.json');
                $this->jsonFile->parser->getRow($this->index);

                $this->jsonFile->convertTo('JSON');
                $this->jsonFile->writer->editRow($this->index, ['name' => $this->name, 'value' => $this->value]);
                $this->jsonFile->writer->saveFile($this->langCode, GLOBAL_ROOT . '/includes/languages/'.$this->langCode.'.json');

                $response = array("code" => 200, "data" => array("index" => $this->index, 'name' => $this->name, 'value' => $this->value, 'langCode' => $this->langCode));
                response()->json($response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
                break;
            case 'delete_row':

                $this->jsonFile->parser->loadFile(GLOBAL_ROOT . '/includes/languages/' . $this->langCode . '.json');
                $this->jsonFile->parser->getRow($this->index);

                $this->jsonFile->convertTo('JSON');
                $this->jsonFile->writer->deleteRow($this->index);
                $this->jsonFile->writer->saveFile($this->langCode, GLOBAL_ROOT . '/includes/languages/'.$this->langCode.'.json');

                $response = array("code" => 200);
                response()->json($response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();


                break;
            case 'read_table':

                if (!empty($this->translationId)) {
                    $response = $this->readTable($this->translationId, $this->searchValue['value']);
                     // print_r($response);
                    response()->json($response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
                }
                break;

            default:
                break;
        }

        if (!empty($this->flags)) {
            $this->smarty->assign('flags', $this->flags);
        }
        if (!empty($this->translationId)) {
            $this->smarty->assign('id', $this->translationId);
        }
        if (!empty($this->action)) {
            $this->smarty->assign('action', $this->action);
        }

        if ($this->permissions('translations')) {
            return  $this->smarty->fetch('views/translations/translations.tpl');
        }

        $this->smarty->assign('title', lang('general:accessIsDenied'));
        return  $this->smarty->fetch('accessIsDenied.tpl');

    }


    private function readTable($translationId, $searchValue = null)
    {
        $file = array();
        $language = connect()->table('languages')->where('languageId', '=', $translationId)->get();

        $this->jsonFile->parser->loadFile(GLOBAL_ROOT . '/includes/languages/' . $language->codename . '.json');
        if ($getFile = $this->jsonFile->parser->getField()) {
            foreach ($getFile as $key => $value) {
                if (!empty($value)) {
                   if ($searchValue) {
                       if ((strpos($value['name'], $searchValue) !== false) || strpos($value['value'], $searchValue) !== false) {
                           $file[$key]['name']      = $value['name'];
                           $file[$key]['value']     = $value['value'];
                           $file[$key]['index']     = $key;
                           $file[$key]['langCode']  = $language->codename;
                       }
                   } else {
                       $file[$key]['name']      = $value['name'];
                       $file[$key]['value']     = $value['value'];
                       $file[$key]['index']     = $key;
                       $file[$key]['langCode']  = $language->codename;
                   }
                }
            }
            $response = array(
                "langCode"          => $language->codename,
                "draw"              => intval($this->draw),
                "recordsTotal"      => count($file),
                "recordsFiltered"   => count($file),
                "data"              => array_slice($file, $this->start, $this->length),
                "code"              => 200
            );

        } else {
            $response = array("draw" => intval($this->draw), "recordsTotal" => 0, "recordsFiltered" => 0, "data" => [], "code" => 200);
        }


        return $response;


    }


    /***************** FUNCTIONS ****************/

}