@extends('layouts.app')

@section('title', __('vetClinic::lang.consent_templates'))

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

@section('content')
<section class="content-header">
    <h1><i class="fas fa-file-signature"></i> @lang('vetClinic::lang.consent_templates')</h1>
    <ol class="breadcrumb">
        <li><a href="{{ route('vc.departments.index') }}">@lang('vetClinic::lang.settings')</a></li>
        <li class="active">@lang('vetClinic::lang.consent_templates')</li>
    </ol>
</section>

<section class="content">

    <div class="row" style="margin-bottom:10px;">
        <div class="col-md-12">
            <button class="btn btn-primary pull-right" id="btn_new_ct">
                <i class="fa fa-plus"></i> @lang('vetClinic::lang.add_new')
            </button>
            <div class="alert alert-info" style="margin-bottom:0;padding:6px 12px;display:inline-block;">
                <i class="fa fa-info-circle"></i>
                Rows marked <strong>System</strong> are built-in bilingual templates — view them, or
                <strong>Clone to edit</strong> for an editable copy. Consents are printed from an appointment's
                <strong>Consents</strong> tab.
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary'])
                <table class="table table-bordered table-striped" id="ct_table">
                    <thead>
                        <tr>
                            <th>@lang('vetClinic::lang.name')</th>
                            <th>Category</th>
                            <th>Type</th>
                            <th>@lang('vetClinic::lang.status')</th>
                            <th style="width:170px;">@lang('vetClinic::lang.actions')</th>
                        </tr>
                    </thead>
                </table>
            @endcomponent
        </div>
    </div>
</section>

{{-- ── Add / Edit / View Modal ─────────────────────────────── --}}
<div class="modal fade" id="ctModal" 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;">&times;</button>
                <h4 class="modal-title" id="ct_modal_title">Add Consent Template</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="ct_id">

                <div id="ct_readonly_note" class="alert alert-warning" style="display:none;padding:7px 12px;font-size:12px;">
                    <i class="fa fa-lock"></i> This is a built-in system template and cannot be edited.
                    Use <strong>Clone to edit</strong> to create your own editable copy.
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Name (English) <span class="text-danger">*</span></label>
                            <input type="text" id="ct_name_en" class="form-control">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>الاسم (بالعربية)</label>
                            <input type="text" id="ct_name_ar" class="form-control" dir="rtl">
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-5">
                        <div class="form-group">
                            <label>Category <span class="text-danger">*</span></label>
                            <select id="ct_category" class="form-control">
                                @foreach($categories as $val => $label)
                                <option value="{{ $val }}">{{ $label }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>@lang('vetClinic::lang.status')</label>
                            <select id="ct_status" class="form-control">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <div class="checkbox" style="margin-top:4px;">
                                <label><input type="checkbox" id="ct_requires_witness"> Requires witness</label>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Placeholder reference --}}
                <div class="well well-sm" style="padding:8px 12px;margin-bottom:12px;background:#f8fafc;">
                    <strong style="font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:#64748b;">
                        <i class="fa fa-magic"></i> Placeholders
                    </strong>
                    <span style="font-size:11px;color:#94a3b8;">— click to insert; they auto-fill from the appointment when printed.</span>
                    <div style="margin-top:6px;">
                        @foreach($variables as $token => $desc)
                        <button type="button" class="btn btn-xs btn-default ct-var" data-token="{{ $token }}"
                                title="{{ $desc }}" style="margin:2px;font-family:monospace;">{{ $token }}</button>
                        @endforeach
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Body (English) <span class="text-danger">*</span></label>
                            <textarea id="ct_body_en" class="form-control" rows="13"
                                      style="font-family:'Segoe UI',sans-serif;font-size:12.5px;"></textarea>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>النص (بالعربية)</label>
                            <textarea id="ct_body_ar" class="form-control" rows="13" dir="rtl"
                                      style="font-family:'Segoe UI',sans-serif;font-size:12.5px;"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">@lang('vetClinic::lang.cancel')</button>
                <button class="btn btn-primary" id="btn_save_ct">@lang('vetClinic::lang.save')</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
