@extends('layouts.app')
@section('title', __('vetClinic::lang.reminder_templates'))

@section('css')
@include('vetClinic::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header">
    <h1>
        <i class="fa fa-file-text"></i> @lang('vetClinic::lang.reminder_templates')
        <small>
            <a href="{{ route('vc.reminders.settings') }}" class="text-muted">
                <i class="fa fa-arrow-left"></i> Back to Settings
            </a>
        </small>
    </h1>
</section>

<section class="content">

    {{-- Available variables reference --}}
    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-default'])
                @slot('title')
                    <i class="fa fa-info-circle text-info"></i> Available Template Variables
                    <button class="btn btn-xs btn-default pull-right" type="button"
                        data-toggle="collapse" data-target="#varList">Toggle</button>
                @endslot
                <div id="varList">
                    <div class="row">
                        @foreach($variables as $token => $desc)
                        <div class="col-md-3" style="margin-bottom:6px;">
                            <code style="cursor:pointer;background:#f8f9fa;border:1px solid #dee2e6;border-radius:3px;padding:2px 6px;font-size:12px;"
                                onclick="copyToken('{{ $token }}')" title="Click to copy">{{ $token }}</code>
                            <br><small class="text-muted">{{ $desc }}</small>
                        </div>
                        @endforeach
                    </div>
                </div>
            @endcomponent
        </div>
    </div>

    {{-- Template cards --}}
    @php
        $typeLabels = [
            'email_due'      => ['label' => 'Email — Due Soon',    'icon' => 'fa-envelope',  'color' => 'primary'],
            'email_overdue'  => ['label' => 'Email — Overdue',     'icon' => 'fa-envelope',  'color' => 'danger'],
            'wa_due'         => ['label' => 'WhatsApp — Due Soon', 'icon' => 'fa-whatsapp',  'color' => 'success'],
            'wa_overdue'     => ['label' => 'WhatsApp — Overdue',  'icon' => 'fa-whatsapp',  'color' => 'warning'],
        ];
    @endphp

    <div class="row">
        @foreach($templates as $tpl)
        @php $meta = $typeLabels[$tpl->type] ?? ['label' => $tpl->type, 'icon' => 'fa-file', 'color' => 'default']; @endphp
        <div class="col-md-6">
            <div class="box box-{{ $meta['color'] }}">
                <div class="box-header with-border">
                    <h3 class="box-title">
                        <i class="fa {{ $meta['icon'] }}"></i>
                        {{ $meta['label'] }}
                        @if($tpl->is_system_default)
                            <span class="label label-default" style="font-size:10px;">System Default</span>
                        @else
                            <span class="label label-info" style="font-size:10px;">Customised</span>
                        @endif
                        @if(!$tpl->is_active)
                            <span class="label label-warning" style="font-size:10px;">Inactive</span>
                        @endif
                    </h3>
                    <div class="box-tools">
                        <button class="btn btn-xs btn-warning btn-edit-template"
                            data-id="{{ $tpl->id }}"
                            data-type="{{ $tpl->type }}"
                            data-label="{{ $meta['label'] }}">
                            <i class="fa fa-edit"></i> Edit
                        </button>
                    </div>
                </div>
                <div class="box-body">
                    <strong>{{ $tpl->name }}</strong>
                    @if($tpl->subject)
                        <br><span class="text-muted" style="font-size:12px;">Subject: {{ $tpl->subject }}</span>
                    @endif
                    <div style="margin-top:8px;background:#f8f9fa;border-radius:4px;padding:10px;font-size:12px;color:#555;
                                white-space:pre-wrap;max-height:120px;overflow:hidden;border:1px solid #e9ecef;">{{ \Illuminate\Support\Str::limit($tpl->body ?? '', 300) }}</div>
                </div>
            </div>
        </div>
        @endforeach
    </div>

</section>

{{-- Edit Modal --}}
<div class="modal fade" id="editTemplateModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" style="font-size:15px;"><span>&times;</span></button>
                <h4 class="modal-title"><i class="fa fa-edit"></i> Edit Template: <span id="modal_tpl_label"></span></h4>
            </div>
            <div class="modal-body">
                <form id="editTemplateForm">
                    <input type="hidden" id="tpl_id">
                    <div class="form-group">
                        <label>Template Name</label>
                        <input type="text" id="tpl_name" class="form-control" required>
                    </div>
                    <div class="form-group" id="tpl_subject_wrap">
                        <label>Email Subject</label>
                        <input type="text" id="tpl_subject" class="form-control">
                        <p class="help-block">Use variable tokens like <code>@{{pet_name}}</code> here.</p>
                    </div>
                    <div class="form-group">
                        <label>Message Body</label>
                        <textarea id="tpl_body" class="form-control" rows="10" style="font-family:monospace;font-size:13px;" required></textarea>
                        <p class="help-block">
                            Use the variable tokens listed above. Click a token to copy it, then paste it here.
                        </p>
                    </div>
                    <div class="form-group">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" id="tpl_is_active" checked> Active
                            </label>
                        </div>
                    </div>
                </form>
                <div id="tpl_save_result" style="display:none;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">@lang('vetClinic::lang.cancel')</button>
                <button type="button" id="btn_save_template" class="btn btn-primary">
                    <i class="fa fa-save"></i> @lang('vetClinic::lang.save')
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
function copyToken(token) {
    navigator.clipboard.writeText(token).then(function() {
        toastr.success('Copied: ' + token, '', {timeOut: 1500});
    }).catch(function() {
        var el = document.createElement('textarea');
        el.value = token;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        toastr.success('Copied: ' + token, '', {timeOut: 1500});
    });
}

$(document).ready(function () {

    $(document).on('click', '.btn-edit-template', function () {
        var id    = $(this).data('id');
        var label = $(this).data('label');
        var type  = $(this).data('type');

        $('#modal_tpl_label').text(label);
        $('#tpl_save_result').hide();
        // WA templates have no subject
        if (type.startsWith('wa_')) {
            $('#tpl_subject_wrap').hide();
        } else {
            $('#tpl_subject_wrap').show();
        }

        $.get('/vet-clinic/reminders/templates/' + id + '/edit')
            .done(function (tpl) {
                $('#tpl_id').val(tpl.id);
                $('#tpl_name').val(tpl.name);
                $('#tpl_subject').val(tpl.subject || '');
                $('#tpl_body').val(tpl.body);
                $('#tpl_is_active').prop('checked', tpl.is_active);
                $('#editTemplateModal').modal('show');
            })
            .fail(function () {
                toastr.error('Could not load template.');
            });
    });

    $('#btn_save_template').on('click', function () {
        var $btn = $(this);
        var id   = $('#tpl_id').val();
        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
        $('#tpl_save_result').hide();

        $.post('/vet-clinic/reminders/templates/' + id + '/update', {
            _token:    '{{ csrf_token() }}',
            name:      $('#tpl_name').val(),
            subject:   $('#tpl_subject').val(),
            body:      $('#tpl_body').val(),
            is_active: $('#tpl_is_active').is(':checked') ? 1 : 0,
        })
        .done(function (res) {
            if (res.success) {
                toastr.success(res.msg);
                $('#editTemplateModal').modal('hide');
                setTimeout(function() { location.reload(); }, 800);
            } else {
                $('#tpl_save_result')
                    .removeClass('alert-success').addClass('alert alert-danger')
                    .html('<i class="fa fa-times"></i> ' + (res.msg || 'Error'))
                    .show();
            }
        })
        .fail(function (xhr) {
            var msg = 'Failed to save.';
            if (xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON.message;
            if (xhr.responseJSON && xhr.responseJSON.errors) {
                msg = Object.values(xhr.responseJSON.errors).flat().join('<br>');
            }
            $('#tpl_save_result')
                .removeClass('alert-success').addClass('alert alert-danger')
                .html('<i class="fa fa-times"></i> ' + msg)
                .show();
        })
        .always(function () {
            $btn.prop('disabled', false).html('<i class="fa fa-save"></i> @lang("vetClinic::lang.save")');
        });
    });
});
</script>
@endsection
