@extends('layouts.app')
@section('title', __('clinicCore::lang.orders'))

@section('css')
<style>
.vc-page-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:18px; flex-wrap:wrap; gap:10px; }
.vc-page-title  { font-size:22px; font-weight:800; color:#1e293b; display:flex; align-items:center; gap:10px; }
.vc-page-title i { color:#2980b9; }
.vc-page-actions { display:flex; gap:8px; flex-wrap:wrap; }
.filter-card { background:#fff; border-radius:12px; padding:16px 20px; box-shadow:0 1px 6px rgba(0,0,0,.08); margin-bottom:14px; border:1px solid #e8ecf1; }
.filter-row  { display:flex; gap:10px; flex-wrap:wrap; align-items:flex-end; }
.filter-field { display:flex; flex-direction:column; gap:4px; }
.filter-label { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#64748b; white-space:nowrap; }
.filter-field .form-control { height:34px; font-size:12px; border-radius:7px; border:1.5px solid #e2e8f0; }
.search-wrap { position:relative; flex:1; min-width:200px; }
.search-wrap .fa { position:absolute; left:10px; top:50%; transform:translateY(-50%); color:#94a3b8; font-size:12px; }
.search-wrap input { padding-left:30px !important; }
#orders_table td { vertical-align:middle; font-size:12.5px; }
#orders_table_wrapper .dataTables_filter { display:none; }
.vc-table-box { background:#fff; border-radius:10px; overflow:hidden; box-shadow:0 1px 6px rgba(0,0,0,.08); border:1px solid #e8ecf1; }
.ord-item-row td { vertical-align:middle; }
</style>
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header" style="display:none"></section>
<section class="content">

<div class="vc-page-header">
    <div class="vc-page-title">
        <i class="fas fa-clipboard-list"></i>
        @lang('clinicCore::lang.orders')
    </div>
    <div class="vc-page-actions">
        @can('clinic.order.create')
        <button class="btn btn-primary btn-sm" id="btn_new_order">
            <i class="fa fa-plus"></i> @lang('clinicCore::lang.new_order')
        </button>
        @endcan
    </div>
</div>

{{-- Filter Card --}}
<div class="filter-card">
    <div class="filter-row">
        <div class="filter-field" style="flex:1;min-width:200px;">
            <span class="filter-label"><i class="fa fa-search fa-fw"></i> @lang('clinicCore::lang.search')</span>
            <div class="search-wrap">
                <i class="fa fa-search"></i>
                <input type="text" id="ord_search" class="form-control" placeholder="{{ __('clinicCore::lang.order_no') }}, {{ __('clinicCore::lang.patients') }}…">
            </div>
        </div>
        <div class="filter-field" style="min-width:130px;">
            <span class="filter-label">@lang('clinicCore::lang.order_type')</span>
            <select id="ord_type" class="form-control">
                <option value="">—</option>
                @foreach(['lab','imaging','procedure','consultation'] as $t)
                <option value="{{ $t }}">@lang('clinicCore::lang.order_type_'.$t)</option>
                @endforeach
            </select>
        </div>
        <div class="filter-field" style="min-width:120px;">
            <span class="filter-label">@lang('clinicCore::lang.order_priority')</span>
            <select id="ord_priority" class="form-control">
                <option value="">—</option>
                @foreach(['routine','urgent','stat'] as $p)
                <option value="{{ $p }}">{{ ucfirst($p) }}</option>
                @endforeach
            </select>
        </div>
        <div class="filter-field" style="min-width:130px;">
            <span class="filter-label">@lang('clinicCore::lang.status')</span>
            <select id="ord_status" class="form-control">
                <option value="">—</option>
                @foreach(['ordered','collected','in_progress','resulted','verified','cancelled'] as $s)
                <option value="{{ $s }}">{{ ucfirst(str_replace('_',' ', $s)) }}</option>
                @endforeach
            </select>
        </div>
        <div class="filter-field" style="align-self:flex-end;">
            <button id="btn_clear_ord" class="btn btn-default" style="height:34px;">
                <i class="fa fa-times-circle" style="color:#ef4444;"></i> @lang('clinicCore::lang.cancel')
            </button>
        </div>
    </div>
</div>

{{-- Table --}}
<div class="vc-table-box">
    <div style="padding:14px;">
        <table class="table table-bordered table-striped table-hover" id="orders_table" style="font-size:12.5px;">
            <thead style="background:#f8fafc;">
                <tr>
                    <th>@lang('clinicCore::lang.order_no')</th>
                    <th>@lang('clinicCore::lang.patients')</th>
                    <th>@lang('clinicCore::lang.order_type')</th>
                    <th>@lang('clinicCore::lang.order_priority')</th>
                    <th>@lang('clinicCore::lang.status')</th>
                    <th>@lang('clinicCore::lang.date')</th>
                    <th>@lang('clinicCore::lang.actions')</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

</section>

{{-- ── Add-order modal ─────────────────────────────────────────────────── --}}
@can('clinic.order.create')
<div id="orderCreateModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document"><div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><i class="fa fa-plus"></i> @lang('clinicCore::lang.new_order')</h4>
    </div>
    <div class="modal-body">
        <div class="row">
            <div class="col-md-3 form-group">
                <label>@lang('clinicCore::lang.patient_contacts') <span class="text-danger">*</span></label>
                <select id="ord_contact" class="form-control" style="width:100%"></select>
            </div>
            <div class="col-md-3 form-group">
                <label>@lang('clinicCore::lang.patients') <span class="text-danger">*</span></label>
                <select id="ord_patient" class="form-control" style="width:100%"></select>
            </div>
            <div class="col-md-3 form-group">
                <label>@lang('clinicCore::lang.order_type') <span class="text-danger">*</span></label>
                <select id="ord_new_type" class="form-control">
                    @foreach(['lab','imaging','procedure','consultation'] as $t)
                    <option value="{{ $t }}">@lang('clinicCore::lang.order_type_'.$t)</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3 form-group">
                <label>@lang('clinicCore::lang.order_priority')</label>
                <select id="ord_new_priority" class="form-control">
                    @foreach(['routine','urgent','stat'] as $p)
                    <option value="{{ $p }}">{{ ucfirst($p) }}</option>
                    @endforeach
                </select>
            </div>
        </div>
        <div class="form-group">
            <label>@lang('clinicCore::lang.clinical_indication')</label>
            <textarea id="ord_indication" class="form-control" rows="2"></textarea>
        </div>
        <label>@lang('clinicCore::lang.add_order')</label>
        <table class="table table-condensed table-bordered" id="ord_items_table">
            <thead><tr>
                <th>@lang('clinicCore::lang.service_name')</th>
                <th style="width:120px;">@lang('clinicCore::lang.service_code')</th>
                <th style="width:130px;">@lang('clinicCore::lang.laterality')</th>
                <th style="width:70px;">@lang('clinicCore::lang.quantity')</th>
                <th style="width:36px;"></th>
            </tr></thead>
            <tbody id="ord_items_body"></tbody>
        </table>
        <button type="button" class="btn btn-default btn-sm" id="ord_add_item"><i class="fa fa-plus"></i> @lang('clinicCore::lang.add')</button>
        <div id="ord_create_warnings" style="margin-top:10px;"></div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
        <button type="button" class="btn btn-primary" id="ord_save"><i class="fa fa-save"></i> @lang('clinicCore::lang.save')</button>
    </div>
  </div></div>
</div>
@endcan

{{-- ── View-order modal ────────────────────────────────────────────────── --}}
<div id="orderViewModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document"><div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><i class="fa fa-clipboard-list"></i> <span id="ordv_no"></span></h4>
    </div>
    <div class="modal-body" id="ordv_body">
        <div style="text-align:center;padding:20px;color:#94a3b8;"><i class="fa fa-spinner fa-spin"></i></div>
    </div>
    <div class="modal-footer">
        @can('clinic.order.verify')
        <button type="button" class="btn btn-success" id="ordv_verify" style="display:none;"><i class="fa fa-check-double"></i> @lang('clinicCore::lang.verify_results')</button>
        @endcan
        <a href="#" target="_blank" class="btn btn-default" id="ordv_print"><i class="fa fa-print"></i> Print</a>
        <button type="button" class="btn btn-default" data-dismiss="modal">@lang('clinicCore::lang.close')</button>
    </div>
  </div></div>
</div>

@endsection

@section('javascript')
<script>
var ordTable = null;
var ordToken = '{{ csrf_token() }}';
var ordListUrl = '{{ route('clinic.orders.list') }}';

$(document).ready(function () {
    ordTable = $('#orders_table').DataTable({
        processing: true, serverSide: true, order: [[5, 'desc']],
        ajax: {
            url: ordListUrl,
            data: function (d) {
                d.filter_search   = $('#ord_search').val();
                d.filter_type     = $('#ord_type').val();
                d.filter_priority = $('#ord_priority').val();
                d.filter_status   = $('#ord_status').val();
            }
        },
        columns: [
            { data: 'order_no_col',   name: 'order_no',     orderable: false },
            { data: 'patient_name',   name: 'patient_name', orderable: false },
            { data: 'type_badge',     name: 'order_type',   orderable: false },
            { data: 'priority_badge', name: 'priority',     orderable: false },
            { data: 'status_badge',   name: 'status',       orderable: false },
            { data: 'created_col',    name: 'created_at' },
            { data: 'action',         name: 'action',       orderable: false, searchable: false }
        ],
        pageLength: 25,
        language: { processing: '<i class="fa fa-spinner fa-spin"></i> Loading…' }
    });

    var t = null;
    $('#ord_search').on('input', function () { clearTimeout(t); t = setTimeout(function () { ordTable.ajax.reload(); }, 350); });
    $('#ord_type, #ord_priority, #ord_status').on('change', function () { ordTable.ajax.reload(); });
    $('#btn_clear_ord').on('click', function () {
        $('#ord_search').val(''); $('#ord_type,#ord_priority,#ord_status').val('');
        ordTable.ajax.reload();
    });
});

// ── View order ──
$(document).on('click', '.clc-order-view', function (e) {
    e.preventDefault();
    var id = $(this).data('id');
    $('#ordv_body').html('<div style="text-align:center;padding:20px;color:#94a3b8;"><i class="fa fa-spinner fa-spin"></i></div>');
    $('#ordv_verify').hide();
    $('#ordv_print').attr('href', '{{ url('clinic/orders') }}/' + id + '/print');
    $('#orderViewModal').modal('show');
    $.get('{{ url('clinic/orders') }}/' + id).done(function (res) {
        if (!res.success) return;
        var o = res.order;
        $('#ordv_no').text(o.order_no + ' · ' + (o.order_type || ''));
        var esc = function (s) { return $('<div>').text(s == null ? '' : s).html(); };
        var h = '<p><strong>@lang('clinicCore::lang.patients'):</strong> ' + esc(o.patient_name || '—')
              + ' &nbsp; <strong>@lang('clinicCore::lang.order_priority'):</strong> ' + esc(o.priority)
              + ' &nbsp; <strong>@lang('clinicCore::lang.status'):</strong> ' + esc(o.status.replace('_',' ')) + '</p>';
        if (o.clinical_indication) h += '<p><strong>@lang('clinicCore::lang.clinical_indication'):</strong> ' + esc(o.clinical_indication) + '</p>';
        h += '<table class="table table-bordered table-condensed"><thead><tr>'
           + '<th>@lang('clinicCore::lang.service_name')</th><th>@lang('clinicCore::lang.laterality')</th>'
           + '<th>@lang('clinicCore::lang.status')</th><th>@lang('clinicCore::lang.result_summary')</th><th>@lang('clinicCore::lang.abnormal_flag')</th>'
           + '</tr></thead><tbody>';
        o.items.forEach(function (it) {
            var flag = it.abnormal_flag ? esc(it.abnormal_flag.replace('_',' ')) : '—';
            var critical = (it.abnormal_flag === 'critical_high' || it.abnormal_flag === 'critical_low');
            h += '<tr>'
              + '<td>' + esc(it.service_name) + (it.service_code ? ' <small class="text-muted">(' + esc(it.service_code) + ')</small>' : '')
              +   (it.note ? '<br><small class="text-warning"><i class="fa fa-exclamation-triangle"></i> ' + esc(it.note) + '</small>' : '') + '</td>'
              + '<td>' + esc(it.laterality) + '</td>'
              + '<td>' + esc(it.status.replace('_',' ')) + '</td>'
              + '<td>' + esc(it.result_summary || '—') + '</td>'
              + '<td>' + (critical ? '<span class="label label-danger">' + flag + '</span>' : flag) + '</td>'
              + '</tr>';
        });
        h += '</tbody></table>';
        $('#ordv_body').html(h);
        if (o.can_verify) {
            $('#ordv_verify').show().data('id', o.id);
        }
    });
});

@can('clinic.order.verify')
$(document).on('click', '#ordv_verify', function () {
    var id = $(this).data('id');
    var $btn = $(this).prop('disabled', true);
    $.post('{{ url('clinic/orders') }}/' + id + '/verify', { _token: ordToken })
        .done(function (res) {
            if (res.success) { if (window.toastr) toastr.success(res.msg); $('#orderViewModal').modal('hide'); if (ordTable) ordTable.ajax.reload(); }
        })
        .fail(function (xhr) { var m = (xhr.responseJSON && xhr.responseJSON.msg) || 'Error'; if (window.toastr) toastr.error(m); })
        .always(function () { $btn.prop('disabled', false); });
});
@endcan

@can('clinic.order.create')
// ── New order modal ──
function ordItemRow() {
    return '<tr class="ord-item-row">'
        + '<td><input type="text" class="form-control input-sm ord-svc" placeholder="{{ __('clinicCore::lang.service_name') }}"></td>'
        + '<td><input type="text" class="form-control input-sm ord-code"></td>'
        + '<td><select class="form-control input-sm ord-lat">'
        +   '<option value="na">@lang('clinicCore::lang.lat_na')</option>'
        +   '<option value="left">@lang('clinicCore::lang.lat_left')</option>'
        +   '<option value="right">@lang('clinicCore::lang.lat_right')</option>'
        +   '<option value="bilateral">@lang('clinicCore::lang.lat_bilateral')</option>'
        + '</select></td>'
        + '<td><input type="number" class="form-control input-sm ord-qty" value="1" min="1"></td>'
        + '<td><button type="button" class="btn btn-danger btn-xs ord-del-item"><i class="fa fa-trash"></i></button></td>'
        + '</tr>';
}

$('#btn_new_order').on('click', function () {
    $('#ord_indication').val('');
    $('#ord_create_warnings').html('');
    $('#ord_items_body').html(ordItemRow());
    $('#orderCreateModal').modal('show');
});
$('#ord_add_item').on('click', function () { $('#ord_items_body').append(ordItemRow()); });
$(document).on('click', '.ord-del-item', function () { $(this).closest('tr').remove(); });

// Contact search → patient dropdown (mirrors the Rx create flow).
$('#ord_patient').select2({ dropdownParent: $('#orderCreateModal'), width: '100%', placeholder: '— {{ __('clinicCore::lang.patients') }} —' });
$('#ord_contact').select2({
    dropdownParent: $('#orderCreateModal'),
    width: '100%',
    minimumInputLength: 2,
    placeholder: '{{ __('clinicCore::lang.search') }} contact…',
    ajax: {
        url: '{{ route('clinic.patient-contacts.search') }}',
        dataType: 'json', delay: 300,
        data: function (p) { return { q: p.term }; },
        processResults: function (d) { return { results: d }; }
    }
}).on('select2:select', function (e) {
    var contactId = e.params.data.id;
    $('#ord_patient').empty().append('<option value="">Loading…</option>').trigger('change');
    $.get('{{ url('clinic/patients/by-owner') }}/' + contactId, function (data) {
        $('#ord_patient').empty().append('<option value="">— {{ __('clinicCore::lang.patients') }} —</option>');
        $.each(data, function (i, p) { $('#ord_patient').append('<option value="' + p.id + '">' + p.text + '</option>'); });
        $('#ord_patient').trigger('change');
    });
});

$('#ord_save').on('click', function () {
    var patientId = $('#ord_patient').val();
    if (!patientId) { if (window.toastr) toastr.warning('Select a patient.'); return; }
    var items = [];
    $('#ord_items_body tr.ord-item-row').each(function () {
        var svc = ($(this).find('.ord-svc').val() || '').trim();
        if (!svc) return;
        items.push({
            service_name: svc,
            service_code: ($(this).find('.ord-code').val() || '').trim(),
            laterality: $(this).find('.ord-lat').val(),
            quantity: parseInt($(this).find('.ord-qty').val() || '1', 10)
        });
    });
    if (!items.length) { if (window.toastr) toastr.warning('Add at least one service.'); return; }

    var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
    $.post('{{ route('clinic.orders.store') }}', {
        _token: ordToken,
        patient_id: patientId,
        order_type: $('#ord_new_type').val(),
        priority: $('#ord_new_priority').val(),
        clinical_indication: $('#ord_indication').val(),
        items: items
    }).done(function (res) {
        if (res.success) {
            if (res.warnings && res.warnings.length) {
                var w = '<div class="alert alert-warning" style="margin-bottom:0;"><strong>Note:</strong><ul style="margin:4px 0 0;">';
                res.warnings.forEach(function (m) { w += '<li>' + $('<div>').text(m).html() + '</li>'; });
                w += '</ul></div>';
                $('#ord_create_warnings').html(w);
            }
            if (window.toastr) toastr.success(res.msg);
            $('#orderCreateModal').modal('hide');
            if (ordTable) ordTable.ajax.reload();
        }
    }).fail(function (xhr) {
        var m = (xhr.responseJSON && xhr.responseJSON.msg) || 'Could not place order.';
        if (window.toastr) toastr.error(m);
    }).always(function () {
        $btn.prop('disabled', false).html('<i class="fa fa-save"></i> @lang('clinicCore::lang.save')');
    });
});
@endcan
</script>
@endsection
