<?php

namespace Dashboard\Controllers\Settings;

use Dashboard\Core\Controller;
use Verot\Upload\Upload;

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

    public function index()
    {
        return view('settings.general.index');
    }

    public function update()
    {
        if (input()->file('favicon')->size) {
            $upload = new Upload($_FILES["favicon"]);
            $imageID = md5(uniqid(rand(0, 9999)));
            if ($upload->uploaded) {
                $upload->file_overwrite = true;
                $upload->file_new_name_body = "favicon";
                $upload->image_convert = "png";
                $upload->image_resize = true;
                $upload->image_ratio_crop = true;
                $upload->image_x = 64;
                $upload->image_y = 64;
                $upload->process(__ROOT__ . "/apps/main/public/");
                if (!$upload->processed) {
                    return back()->flash('error', t__('An error occupied while uploading an image: %error%', ['%error%' => $upload->error]));
                }
            }
        }

        if (substr(input("websiteURL"), -1) == '/') {
            set_input("websiteURL", substr(input("websiteURL"), 0, -1));
        }

        foreach ($_POST as $key => $value) {
						if ($key == "about") {
							$value = filteredContent($_POST[$key]);
							if ($value == "<p>&nbsp;</p>") {
								$value = "";
							}
						} else {
              $value = input($key);
            }

            $updateSettings = db()->prepare("UPDATE Settings SET value = ? WHERE name = ?");
            $updateSettings->execute([$value, $key]);
        }

        $updateSettings = db()->prepare("UPDATE Settings SET value = ? WHERE name = ?");
        $updateSettings->execute(array(time(), "updatedAt"));
        createLog("GENERAL_SETTINGS_UPDATED");

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

    }
}