<?php

namespace Server\language\web;

use Server\language\LanguageService;

class LocalesController extends LanguageService {

    public function main(){
        return $this->View([
            'title'=>__('lang.languages'),
            'locale'=>$this->appLocale,
            'languages'=>$this->getLanguages(),
            'systemLocales'=>$this->systemLocales
        ]);
    }

    public function setup(){
        $locale = request()->input('id', "");
        if ($locale==$this->appLocale) return $this->success("successful", referer());
        global $_W;
        if (!$_W['setting']['languages'][$locale]){
            return $this->message('lang.invalidLocale');
        }
        if ($this->langSwitch($locale)){
            return $this->success("successful", referer());
        }
        return $this->message('operationFailed');
    }

    public function remove(){
        $locale = request()->input('id', "");
        if (empty($locale)) return $this->message('lang.invalidLocale');
        $languages = $this->langScan($locale);
        if (!empty($languages)){
            return $this->message('lang.removeLocaleNotify');
        }
        if (!pdo_delete('languages', array('code'=>$locale))){
            return $this->message('operationFailed');
        }
        return $this->success("successful", $this->url('locales'));
    }

    public function post(){
        $locale = request()->input('id', "");
        $language = null;
        if (!empty($locale)){
            $language = pdo_get("languages", array('code'=>$locale));
        }
        if (checksubmit()){
            $data = post_var(array('name', 'country', 'status'), request()->input('data'));
            if (empty($data['name'])) return $this->message('lang.packageNamePlaceholder');
            if (empty($data['country'])) return $this->message('lang.countryPlaceholder');
            $data['status'] = intval($data['status']);
            if ($this->appLocale==$locale){
                $data['status'] = 1;
            }
            if ($language){
                pdo_update('languages', $data, array('code'=>$language['code']));
            }else{
                if (empty($locale)) return $this->message('lang.invalidLocale');
                $data['code'] = $locale;
                pdo_insert('languages', $data);
            }
            return $this->success("successful", referer());
        }
        return $this->View(array(
            'title'=>$language?__('modifyData', array('data'=>__('lang.locale'))):__('newData', array('data'=>__('lang.locale'))),
            'locale'=>$locale,
            'appLocale'=>$this->appLocale,
            'language'=>$language?:[]
        ), 'localePost');
    }

}
