<?php

namespace App\Http\Controllers;

use App;
use File;
use Request;

class TranslationController extends Controller
{


    protected $languagesPath;
    protected $directory_separator;
    protected $from;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

        $this->directory_separator = DIRECTORY_SEPARATOR;
        $this->languagesPath = App::langPath();

    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return redirect('admin/translate/all/edit/de');
    }


    /**
     * @param $language
     * @param string $from
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function edit($language, $from = 'en')
    {
        $localisations = array_keys(config('localization.supportedLocales'));
        $files = $this->json_files($localisations);
        $translations = $this->translationsJson($language, $from);
        $show = "all";
        return view('translation.index', compact('files','translations', 'language', 'from', 'show'));
    }


    /**
     * @param $lang
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function update($language)
    {


        $path = $this->resourcePath($this->languagesPath);
        $file = $path.$language.".json";
        $data = Request::all();
        $this->backup($path, $language.".json");
        unset($data['_token']);

            $ret = [];
            //file make keys
            $source = json_decode(File::get($path."de.json"));
            foreach ($source as $key => $v){
               $skey = $this->sanitize($key);
               if(!empty($data[$skey])) {
                   $ret[$key] = $data[$skey];
               }
            }
        $jsonData = json_encode($ret, TRUE);
        file_put_contents($file, $jsonData);
        return redirect()
            ->route('admin_translate_all_edit', [$language])
            ->with('message', 'Translation added successfully');
    }

    /**
     * @param $langs
     * @return array
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function json_files($localisations){
        $path = $this->resourcePath($this->languagesPath);
        $content = array();
        foreach ($localisations as $local){
            $file = File::get($path.$local.".json");
            if($file){
                $content[$local] = array('path'=>$path.$local.".json", 'content'=>json_encode($file));
            }
        }
        return $content;


    }

    /**
     * @param $language
     * @param $from
     * @return array
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function translationsJson($language, $from)
    {
        $path = $this->resourcePath($this->languagesPath);
        $file = array();
        $file['keys'] = (array) json_decode(File::get($path."de.json"));
        $file['keys'] = $this->sanitizeKey($file['keys']);
        $file['from'] = (array) json_decode(File::get($path.$from.".json"));
        $file['from'] = $this->sanitizeKey($file['from']);
        $file['dest'] = (array) json_decode(File::get($path.$language.".json"));
        $file['dest'] = $this->sanitizeKey($file['dest']);

        return $file;
    }

    private function backup($path, $file)
    {

        if (!File::exists(storage_path('language/'))) {
            File::makeDirectory(storage_path('language/'), 0755, true);
        }

        return File::copy($path.$file, storage_path('language/'.time()."-".$file));
    }

    /**
     * @param $path
     * @return string
     */
    protected function resourcePath($path)
    {
        return "{$path}{$this->directory_separator}";
    }

    /**
     * @param $arr
     * @return mixed
     */
    protected function sanitizeKey($arr){
        foreach ($arr as $key => $val){
            unset($arr[$key]);
            $arr[$this->sanitize($key)] = $val;
        }
        return $arr;

    }

    /**
     * @param $string
     * @param bool $force_lowercase
     * @param bool $anal
     * @return mixed|null|string|string[]
     */
    protected function sanitize($string, $force_lowercase = true, $anal = false)
    {
        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
            "}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
            "â€”", "â€“", ",", "<", ".", ">", "/", "?");
        $clean = trim(str_replace($strip, "", strip_tags($string)));
        $clean = preg_replace('/\s+/', "_", $clean);
        $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;

        return ($force_lowercase) ?
            (function_exists('mb_strtolower')) ?
                mb_strtolower($clean, 'UTF-8') :
                strtolower($clean) :
            $clean;
    }

}
