<div class="card m-0 p-0" id="company-documents">
    <div class="card-header border-bottom-0 p-2">
        <div class="d-flex align-items-center ">
            <div class="d-flex align-items-center">
                <h6 class="my-0 font-weight-bold">Practice Documents &amp; Forms</h6>
            </div>

            <span class="mx-2 text-secondary">|</span>
            <div moe larger center>
                <a href="#" start show>Add</a>
                <form url="/api/companyProDocument/create">
                    <input type="hidden" name="relatedClientUid" value="{{$patient->uid}}">
                    @if(isset($note))
                    <input type="hidden" name="relatedNoteUid" value="{{$note->uid}}">
                    @endif
                    
                    <div class="form-group">
                        <label>Company Pro</label>
                        <select class="form-control template-selector" name="companyProUid">
                            <option value="">(no template selected)</option>
                            @if(isset($note))
                                @foreach($note->hcpPro->companyPros as $cp)
                                    <option value="{{$cp->uid}}">{{$cp->displayName()}}</option>
                                @endforeach
                            @else 
                                @if($patient->mcp)
                                    @foreach($patient->mcp->companyPros as $cp)
                                        <option value="{{$cp->uid}}">{{$cp->displayName()}}</option>
                                    @endforeach
                                @endif
                            @endif
                        </select>
                    </div>

                    @if(isset($templates) && count($templates))
                    <div class="form-group">
                        <label>Template</label>
                        <select class="form-control template-selector" name="internalName">
                            <option value="">(no template selected)</option>
                            @foreach($templates as $template)
                            @if(strpos($template['name'], "lh-") === FALSE && strpos($template['name'], "smg-") === FALSE && strpos($template['name'], "leadership-") === FALSE)
                            <option value="{{$template['name']}}">{{$template['title']}}&nbsp;&nbsp;({{$template['name']}})</option>
                            @endif
                            @endforeach
                        </select>
                    </div>
                    @endif
                    <div class="mb-2">
                        <label for="board" class="mb-1 text-secondary">Title</label>
                        <input type="hidden" name="title">
                        <div class="title-display form-control form-control-sm"></div>
                    </div>
                    <div class="mb-2">
                        <label for="board" class="mb-1 text-secondary">Content</label>
                        <input type="hidden" name="contentHtml">
                        <div class="contentHtml-display border rounded p-3 bg-light"></div>
                    </div>
                    <div class="mb-2 custom-fields-container row pt-2">

                    </div>
                    <div class="mt-3">
                        <button type="button" class="btn btn-sm btn-primary mr-2 btn-create-document">Create</button>
                        <button cancel class="btn btn-default border">Cancel</button>
                    </div>
                </form>
            </div>
            <span class="mx-2 text-secondary">|</span>
            <div>
                <div moe relative large>
                    <a href="#" start show><i class="fas fa-sync"></i></a>
                    <form url="/api/session/ping" right>
                        <div class="mb-2">
                            <label for="board" class="mb-1 text-secondary">Are you sure?</label>                            
                        </div>                    
                        <div class="mt-3">
                            <button type="button" class="btn btn-sm btn-primary mr-2" submit>Refresh</button>
                            <button cancel class="btn btn-default border">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <div class="card-body p-0 m-0">
            @foreach ($companyPros as $_companyPro)
                    
                <div class="card m-2 p-0" id="company-documents">
                    <div class="card-header border-bottom-0 p-2">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <h6 class="my-0 font-weight-bold">{{$_companyPro->company->name}}</h6>
                                <span class="mx-2 text-secondary">|</span>
                                <div moe relative large>
                                    <a href="#" start show>Request Client Signature</a>
                                    <form url="/api/companyProDocument/requestClientSignatureByClient">

                                        <input type="hidden" name="clientUid" value="{{$patient->uid}}">
                                    
                                        <div class="mt-3">
                                            <button type="button" class="btn btn-sm btn-primary mr-2" submit>Request Client Signature</button>
                                            <button cancel class="btn btn-default border">Cancel</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-body p-0 m-0">
                        @foreach($_companyPro->documents as $document)
                            @if($document->related_client_id == $patient->id)
                                <div class="px-2 py-1 border-top {{!$document->is_active ? 'bg-light' : ''}} d-flex align-items-baseline on-hover-aliceblue" title="{{!$document->is_active ? 'Inactive' : ''}}">
                                    @if(!$document->is_active)
                                        <div class="text-sm text-secondary mr-1">
                                            <i class="fa fa-ban"></i>
                                        </div>
                                    @endif
                                    <a href="{{ route('generateDocumentPDF', $document->uid) }}" class="mr-auto max-width-50 flex-grow-1" native target="_blank" title="{{$document->internal_name}} {{!$document->is_active ? '[Inactive]' : ''}}">{{ $document->title }}</a>
                                    <div class="d-inline-flex flex-nowrap">
                                        @if(!$document->has_client_signed)
                                            @if($document->is_client_signature_requested)
                                            @else
                                                @if($document->is_active)
                                                    <div moe larger center>
                                                        <a start show href="#" class="text-purple" title="Edit"><i class="fa fa-pencil-alt mr-2"></i></a>
                                                        <form url="/api/companyProDocument/updateBasic" class="mt-2" right>
                                                            <input type="hidden" name="uid" value="{{ $document->uid }}">

                                                            <div class="mb-2">
                                                                <label for="board" class="mb-1 text-secondary">Title</label>
                                                                <input type="text" name="title" class="form-control form-control-sm" value="{{$document->title}}">
                                                            </div>
                                                            <div class="mb-2">
                                                                <label for="board" class="mb-1 text-secondary">Content</label>
                                                                <input type="hidden" name="contentHtml">
                                                                <div class="contentHtml-display border rounded p-3 bg-light">
                                                                    {!! $document->content_html !!}
                                                                </div>
                                                            </div>
                                                            @if($document->custom_fields_data)
                                                                <?php $parsedCF = json_decode($document->custom_fields_data); ?>
                                                                <div class="mb-2 custom-fields-container row pt-2">
                                                                    @foreach($parsedCF as $k => $v)
                                                                        <div class="col-6 my-2">
                                                                            <label class="mb-1 {{$k[0] === '@' ? '' : 'text-secondary'}}">{{$k[0] === '@' ? substr($k, 1) : $k}} {{$k[0] === '@' ? '*' : ''}}</label>
                                                                            <input type="text" class="form-control form-control-sm" {{$k[0] === '@' ? 'required' : ''}} data-variable="{{$k}}" value="{{$v}}">
                                                                        </div>
                                                                    @endforeach
                                                                </div>
                                                            @endif
                                                            <div class="mt-3">
                                                                <button type="button" class="btn btn-sm btn-primary mr-2 btn-update-document">Update</button>
                                                                <button cancel class="btn btn-default border">Cancel</button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                @endif
                                            @endif
                                        @endif
                                        @if($document->is_active)
                                            <div moe large>
                                                <a start show href="#" class="d-inline text-danger on-hover-opaque"><i class="fas fa-trash-alt"></i></a>
                                                <form url="/api/companyProDocument/deactivate" class="mt-2" right>
                                                    <input type="hidden" name="uid" value="{{ $document->uid }}">
                                                    <div class="mb-2">
                                                        <p>Are you sure you want to deactivate <b>{{ $document->title }}</b>?</p>
                                                    </div>
                                                    <div class="mt-3">
                                                        <button submit class="btn btn-sm btn-danger mr-2">Deactivate</button>
                                                        <button cancel class="btn btn-default border">Cancel</button>
                                                    </div>
                                                </form>
                                            </div>
                                        @else
                                            <div moe large>
                                                <a start show href="#" class="d-inline text-info"><i class="fas fa-undo"></i></a>
                                                <form url="/api/companyProDocument/reactivate" class="mt-2" right>
                                                    <input type="hidden" name="uid" value="{{ $document->uid }}">
                                                    <div class="mb-2">
                                                        <p>Are you sure you want to reactivate <b>{{ $document->title }}</b>?</p>
                                                    </div>

                                                    <div class="mt-3">
                                                        <button submit class="btn btn-sm btn-primary mr-2">Reactivate</button>
                                                        <button cancel class="btn btn-default border">Cancel</button>
                                                    </div>
                                                </form>
                                            </div>
                                        @endif
                                        <div class="d-inline-flex align-items-baseline ml-2">
                                            <span class="pr-1 text-secondary text-nowrap">Client:</span>
                                            <div class="d-inline-flex align-items-baseline">
                                                @if($document->has_client_signed)
                                                    <span class="font-weight-bold" title="{{$document->pro_signed_at ?  friendly_date_time($document->pro_signed_at) : '-'}}">
                                                        <i class="fas fa-check text-success text-sm"></i>
                                                    </span>
                                                @endif
                                                @if(!$document->has_client_signed)
                                                    @if($document->is_client_signature_requested)
                                                        <span class="ml-1 text-secondary "><i class="fa fa-check text-secondary pr-1"></i>Requested</span>
                                                        <div moe large="" class="ml-1">
                                                            <a start show href="#" class="text-orange" title="Undo Request">Undo</a>
                                                            <form url="/api/companyProDocument/undoRequestClientSignature" class="mt-2" right>
                                                                <input type="hidden" name="uid" value="{{ $document->uid }}">
                                                                <div class="mb-2">
                                                                    <p>Undo request for Client signature?</p>
                                                                </div>
                                                                <div class="mt-3">
                                                                    <button submit class="btn btn-sm btn-danger mr-2">Undo Request Signature</button>
                                                                    <button cancel class="btn btn-default border">Cancel</button>
                                                                </div>
                                                            </form>
                                                        </div>
                                                    @else
                                                        <div moe large="" class="ml-0">
                                                            <a start show href="#" class="text-purple" title="Request Signature">Request</a>
                                                            <form url="/api/companyProDocument/requestClientSignature" class="mt-2" right>
                                                                <input type="hidden" name="uid" value="{{ $document->uid }}">
                                                                <div class="mb-2">
                                                                    <p>Request for Client signature?</p>
                                                                </div>
                                                                <div class="mt-3">
                                                                    <button submit class="btn btn-sm btn-primary mr-2">Request Signature</button>
                                                                    <button cancel class="btn btn-default border">Cancel</button>
                                                                </div>
                                                            </form>
                                                        </div>
                                                    @endif
                                                @endif
                                            </div>
                                           
                                        </div>
                                    </div>
                                </div>
                            @endif
                        @endforeach
                    </div>
                </div>
            @endforeach
    </div>