$(function () {

var lastFocusedBody = null;

var ctTable = $('#ct_table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '{{ route('vc.consent-templates.list') }}',
    order: [],
    columns: [
        { data: 'name_cell',     name: 'name_en' },
        { data: 'category_badge',name: 'category', orderable: false },
        { data: 'system_badge',  name: 'business_id', orderable: false },
        { data: 'status_badge',  name: 'status', orderable: false },
        { data: 'action',        name: 'action', orderable: false, searchable: false }
    ]
});

// Track which body textarea was last focused so placeholder buttons insert there.
$('#ct_body_en, #ct_body_ar').on('focus', function () { lastFocusedBody = this; });

$('.ct-var').on('click', function () {
    var token = $(this).data('token');
    var el = lastFocusedBody || document.getElementById('ct_body_en');
    var start = el.selectionStart, end = el.selectionEnd;
    el.value = el.value.substring(0, start) + token + el.value.substring(end);
    el.selectionStart = el.selectionEnd = start + token.length;
    el.focus();
});

function setReadonly(ro) {
    $('#ct_name_en,#ct_name_ar,#ct_category,#ct_status,#ct_requires_witness,#ct_body_en,#ct_body_ar')
        .prop('disabled', ro);
    $('#ct_readonly_note').toggle(ro);
    $('#btn_save_ct').toggle(!ro);
}

function fillForm(d) {
    $('#ct_id').val(d.id);
    $('#ct_name_en').val(d.name_en);
    $('#ct_name_ar').val(d.name_ar || '');
    $('#ct_category').val(d.category);
    $('#ct_status').val(d.status);
    $('#ct_requires_witness').prop('checked', !!(d.requires_witness == 1 || d.requires_witness === true));
    $('#ct_body_en').val(d.body_en || '');
    $('#ct_body_ar').val(d.body_ar || '');
}

$('#btn_new_ct').on('click', function () {
    $('#ct_modal_title').text('Add Consent Template');
    fillForm({ id: '', name_en: '', name_ar: '', category: 'general', status: 'active',
               requires_witness: false, body_en: '', body_ar: '' });
    setReadonly(false);
    $('#ctModal').modal('show');
});

// Edit a custom template
$(document).on('click', '.btn-edit-ct', function () {
    $.get('{{ url('vet-clinic/consent-templates') }}/' + $(this).data('id') + '/edit', function (d) {
        $('#ct_modal_title').text('Edit Consent Template');
        fillForm(d);
        setReadonly(false);
        $('#ctModal').modal('show');
    });
});

// View a system template (read-only)
$(document).on('click', '.btn-view-ct', function () {
    $.get('{{ url('vet-clinic/consent-templates') }}/' + $(this).data('id') + '/edit', function (d) {
        $('#ct_modal_title').text('View Consent Template');
        fillForm(d);
        setReadonly(true);
        $('#ctModal').modal('show');
    });
});

// Clone a system template to an editable copy
$(document).on('click', '.btn-clone-ct', function () {
    var btn = $(this);
    btn.prop('disabled', true);
    $.ajax({
        url: '{{ url('vet-clinic/consent-templates') }}/' + btn.data('id') + '/clone',
        method: 'POST', data: { _token: '{{ csrf_token() }}' },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg);
                ctTable.ajax.reload();
                $('#ct_modal_title').text('Edit Consent Template');
                fillForm(res.template);
                setReadonly(false);
                $('#ctModal').modal('show');
            }
        },
        error: function () { toastr.error('Could not clone template.'); },
        complete: function () { btn.prop('disabled', false); }
    });
});

$('#btn_save_ct').on('click', function () {
    var id = $('#ct_id').val();
    var url = id
        ? '{{ url('vet-clinic/consent-templates') }}/' + id + '/update'
        : '{{ route('vc.consent-templates.store') }}';

    $.ajax({
        url: url, method: 'POST',
        data: {
            _token:           '{{ csrf_token() }}',
            name_en:          $('#ct_name_en').val(),
            name_ar:          $('#ct_name_ar').val(),
            category:         $('#ct_category').val(),
            status:           $('#ct_status').val(),
            requires_witness: $('#ct_requires_witness').is(':checked') ? 1 : 0,
            body_en:          $('#ct_body_en').val(),
            body_ar:          $('#ct_body_ar').val()
        },
        success: function (res) {
            if (res.success) { $('#ctModal').modal('hide'); toastr.success(res.msg); ctTable.ajax.reload(); }
        },
        error: function (xhr) {
            var m = xhr.responseJSON && xhr.responseJSON.errors
                ? Object.values(xhr.responseJSON.errors)[0][0]
                : (xhr.responseJSON && xhr.responseJSON.message) || 'Error saving template.';
            toastr.error(m);
        }
    });
});

$(document).on('click', '.btn-delete-ct', function () {
    if (!confirm('@lang('vetClinic::lang.confirm_delete')')) return;
    $.ajax({
        url: '{{ url('vet-clinic/consent-templates') }}/' + $(this).data('id'),
        method: 'DELETE', data: { _token: '{{ csrf_token() }}' },
        success: function (res) { if (res.success) { toastr.success(res.msg); ctTable.ajax.reload(); } }
    });
});

});
</script>
@endsection
