<?php

namespace Dashboard\Controllers\Settings;

use Dashboard\Core\Controller;
use PDO;

class LanguageController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_SETTINGS');
    }

    public function index()
    {
        $languages = db()->query("SELECT * FROM Languages");
        $languages = $languages->fetchAll(PDO::FETCH_ASSOC);

        return view('settings.languages.index', compact('languages'));
    }

    public function create()
    {
        return view('settings.languages.create');
    }

    public function store()
    {
        validate([
            'languageCode' => 'required',
            'languageName' => 'required',
        ]);

        $insertLanguages = db()->prepare("INSERT INTO Languages (code, name) VALUES (?, ?)");
        $insertLanguages->execute(array(input("languageCode"), input("languageName")));

        if (!file_exists(__ROOT__ . "/apps/main/app/languages/" . input("languageCode") . ".json")) {
            $defaultFile = file_get_contents(__ROOT__ . "/apps/main/app/languages/en.json");
            file_put_contents(__ROOT__ . '/apps/main/app/languages/' . input("languageCode") . '.json', $defaultFile);
        }

        createLog("LANGUAGE_ADDED");
        return back()->flash('success', t__('Language has been added successfully!'));
    }

    public function edit($id)
    {
        $language = db()->prepare("SELECT * FROM Languages WHERE code = ?");
        $language->execute(array($id));
        $language = $language->fetch();

        if (!$language) return view('404');

        $languageFile = __ROOT__ . '/apps/main/app/languages/' . $language["code"] . '.json';
        $themeLanguageFile = themePath(true) . '/languages/' . $language["code"] . '.json';

        $customTranslates = db()->prepare("SELECT `key`, `value` FROM CustomTranslate WHERE language = ?");
        $customTranslates->execute(array($language["code"]));
        $customTranslateArray = $customTranslates->fetchAll(PDO::FETCH_ASSOC);

        return view('settings.languages.edit', compact('language', 'languageFile', 'themeLanguageFile', 'customTranslateArray'));
    }

    public function update($id)
    {
        $language = db()->prepare("SELECT * FROM Languages WHERE code = ?");
        $language->execute(array($id));
        $readLanguage = $language->fetch();

        $languageFile = __ROOT__ . '/apps/main/app/languages/' . $readLanguage["code"] . '.json';
        $themeLanguageFile = themePath(true) . '/languages/' . $readLanguage["code"] . '.json';

        $customTranslates = db()->prepare("SELECT `key`, `value` FROM CustomTranslate WHERE language = ?");
        $customTranslates->execute(array($readLanguage["code"]));
        $customTranslateArray = $customTranslates->fetchAll(PDO::FETCH_ASSOC);

        validate([
            'languageName' => 'required',
        ]);

        $updateLanguages = db()->prepare("UPDATE Languages SET name = ? WHERE code = ?");
        $updateLanguages->execute(array(input("languageName"), $readLanguage["code"]));

        $languageContent = json_decode(file_get_contents($languageFile), true);
        $themeLanguageContent = json_decode(file_get_contents($themeLanguageFile), true);

        foreach ($_POST["languageKeys"] as $postIndex => $key) {
            $value = $_POST["languageValues"][$postIndex];
						
						$isTranslated = in_array($key, array_column($customTranslateArray, 'key'));

            if ($languageContent[$key] == $value && !$isTranslated)
                continue;
            if (!$isTranslated) {
                $insertCustomTranslate = db()->prepare("INSERT INTO CustomTranslate (`language`, `key`, `value`) VALUES (?, ?, ?)");
                $insertCustomTranslate->execute(array($readLanguage["code"], $key, $value));
            } else {
                $updateCustomTranslate = db()->prepare("UPDATE CustomTranslate SET `value` = ? WHERE language = ? AND `key` = ?");
                $updateCustomTranslate->execute(array($value, $readLanguage["code"], $key));
            }
        }

        foreach ($_POST["theme_languageKeys"] as $postIndex => $key) {
            $value = $_POST["theme_languageValues"][$postIndex];

            if ($themeLanguageContent[$key] == $value)
                continue;
            if (!in_array($key, array_column($customTranslateArray, 'key'))) {
                $insertCustomTranslate = db()->prepare("INSERT INTO CustomTranslate (`language`, `key`, `value`) VALUES (?, ?, ?)");
                $insertCustomTranslate->execute(array($readLanguage["code"], $key, $value));
            } else {
                $updateCustomTranslate = db()->prepare("UPDATE CustomTranslate SET `value` = ? WHERE language = ? AND `key` = ?");
                $updateCustomTranslate->execute(array($value, $readLanguage["code"], $key));
            }
        }
        createLog("LANGUAGE_UPDATED");

        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

    public function destroy($id)
    {
        if (settings("language") != $id) {
            $deleteLanguage = db()->prepare("DELETE FROM Languages WHERE code = ?");
            $deleteLanguage->execute(array($id));
        }
        return back();
    }

    public function set($id)
    {
		    $language = db()->prepare("SELECT * FROM Languages WHERE code = ?");
		    $language->execute(array($id));
		    $language = $language->fetch();
		    
		    if (!$language) return view('404');
				
				// Prevent setting the disabled language as default
				if ($language['isActive'] == 0) return back();
				
        $setLanguage = db()->prepare("UPDATE Settings SET value = ? WHERE name = ?");
        $setLanguage->execute(array($id, "language"));

        createLog("LANGUAGE_UPDATED");

        return back();
    }

  public function toggle($id)
  {
    $language = db()->prepare("SELECT * FROM Languages WHERE code = ?");
    $language->execute(array($id));
    $language = $language->fetch();
	  
	  if (!$language) return view('404');
		
		// Prevent disabling the default language
    if ($language['code'] == settings('language') && $language['isActive'] == '1') {
      return back()->flash('error', t__('You cannot disable the default language!'));
    }

    $updateLanguage = db()->prepare("UPDATE Languages SET isActive = ? WHERE code = ?");
    $updateLanguage->execute(array($language['isActive'] == '0' ? '1' : '0', $id));

    createLog("LANGUAGE_UPDATED");

    return back()->flash('success', t__('Changes has been saved successfully!'));
  }
}