</div>

<script>
    (function() {
        function init() {
            let templates = <?= json_encode($templates ?? null) ?>;

            $('.signature-pad').each(function() {
                    var targetInput = $(this).data('target-input');
                    let form = $(this).closest('form');
                    let signaturePad = new SignaturePad(this, {
                        onEnd: function() {
                            form.find('[name="'+targetInput+'"]').val(signaturePad.toDataURL());
                        }
                    });
                    form.find('.btn-clear-signature').on('click', function() {
                        signaturePad.clear();
                        return false;
                    });
                });

            $('.template-selector')
                .off('change')
                .on('change', function() {
                    let form = $(this).closest('form');
                    let template = templates.filter(_x => _x.name === $(this).val());
                    if (template && template.length) {
                        template = template[0];
                        form.find('[name="title"]').val(template.title);
                        form.find('.title-display').text(template.title);
                        form.find('[name="contentHtml"]').val(template.html);
                        form.find('.contentHtml-display').html(template.htmlDisplay);

                        // show field inputs, require admin inputs
                        form.find('.custom-fields-container').empty();
                        if (!!template.proVariables) {
                            for (let x in template.proVariables) {
                                if (template.proVariables.hasOwnProperty(x)) {
                                    let variable = template.proVariables[x];
                                    let input = $('<input type="text" />')
                                        .addClass('form-control form-control-sm')
                                        .attr('data-variable', x);
                                    if (variable.adminField) input.prop('required', true);
                                    let label = $('<label class="mb-1">')
                                        .addClass('mb-1')
                                        .addClass(variable.adminField ? '' : 'text-secondary')
                                        .text((x.indexOf('@') === 0 ? x.substr(1) : x) + (variable.adminField ? ' *' : ''));
                                    $('<div/>').addClass('col-6 my-2').append(label).append(input).appendTo(form.find('.custom-fields-container'));
                                }
                            }
                        }
                    }
                });

            $(document)
                .off('keyup change paste blur', 'input[data-variable]')
                .on('keyup change paste blur', 'input[data-variable]', function() {
                    let text = $(this).attr('data-variable');
                    if (text.indexOf('@') === 0) {
                        text = text.substr(1);
                    }
                    if (this.value && $.trim(this.value)) text = $.trim(this.value);
                    $(this).closest('form').find('.document-variable[data-variable="' + $(this).attr('data-variable') + '"]').text(text);
                });

            $(document)
                .off('click', '.btn-create-document')
                .on('click', '.btn-create-document', function() {

                    let form = $(this).closest('form');
                    if (!form[0].checkValidity()) {
                        form[0].reportValidity();
                        return false;
                    }

                    let customFields = {};
                    if (form.find('input[data-variable]').length) {
                        form.find('input[data-variable]').each(function() {
                            customFields[$(this).attr('data-variable')] = this.value;
                        });
                    }

                    $.post(form.attr('url'), form.serialize(), _data => {

                        // update custom field user inputs
                        if (!hasResponseError(_data)) {
                            $.post('/api/companyProDocument/updateCustomFieldsData', {
                                uid: _data.data,
                                fieldDataMap: JSON.stringify(customFields)
                            }, _data => {
                                if (!hasResponseError(_data)) {
                                    fastReload();
                                }
                            });
                        }

                    }, 'json');
                });

            $(document)
                .off('click', '.btn-update-document')
                .on('click', '.btn-update-document', function() {

                    let form = $(this).closest('form');
                    if (!form[0].checkValidity()) {
                        form[0].reportValidity();
                        return false;
                    }

                    let customFields = {};
                    if (form.find('input[data-variable]').length) {
                        form.find('input[data-variable]').each(function() {
                            customFields[$(this).attr('data-variable')] = this.value;
                        });
                    }

                    $.post(form.attr('url'), form.serialize(), _data => {

                        // update custom field user inputs
                        if (!hasResponseError(_data)) {
                            $.post('/api/companyProDocument/updateCustomFieldsData', {
                                uid: form.find('[name="uid"]').val(),
                                fieldDataMap: JSON.stringify(customFields)
                            }, _data => {
                                if (!hasResponseError(_data)) {
                                    fastReload();
                                }
                            });
                        }

                    }, 'json');
                });

            $('input[data-variable]').trigger('change');
            runMCInitializer('previewAndSignDocumentModal');
        }
        addMCInitializer('company-documents', init, '#company-documents');
    }).call(window);
</script>

@include('app.patient.partials.preview-and-sign-document-modal')
