@extends('layouts.app')

@section('title', 'Storage access code')

@section('content')
<section class="content-header">
    <h1><i class="fa fa-lock"></i> Storage locked</h1>
</section>

<section class="content">
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <div class="box box-warning">
                <div class="box-header with-border"><h3 class="box-title">Enter access code</h3></div>
                <div class="box-body">
                    <p class="text-muted">A one-time code is required to open a storage-access session on this device.</p>

                    <button type="button" id="ss-send" class="btn btn-default btn-block"><i class="fa fa-paper-plane"></i> Send me a code</button>
                    <p id="ss-send-msg" class="text-info" style="margin-top:8px;"></p>

                    <div class="form-group" style="margin-top:12px;">
                        <label>Code</label>
                        <input type="text" id="ss-code" class="form-control input-lg" inputmode="numeric" maxlength="6" placeholder="000000">
                    </div>
                    <button type="button" id="ss-verify" class="btn btn-primary btn-block"><i class="fa fa-unlock"></i> Unlock storage</button>
                    <p id="ss-verify-msg" style="margin-top:8px;"></p>

                    <input type="hidden" id="ss-intended" value="{{ $intended }}">
                </div>
            </div>
        </div>
    </div>
</section>
@endsection

@section('javascript')
<script>
$(function () {
    $('#ss-send').on('click', function () {
        $('#ss-send-msg').text('Sending…');
        $.post('{{ route('smart-storage.otp.send') }}', { _token: '{{ csrf_token() }}' })
            .done(function (res) {
                var t = res.msg || 'Code sent.';
                if (res.dev_code) { t += ' (dev: ' + res.dev_code + ')'; }
                $('#ss-send-msg').text(t);
            })
            .fail(function () { $('#ss-send-msg').text('Could not send code.'); });
    });

    $('#ss-verify').on('click', function () {
        $('#ss-verify-msg').html('');
        $.post('{{ route('smart-storage.otp.verify') }}', {
            _token: '{{ csrf_token() }}',
            code: $('#ss-code').val(),
            intended: $('#ss-intended').val()
        }).done(function (res) {
            if (res.success) {
                $('#ss-verify-msg').html('<span class="text-success">Unlocked. Redirecting…</span>');
                window.location = res.intended || '{{ url('/') }}';
            } else {
                $('#ss-verify-msg').html('<span class="text-danger">' + (res.msg || 'Invalid code.') + '</span>');
            }
        }).fail(function () {
            $('#ss-verify-msg').html('<span class="text-danger">Verification failed.</span>');
        });
    });
});
</script>
@endsection
