<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;

use App\Account;
use App\Alias;
use App\Domain;
use App\DomainUser;
use App\TlsPolicy;
use App\User;
use App\DovecotPw;
use App\Entropy;

use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Exceptions\PermissionException;
use App\Exceptions\ErrorException;
use Illuminate\Validation\Rule;


class AccountPwController extends Controller
{
    const MinimumEntropy = 50;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
        // Page does not require authentication
    }

    /**
     * Show the password change page
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('layouts/chpass',[]);
    }


    public function ajax(Request $request)
    {
        try
        {
            $validatedData = $request->validate([
                'username' => ['required', 'string',],
                'pass' => ['required', 'string',],
                'newpass' => ['required', 'string',],
            ]);

            // now validate if proper password credentials were sent
            $validCredentials = DovecotPw::Validate($validatedData['username'],$validatedData['pass']);
            if(!$validCredentials)
            {
                throw new ErrorException("Username/Password do not match");
            }
        
            // split account into user and domain
            $dparts = explode('@',$validatedData['username'],2);
            $username = $dparts[0];
            $domain = isset($dparts[1])?$dparts[1]:'localhost';

            // retrieve proper account
            $account = Account::where('username',$username)->where('domain', $domain)->firstOr(function(){
                throw new  ErrorException('Account not found');
            });

            // Check if password meets policy and set if so

            if(Entropy::Calculate($validatedData['newpass']) < static::MinimumEntropy) {
                throw new  ErrorException('Password is not complex enough');
            }
            // encode password
            $hash = DovecotPw::Encrypt($validatedData['newpass']);
            $account->password = $hash;
            $account->save();

            return ["success" => true, "msg" => "Password succesfully changed"];
        }
        catch(ValidationException $v)
        {
            return response(['fail' => 'validation', 'errors' => $v->errors()],400);
        }
        catch(PermissionException $x)
        {
            return response(['fail' => 'role', 'errors' => ['Action requires role '. $x->role()]],403);
        }
        catch(ErrorException $v)
        {
            return response(['fail' => 'errors', 'errors' => $v->errors()],400);
        }
    }



}