<?php

namespace App\Controllers\System;

use App\Controllers\Controller;
use App\Lib\Config;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Respect\Validation\Validator as v;

class SettingsController extends Controller
{
    public function index(Request $request, Response $response){
        $data =[
            'APP_NAME'=>envi('APP_NAME') ?? 'Cpanel Email Manager',
            'CPANEL_DOMAIN'=>envi('CPANEL_DOMAIN'),
            'CPANEL_USERNAME'=>envi('CPANEL_USERNAME'),
            'CPANEL_PASSWORD'=>decrypt(envi('CPANEL_PASSWORD')),
            'CPANEL_QUOTA'=>envi('CPANEL_QUOTA'),
        ];
        return view($response,'system/settings/index.twig',compact('data'));
    }

    /**
     * @param Request $request
     * @param Response $response
     */
    public function update(Request $request, Response $response){
        $data = $request->getParsedBody();
        $validation = $this->validator->validate($request, [
            'CPANEL_DOMAIN' => v::notEmpty()->stringType(),
            'CPANEL_USERNAME' => v::notEmpty()->stringType(),
            'CPANEL_PASSWORD' => v::notEmpty()->stringType(),
        ]);
        if ($validation->failed()) {
            redirect()->route('settings');
        }else{
            $data =[
                'APP_NAME'=>env('APP_NAME') ?? 'Cpanel Email Manager',
                'CPANEL_DOMAIN'=>post('CPANEL_DOMAIN'),
                'CPANEL_USERNAME'=>post('CPANEL_USERNAME'),
                'CPANEL_PASSWORD'=>post('CPANEL_PASSWORD'),
                'CPANEL_QUOTA'=>post('CPANEL_QUOTA')
            ];
            $apiKey = envi('AUTH_KEY');
            if(Config::appSettings($data,$apiKey)){
                redirect()->route('settings')->with('success', 'Settings updated');
            }else{
                redirect()->route('settings')->with('error', 'Settings not updated');
            }
        }

    }
}