<?php
namespace App\Controllers;

use App\Auth\Auth;
use App\Controllers\Controller;
use App\Lib\Datatable;
use App\Lib\HmailAPI;
use App\Lib\Reporting;
use App\Models\User;
use Delight\Auth\InvalidEmailException;
use Delight\Auth\InvalidPasswordException;
use Delight\Auth\Role;
use Delight\Auth\UnknownIdException;
use Delight\Auth\UserAlreadyExistsException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Respect\Validation\Validator as v;

class CPEmailController extends Controller
{
    /**
     * @param Request $request
     * @param Response $response
     * @return mixed
     * @throws \DI\DependencyException
     * @throws \DI\NotFoundException
     */
    public function index(Request $request, Response $response)
    {
        $email = get('email');
        $domain = envi('CPANEL_DOMAIN');
        $quotasize = envi('CPANEL_QUOTA');
        $emails = HmailAPI::listEmails();
        $emails = $emails['data'];
        return view($response,'cpemail/index.twig', compact('emails','domain','quotasize'));
    }


    /**
     * @param Request $request
     * @param Response $response
     * @return mixed
     * @throws \DI\DependencyException
     * @throws \DI\NotFoundException
     */
    public function create(Request $request, Response $response){
        $domain = envi('CPANEL_DOMAIN');
        $quotasize = envi('CPANEL_QUOTA');
        return view($response,'cpemail/create.twig',compact('domain','quotasize'));
    }

    /**
     * @param Request $request
     * @param Response $response
     */
    public function store(Request $request, Response $response)
    {
        $validation = $this->validator->validate($request, [
            'username' => v::noWhitespace()->notEmpty()->alnum(),
            'password' => v::notEmpty()->stringType()->length(8),
        ]);

        $data = $request->getParsedBody();
        $userEmail = $data['username'].'@'.envi('CPANEL_DOMAIN');

        if ($validation->failed()) {
            redirect()->route('email.create');
        }
        //create email account on cpanel
        if(HmailAPI::addEmail($userEmail, $data['password'], $data['email_quota'], $data['email_forward'])){
            redirect()->route('email.index')->with('success','Email created successfully');
        }else{
            redirect()->route('email.create')->with('error','Error: Unable to create email on cpanel. Check your settings.');
        }
    }

    /**
     * @param Request $request
     * @param Response $response
     */
    public function updatePassword(Request $request, Response $response)
    {
        $validation = $this->validator->validate($request, [
            'email' => v::noWhitespace()->notEmpty()->email(),
            'password' => v::notEmpty()->stringType()->length(8),
        ]);

        $data = $request->getParsedBody();
        $userEmail = $data['email'];

        if ($validation->failed()) {
            redirect()->route('email.index');
        }
        //create email account on cpanel
        if(HmailAPI::updateEmailPassword($userEmail, $data['password'])){
            redirect()->route('email.index')->with('success','Email password updated successfully');
        }else{
            redirect()->route('email.index')->with('error','Error: Unable to update email password');
        }
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return Response
     */
    public function deleteEmail(Request $request, Response $response, $email)
    {
        $email = baseDecode($email);
        if ($email) {
            if(HmailAPI::deleteEmail($email)) {
                echo 1;
            }
        }
        return $response;
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return void
     */
    public function updateQuota(Request $request, Response $response)
    {
        $validation = $this->validator->validate($request, [
            'quota' => v::noWhitespace()->notEmpty()->number(),
        ]);

        $data = $request->getParsedBody();
        $userEmail = $data['email'];

        if ($validation->failed()) {
            redirect()->route('email.index');
        }
        if(HmailAPI::editQuota($userEmail, $data['quota'])){
            redirect()->route('email.index')->with('success','Email quota updated successfully');
        }else{
            redirect()->route('email.index')->with('error','Error: Unable to update email quota');
        }
    }

    /**
     * Manage forward
     * @param Request $request
     * @param Response $response
     * @param $email
     * @return mixed
     * @throws \DI\DependencyException
     * @throws \DI\NotFoundException
     */
    public function createForward(Request $request, Response $response, $email){
        //delete forward
        $email = baseDecode($email);
        if(get('fwdemail')){
            HmailAPI::deleteForward($email, baseDecode(get('fwdemail')));
            redirect()->route('email.forward.create',['email'=>baseEncode($email)]);
        }
        $forwards = HmailAPI::getForward($email)['data'];
        return view($response,'cpemail/forward.twig',compact('email','forwards'));
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return void
     */
    public function manageForwarding(Request $request, Response $response)
    {
        $validation = $this->validator->validate($request, [
            'email' => v::noWhitespace()->notEmpty()->email(),
            'email_forward' => v::noWhitespace()->notEmpty()->email(),
        ]);

        $data = $request->getParsedBody();
        $email = baseEncode($data['email']);

        if ($validation->failed()) {
            redirect()->route('email.forward.create',['email'=>$email]);
        }
        if(HmailAPI::addForward($data['email'], $data['email_forward'])){
            redirect()->route('email.forward.create',['email'=>$email])->with('success','Email forward updated successfully');
        }else{
            redirect()->route('email.forward.create',['email'=>$email])->with('error','Error: Unable to update email forward');
        }
    }

    /**
     * Create Autoresponder
     * @param Request $request
     * @param Response $response
     * @return mixed
     * @throws \DI\DependencyException
     * @throws \DI\NotFoundException
     */
    public function createAutoResponder(Request $request, Response $response, $email){
        $email = baseDecode($email);
        if(get('delete')){
            HmailAPI::deleteAutoResponder($email);
            redirect()->route('email.index');
        }
        $list = HmailAPI::getAutoResponder($email);
        $list = $list['data'];
        return view($response,'cpemail/autoresponder.twig',compact('email','list'));
    }

    /**
     * Manage Autoresponder
     * @param Request $request
     * @param Response $response
     * @return void
     */
    public function manageAutoResponder(Request $request, Response $response)
    {
        $validation = $this->validator->validate($request, [
            'email' => v::noWhitespace()->notEmpty()->email(),
            'from' => v::notEmpty(),
            'subject' => v::notEmpty(),
            'body' => v::notEmpty(),
        ]);

        $data = $request->getParsedBody();
        $email = baseEncode($data['email']);

        if ($validation->failed()) {
            redirect()->route('email.autoresponder.create',['email'=>$email]);
        }
        $autoResp = HmailAPI::addAutoResponder($data['email'],$data['from'],$data['subject'],$data['body'],$data['is_html'],$data['interval'],strtotime($data['start']),strtotime($data['stop']));

        if($autoResp){
            redirect()->route('email.autoresponder.create',['email'=>$email])->with('success','Email auto responder updated successfully');
        }else{
            redirect()->route('email.autoresponder.create',['email'=>$email])->with('error','Error: Unable to update email auto responder');
        }
    }

}
