<?php
/**
 * Member verification section
 * Used to confirm users identity via two stage authentication
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */

use Illuminate\Support\Facades\App;
use Mtc\Modules\Members\Classes\Auth;
use Mtc\Modules\Members\Classes\MemberManager;
use Mtc\Modules\Members\Models\Member;

$path = "../../";
require_once $path . "core/includes/header.inc.php";
$page_meta['title'] = 'Verify your account';
$errors = [];
$messages = [];
/**
 * @var Member $member
 */

if (!Auth::isLoggedIn()) {
    header("Location: " . route('members-login'));
    exit();
}

// We have a request to generate and send the code
if (filter_input(INPUT_POST, 'action') === 'send_code') {
    $send_to = request()->input('method') === 'email' ? request()->input('email') : request()->input('contact_no');
    try {
        $sent = App::make(MemberManager::class)->sendVerification(request()->input('method'), $send_to);
        if ($sent) {
            $device = request()->input('method') === 'email' ? 'email' : 'phone';
            $messages[] = "Please check your {$device} for verification code";
        }
    } catch (\Exception $exception) {
        $errors = [
            $exception->getMessage()
        ];
    }

    header('Content-Type: application/json');
    echo json_encode([
        'messages' => $messages,
        'errors' => $errors,
    ]);
    exit();
}

// Verify submitted code
if (filter_input(INPUT_POST, 'action') === 'verify_code') {
    $expiry = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $member->verification_code_expiry);

    if (filter_input(INPUT_POST, 'code') !== $member->verification_code) {
            $errors[] = 'Verification code did not match';
        }

    if (empty($errors) && \Carbon\Carbon::now() > $expiry) {
        $errors[] = 'The code has expired. Please re-send code';
    }

    if (empty($errors)) {
        $member->verification_code = '';
        $member->id_verified = \Carbon\Carbon::now();
        $member->save();
        unset($_SESSION['require_account_verification']);
    }


}

// Render page
$twig->display('members/verify.twig', [
    'page_meta' => $page_meta,
    'errors' => $errors,
    'messages' => $messages,
    'name' => $member->addressBilling->firstname,
    'self' => $_SERVER['REQUEST_URI']
]);
