@extends('layouts.app')

@section('title', __('vetPortal::lang.portal_accounts'))

@section('content')
<section class="content-header">
    <h1><i class="fas fa-users"></i> @lang('vetPortal::lang.portal_accounts')
        <small>Pet-owner logins for the public portal</small>
    </h1>
</section>

<section class="content">
    <div class="row">
        <div class="col-md-3 col-sm-6">
            <div class="info-box bg-aqua"><span class="info-box-icon"><i class="fa fa-users"></i></span>
                <div class="info-box-content"><span class="info-box-text">Total Accounts</span>
                    <span class="info-box-number">{{ $stats['total'] }}</span></div></div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="info-box bg-green"><span class="info-box-icon"><i class="fa fa-check"></i></span>
                <div class="info-box-content"><span class="info-box-text">Enabled</span>
                    <span class="info-box-number">{{ $stats['enabled'] }}</span></div></div>
        </div>
    </div>

    <div class="row" style="margin-bottom:12px;">
        <div class="col-md-12">
            <button class="btn btn-primary" id="btn_add_account">
                <i class="fa fa-plus"></i> @lang('vetPortal::lang.new_account')
            </button>
        </div>
    </div>

    @component('components.widget', ['class' => 'box-primary'])
        <table class="table table-bordered table-striped" id="accounts_table" style="width:100%;">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Login Email</th>
                    <th>Pet Owner</th>
                    <th>Status</th>
                    <th>Last Login</th>
                    <th>Actions</th>
                </tr>
            </thead>
        </table>
    @endcomponent
</section>

{{-- Create account modal --}}
<div class="modal fade" id="accountModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="account_form">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" style="font-size:15px;">&times;</button>
                    <h4 class="modal-title">@lang('vetPortal::lang.new_account')</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>@lang('vetPortal::lang.pet_owner') <span class="text-danger">*</span></label>
                        <select id="acc_owner" class="form-control" style="width:100%"></select>
                        <input type="hidden" id="acc_contact_id">
                    </div>
                    <div class="form-group">
                        <label>Name <span class="text-danger">*</span></label>
                        <input type="text" id="acc_name" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>@lang('vetPortal::lang.email') <span class="text-danger">*</span></label>
                        <input type="email" id="acc_email" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>@lang('vetPortal::lang.password') <span class="text-danger">*</span></label>
                        <input type="text" id="acc_password" class="form-control" placeholder="min 6 characters">
                        <small class="text-muted">Share this with the pet owner; they can change it later.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Create</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Reset password modal --}}
<div class="modal fade" id="resetModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="reset_form">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" style="font-size:15px;">&times;</button>
                    <h4 class="modal-title">@lang('vetPortal::lang.reset_password')</h4>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="reset_id">
                    <p class="text-muted" style="font-size:12px;">Set a new password for <strong id="reset_name"></strong>.</p>
                    <div class="form-group">
                        <label>New @lang('vetPortal::lang.password') <span class="text-danger">*</span></label>
                        <input type="text" id="reset_password" class="form-control" placeholder="min 6 characters">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Reset</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
var accountsTable = $('#accounts_table').DataTable({
    processing: true, serverSide: true, order: [],
    ajax: '{{ route('vp.accounts.list') }}',
    columns: [
        { data: 'name',         name: 'name' },
        { data: 'email',        name: 'email' },
        { data: 'owner',        name: 'owner', orderable: false },
        { data: 'status_badge', name: 'enabled', orderable: false },
        { data: 'last_login',   name: 'last_login_at' },
        { data: 'action',       name: 'action', orderable: false, searchable: false }
    ]
});

$('#btn_add_account').on('click', function () {
    $('#account_form')[0].reset();
    $('#acc_contact_id').val('');
    $('#acc_owner').val(null).trigger('change');
    $('#accountModal').modal('show');
});

$('#acc_owner').select2({
    width: '100%', dropdownParent: $('#accountModal'),
    placeholder: 'Search pet owner…', minimumInputLength: 1,
    ajax: {
        url: '{{ route('vc.pet-owners.search') }}', dataType: 'json', delay: 250,
        data: function (p) { return { q: p.term }; },
        processResults: function (d) { return { results: d }; }
    }
}).on('select2:select', function (e) {
    var d = e.params.data;
    $('#acc_contact_id').val(d.id);
    if (!$('#acc_name').val())  $('#acc_name').val(d.name || '');
    if (!$('#acc_email').val()) $('#acc_email').val(d.email || '');
});

$('#account_form').on('submit', function (e) {
    e.preventDefault();
    if (!$('#acc_contact_id').val()) { toastr.warning('Select a pet owner.'); return; }
    $.post('{{ route('vp.accounts.store') }}', {
        _token: '{{ csrf_token() }}',
        contact_id: $('#acc_contact_id').val(),
        name: $('#acc_name').val(),
        email: $('#acc_email').val(),
        password: $('#acc_password').val()
    }).done(function (res) {
        if (res.success) { toastr.success(res.msg); $('#accountModal').modal('hide'); accountsTable.ajax.reload(); }
        else { toastr.error(res.msg || 'Failed'); }
    }).fail(function (xhr) {
        var m = xhr.responseJSON && xhr.responseJSON.errors
            ? Object.values(xhr.responseJSON.errors)[0][0]
            : (xhr.responseJSON && xhr.responseJSON.msg ? xhr.responseJSON.msg : 'Failed');
        toastr.error(m);
    });
});

$(document).on('click', '.btn-reset-acc', function () {
    $('#reset_id').val($(this).data('id'));
    $('#reset_name').text($(this).data('name'));
    $('#reset_password').val('');
    $('#resetModal').modal('show');
});

$('#reset_form').on('submit', function (e) {
    e.preventDefault();
    $.post('{{ url('vet-portal/accounts') }}/' + $('#reset_id').val() + '/reset-password', {
        _token: '{{ csrf_token() }}', password: $('#reset_password').val()
    }).done(function (res) {
        if (res.success) { toastr.success(res.msg); $('#resetModal').modal('hide'); }
        else { toastr.error(res.msg || 'Failed'); }
    }).fail(function (xhr) {
        toastr.error(xhr.responseJSON && xhr.responseJSON.errors ? 'Password must be at least 6 characters.' : 'Failed');
    });
});

$(document).on('click', '.btn-toggle-acc', function () {
    $.post('{{ url('vet-portal/accounts') }}/' + $(this).data('id') + '/toggle', { _token: '{{ csrf_token() }}' })
        .done(function (res) {
            if (res.success) { toastr.success(res.msg); accountsTable.ajax.reload(); }
        }).fail(function () { toastr.error('Failed'); });
});

$(document).on('click', '.btn-delete-acc', function () {
    if (!confirm('Delete this portal account? The pet owner will lose access.')) return;
    $.ajax({
        url: '{{ url('vet-portal/accounts') }}/' + $(this).data('id'),
        method: 'DELETE', data: { _token: '{{ csrf_token() }}' }
    }).done(function (res) {
        if (res.success) { toastr.success(res.msg); accountsTable.ajax.reload(); }
    }).fail(function () { toastr.error('Failed'); });
});
</script>
@endsection
