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

@section('css')
<style>
.vc-page-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:14px; 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; }
.queue-filters { display:flex; gap:10px; align-items:flex-end; flex-wrap:wrap; margin-bottom:14px; }
.queue-board { display:flex; gap:14px; align-items:flex-start; flex-wrap:wrap; }
.queue-col { flex:1; min-width:230px; background:#f8fafc; border:1px solid #e8ecf1; border-radius:12px; padding:10px; }
.queue-col-head { font-size:12px; font-weight:800; text-transform:uppercase; letter-spacing:.5px; padding:6px 8px; border-radius:8px; margin-bottom:8px; color:#fff; display:flex; justify-content:space-between; }
.qh-waiting     { background:#f59e0b; }
.qh-in_queue    { background:#3b82f6; }
.qh-with_doctor { background:#8b5cf6; }
.qh-completed   { background:#22c55e; }
.queue-card { background:#fff; border:1px solid #e2e8f0; border-radius:10px; padding:10px 12px; margin-bottom:8px; box-shadow:0 1px 3px rgba(0,0,0,.05); }
.queue-card .qc-top { display:flex; justify-content:space-between; font-size:13px; font-weight:700; color:#1e293b; }
.queue-card .qc-meta { font-size:11px; color:#64748b; margin-top:3px; }
.queue-card .qc-actions { margin-top:8px; display:flex; gap:5px; flex-wrap:wrap; }
.queue-empty { font-size:11px; color:#94a3b8; text-align:center; padding:12px; }
.qc-time-badge { font-size:10px; background:#eff6ff; color:#1d4ed8; border-radius:5px; padding:1px 6px; }
</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-users-line"></i>
        @lang('clinicCore::lang.todays_queue')
        <small style="font-size:12px;color:#94a3b8;font-weight:600;">{{ now()->format('D, d M Y') }}</small>
    </div>
    <div>
        <label style="font-size:11px;color:#64748b;margin-right:6px;">
            <input type="checkbox" id="auto_refresh" checked> @lang('clinicCore::lang.auto_refresh')
        </label>
        <button class="btn btn-default btn-sm" id="btn_refresh_queue"><i class="fa fa-sync"></i> @lang('clinicCore::lang.refresh')</button>
    </div>
</div>

<div class="queue-filters">
    <div>
        <label class="filter-label" style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;display:block;">@lang('clinicCore::lang.clinic_locations')</label>
        <select id="q_location" class="form-control input-sm" style="min-width:160px;">
            <option value="">@lang('clinicCore::lang.any')</option>
            @foreach($locations as $l)<option value="{{ $l->id }}">{{ $l->name }}</option>@endforeach
        </select>
    </div>
    <div>
        <label class="filter-label" style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;display:block;">@lang('clinicCore::lang.doctors')</label>
        <select id="q_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="queue-board">
    <div class="queue-col">
        <div class="queue-col-head qh-waiting"><span>@lang('clinicCore::lang.queue_waiting')</span><span id="cnt_waiting">0</span></div>
        <div id="col_waiting"></div>
    </div>
    <div class="queue-col">
        <div class="queue-col-head qh-in_queue"><span>@lang('clinicCore::lang.queue_in_queue')</span><span id="cnt_in_queue">0</span></div>
        <div id="col_in_queue"></div>
    </div>
    <div class="queue-col">
        <div class="queue-col-head qh-with_doctor"><span>@lang('clinicCore::lang.queue_with_doctor')</span><span id="cnt_with_doctor">0</span></div>
        <div id="col_with_doctor"></div>
    </div>
    <div class="queue-col">
        <div class="queue-col-head qh-completed"><span>@lang('clinicCore::lang.queue_completed')</span><span id="cnt_completed">0</span></div>
        <div id="col_completed"></div>
    </div>
</div>
</section>
@endsection

@section('javascript')
<script>
$(function () {
    var boardUrl   = '{{ route('clinic.queue.board') }}';
    var checkinTpl = '{{ url('clinic/appointments') }}/__ID__/encounter/check-in';
    var statusTpl  = '{{ url('clinic/appointments') }}/__ID__/status';
    var refreshTimer = null;

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

    function cardHtml(a, col) {
        var actions = '';
        if (col === 'waiting') {
            actions = '<button class="btn btn-xs btn-primary q-checkin" data-id="' + a.id + '"><i class="fa fa-sign-in-alt"></i> @lang('clinicCore::lang.check_in')</button>';
        } else if (col === 'in_queue') {
            actions = '<button class="btn btn-xs btn-info q-start" data-id="' + a.id + '"><i class="fa fa-play"></i> @lang('clinicCore::lang.start')</button>';
        } else if (col === 'with_doctor') {
            actions = '<button class="btn btn-xs btn-success q-complete" data-id="' + a.id + '"><i class="fa fa-check"></i> @lang('clinicCore::lang.complete')</button>';
        }
        var checkedIn = a.checked_in_at ? '<span class="qc-time-badge"><i class="fa fa-sign-in-alt"></i> ' + a.checked_in_at + '</span>' : '';
        return '<div class="queue-card">'
            + '<div class="qc-top"><span>' + esc(a.patient || '—') + '</span><span>' + (a.time || '') + '</span></div>'
            + '<div class="qc-meta">' + esc(a.doctor || '—') + (a.department ? ' · ' + esc(a.department) : '') + ' ' + checkedIn + '</div>'
            + '<div class="qc-actions"><a href="' + a.show_url + '" class="btn btn-xs btn-default"><i class="fa fa-eye"></i></a> ' + actions + '</div>'
            + '</div>';
    }

    function renderCol(id, items, colKey) {
        var $c = $('#' + id).empty();
        if (!items.length) { $c.html('<div class="queue-empty">—</div>'); return; }
        items.forEach(function (a) { $c.append(cardHtml(a, colKey)); });
    }

    function loadBoard() {
        $.getJSON(boardUrl, { location_id: $('#q_location').val(), doctor_id: $('#q_doctor').val() }, function (res) {
            renderCol('col_waiting',     res.columns.waiting,     'waiting');
            renderCol('col_in_queue',    res.columns.in_queue,    'in_queue');
            renderCol('col_with_doctor', res.columns.with_doctor, 'with_doctor');
            renderCol('col_completed',   res.columns.completed,   'completed');
            $('#cnt_waiting').text(res.counts.waiting);
            $('#cnt_in_queue').text(res.counts.in_queue);
            $('#cnt_with_doctor').text(res.counts.with_doctor);
            $('#cnt_completed').text(res.counts.completed);
        });
    }

    function post(url, extra, done) {
        $.ajax({ url: url, method: 'POST', data: $.extend({ _token: '{{ csrf_token() }}' }, extra || {}),
            success: function (res) {
                if (res.success) { toastr.success(res.msg); loadBoard(); if (done) done(res); }
                else { toastr.error(res.msg || 'Error'); }
            },
            error: function (xhr) { toastr.error(xhr.responseJSON?.msg ?? 'Error'); }
        });
    }

    $(document).on('click', '.q-checkin', function () { post(checkinTpl.replace('__ID__', $(this).data('id'))); });
    $(document).on('click', '.q-start',   function () { post(statusTpl.replace('__ID__', $(this).data('id')), { status: 'in_progress' }); });
    $(document).on('click', '.q-complete', function () { post(statusTpl.replace('__ID__', $(this).data('id')), { status: 'completed' }); });

    $('#q_location, #q_doctor').on('change', loadBoard);
    $('#btn_refresh_queue').on('click', loadBoard);

    function startTimer() { stopTimer(); refreshTimer = setInterval(loadBoard, 30000); }
    function stopTimer()  { if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; } }
    $('#auto_refresh').on('change', function () { this.checked ? startTimer() : stopTimer(); });

    loadBoard();
    startTimer();
});
</script>
@endsection
