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

@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; }
.filter-card { background:#fff; border-radius:12px; padding:14px 18px; box-shadow:0 1px 6px rgba(0,0,0,.08); margin-bottom:14px; border:1px solid #e8ecf1; display:flex; gap:12px; align-items:flex-end; flex-wrap:wrap; }
.vc-table-box { background:#fff; border-radius:10px; overflow:hidden; box-shadow:0 1px 6px rgba(0,0,0,.08); border:1px solid #e8ecf1; }
#waitlist_table td { vertical-align:middle; font-size:12.5px; }
.wl-status { font-size:11px; font-weight:700; text-transform:capitalize; }
</style>
@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-hourglass-half"></i>
        @lang('clinicCore::lang.waitlist')
    </div>
    <div>
        <button class="btn btn-primary btn-sm" id="btn_add_waitlist">
            <i class="fa fa-plus"></i> @lang('clinicCore::lang.add_to_waitlist')
        </button>
    </div>
</div>

<div class="filter-card">
    <div>
        <label class="filter-label">@lang('clinicCore::lang.status')</label>
        <select id="filter_status" class="form-control input-sm">
            <option value="">@lang('clinicCore::lang.waiting') + @lang('clinicCore::lang.offered')</option>
            <option value="waiting">@lang('clinicCore::lang.waiting')</option>
            <option value="offered">@lang('clinicCore::lang.offered')</option>
            <option value="booked">@lang('clinicCore::lang.booked')</option>
            <option value="cancelled">@lang('clinicCore::lang.cancelled')</option>
            <option value="all">@lang('clinicCore::lang.all')</option>
        </select>
    </div>
    <div>
        <label class="filter-label">@lang('clinicCore::lang.doctors')</label>
        <select id="filter_doctor" class="form-control input-sm" style="min-width:160px;">
            <option value="">@lang('clinicCore::lang.any')</option>
            @foreach($doctors as $d)
            <option value="{{ $d->id }}">{{ $d->name }}</option>
            @endforeach
        </select>
    </div>
</div>

<div class="vc-table-box">
    <table class="table table-hover" id="waitlist_table" style="margin:0;">
        <thead>
            <tr>
                <th>@lang('clinicCore::lang.patient')</th>
                <th>@lang('clinicCore::lang.doctors')</th>
                <th>@lang('clinicCore::lang.department')</th>
                <th>@lang('clinicCore::lang.preferred_date')</th>
                <th>@lang('clinicCore::lang.time')</th>
                <th>@lang('clinicCore::lang.reason')</th>
                <th>@lang('clinicCore::lang.status')</th>
                <th>@lang('clinicCore::lang.added')</th>
                <th style="width:150px;"></th>
            </tr>
        </thead>
        <tbody id="waitlist_body">
            <tr><td colspan="9" class="text-center text-muted">@lang('clinicCore::lang.loading')…</td></tr>
        </tbody>
    </table>
</div>
</section>

{{-- Add-to-waitlist modal --}}
<div class="modal fade" id="waitlistModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style="background:linear-gradient(135deg,#0ea5e9,#6366f1);color:#fff;">
        <button type="button" class="close" data-dismiss="modal" style="color:#fff;">&times;</button>
        <h4 class="modal-title"><i class="fas fa-hourglass-half"></i> @lang('clinicCore::lang.add_to_waitlist')</h4>
      </div>
      <div class="modal-body">
        <div class="form-group">
            <label>@lang('clinicCore::lang.patient_contacts') <span class="text-danger">*</span></label>
            <select id="wl_contact" style="width:100%"></select>
        </div>
        <div class="form-group">
            <label>@lang('clinicCore::lang.patient') <span class="text-danger">*</span></label>
            <select id="wl_patient" style="width:100%"><option value="">—</option></select>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label>@lang('clinicCore::lang.doctors')</label>
                    <select id="wl_doctor" class="form-control">
                        <option value="">@lang('clinicCore::lang.any')</option>
                        @foreach($doctors as $d)<option value="{{ $d->id }}">{{ $d->name }}</option>@endforeach
                    </select>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>@lang('clinicCore::lang.department')</label>
                    <select id="wl_department" class="form-control">
                        <option value="">@lang('clinicCore::lang.any')</option>
                        @foreach($departments as $dep)<option value="{{ $dep->id }}">{{ $dep->name }}</option>@endforeach
                    </select>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    <label>@lang('clinicCore::lang.preferred_date')</label>
                    <input type="date" id="wl_date" class="form-control">
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label>@lang('clinicCore::lang.from')</label>
                    <input type="time" id="wl_time_from" class="form-control">
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label>@lang('clinicCore::lang.to')</label>
                    <input type="time" id="wl_time_to" class="form-control">
                </div>
            </div>
        </div>
        <div class="form-group">
            <label>@lang('clinicCore::lang.reason')</label>
            <input type="text" id="wl_reason" class="form-control" placeholder="@lang('clinicCore::lang.optional')">
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-default" data-dismiss="modal">@lang('clinicCore::lang.close')</button>
        <button class="btn btn-primary" id="btn_save_waitlist"><i class="fa fa-save"></i> @lang('clinicCore::lang.save')</button>
      </div>
    </div>
  </div>
</div>
@endsection

@section('javascript')
<script>
$(function () {
    var listUrl = '{{ route('clinic.waitlist.list') }}';
    var statusLabels = {
        waiting:'@lang('clinicCore::lang.waiting')', offered:'@lang('clinicCore::lang.offered')',
        booked:'@lang('clinicCore::lang.booked')', cancelled:'@lang('clinicCore::lang.cancelled')',
        expired:'@lang('clinicCore::lang.expired')'
    };
    var statusColor = { waiting:'warning', offered:'info', booked:'success', cancelled:'default', expired:'default' };

    function esc(s) { return $('<div>').text(s == null ? '' : s).html(); }

    function loadList() {
        $.getJSON(listUrl, { status: $('#filter_status').val(), doctor_id: $('#filter_doctor').val() }, function (rows) {
            var $b = $('#waitlist_body').empty();
            if (!rows.length) {
                $b.html('<tr><td colspan="9" class="text-center text-muted">@lang('clinicCore::lang.no_entries')</td></tr>');
                return;
            }
            rows.forEach(function (w) {
                var timeRange = (w.time_from || w.time_to) ? ((w.time_from||'') + '–' + (w.time_to||'')) : '—';
                var actions = '';
                if (w.status === 'waiting' || w.status === 'offered') {
                    actions = '<a href="{{ url('clinic/waitlist') }}/' + w.id + '/book-now" class="btn btn-xs btn-success"><i class="fa fa-calendar-check"></i> @lang('clinicCore::lang.book_now')</a> '
                            + '<button class="btn btn-xs btn-danger btn-cancel-wl" data-id="' + w.id + '"><i class="fa fa-times"></i></button>';
                }
                $b.append('<tr>'
                    + '<td>' + esc(w.patient) + '</td>'
                    + '<td>' + esc(w.doctor || '—') + '</td>'
                    + '<td>' + esc(w.department || '—') + '</td>'
                    + '<td>' + esc(w.preferred_date || '—') + '</td>'
                    + '<td>' + timeRange + '</td>'
                    + '<td>' + esc(w.reason || '—') + '</td>'
                    + '<td><span class="label label-' + (statusColor[w.status]||'default') + ' wl-status">' + (statusLabels[w.status]||w.status) + '</span></td>'
                    + '<td>' + esc(w.created_at || '') + '</td>'
                    + '<td>' + actions + '</td>'
                    + '</tr>');
            });
        });
    }

    $('#filter_status, #filter_doctor').on('change', loadList);

    $(document).on('click', '.btn-cancel-wl', function () {
        if (!confirm('@lang('clinicCore::lang.are_you_sure')')) return;
        $.ajax({
            url: '{{ url('clinic/waitlist') }}/' + $(this).data('id') + '/cancel',
            method: 'POST', data: { _token: '{{ csrf_token() }}' },
            success: function (res) { if (res.success) { toastr.success(res.msg); loadList(); } }
        });
    });

    /* ── Add modal ── */
    $('#wl_contact').select2({
        width:'100%', placeholder:'— @lang('clinicCore::lang.search') —', minimumInputLength:1,
        dropdownParent: $('#waitlistModal'),
        ajax: {
            url: '{{ route('clinic.patient-contacts.search') }}', dataType:'json', delay:250,
            data: function (p) { return { q: p.term }; },
            processResults: function (d) { return { results: d }; }
        }
    });
    $('#wl_patient').select2({ width:'100%', dropdownParent: $('#waitlistModal') });

    $('#wl_contact').on('change', function () {
        var cid = $(this).val();
        $('#wl_patient').empty().append('<option value="">—</option>');
        if (!cid) return;
        $.getJSON('{{ url('clinic/patients/by-owner') }}/' + cid, function (patients) {
            patients.forEach(function (p) { $('#wl_patient').append('<option value="' + p.id + '">' + esc(p.text) + '</option>'); });
        });
    });

    $('#btn_add_waitlist').on('click', function () {
        $('#wl_contact').val(null).trigger('change');
        $('#wl_patient').empty().append('<option value="">—</option>').trigger('change');
        $('#wl_doctor,#wl_department').val('');
        $('#wl_date,#wl_time_from,#wl_time_to,#wl_reason').val('');
        $('#waitlistModal').modal('show');
    });

    $('#btn_save_waitlist').on('click', function () {
        var patientId = $('#wl_patient').val();
        if (!patientId) { toastr.error('@lang('clinicCore::lang.patient') @lang('clinicCore::lang.required')'); return; }
        $.ajax({
            url: '{{ route('clinic.waitlist.store') }}',
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                patient_id: patientId,
                doctor_id: $('#wl_doctor').val(),
                department_id: $('#wl_department').val(),
                preferred_date: $('#wl_date').val(),
                preferred_time_from: $('#wl_time_from').val(),
                preferred_time_to: $('#wl_time_to').val(),
                reason: $('#wl_reason').val(),
            },
            success: function (res) { if (res.success) { toastr.success(res.msg); $('#waitlistModal').modal('hide'); loadList(); } },
            error: function (xhr) { toastr.error(xhr.responseJSON?.msg ?? 'Error'); }
        });
    });

    loadList();
});
</script>
@endsection
