@extends('layouts.app')
@section('title', __('medward::lang.bed_board'))
@section('content')
<section class="content-header">
    <h1>@lang('medward::lang.bed_board')</h1>
    <p>{{ __('medward::lang.board_help', ['sec' => $refreshSeconds]) }}</p>
</section>
<section class="content">
  @if($wards->isEmpty())
    <div class="alert alert-info">@lang('medward::lang.no_wards')</div>
  @else
    <div id="medward_board" class="row"></div>
  @endif

  {{-- Transfer modal --}}
  <div class="modal fade" id="medward_transfer_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog"><div class="modal-content">
      <form class="medward-form" method="POST" action="{{ route('medward.board.transfer') }}">
        {{ csrf_field() }}
        <input type="hidden" name="admission_id" id="tr_admission_id">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">@lang('medward::lang.transfer_patient')</h4>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>@lang('medward::lang.select_bed') *</label>
            <select name="bed_id" id="tr_bed_id" class="form-control" required></select>
          </div>
          <div class="form-group">
            <label>@lang('medward::lang.held_reason')</label>
            <input type="text" name="reason" class="form-control">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">@lang('medward::lang.cancel')</button>
          <button type="submit" class="btn btn-primary">@lang('medward::lang.transfer')</button>
        </div>
      </form>
    </div></div>
  </div>
</section>
@endsection

@section('javascript')
@include('medward::partials.crud_scripts')
<style>
  .mw-bed-card { border:1px solid #ddd; border-radius:6px; padding:8px; margin:4px; min-height:78px; cursor:pointer; }
  .mw-bed-card small { display:block; }
  .mw-ward-col { margin-bottom:16px; }
  .mw-bed-available { border-left:5px solid #00a65a; }
  .mw-bed-occupied  { border-left:5px solid #dd4b39; }
  .mw-bed-reserved  { border-left:5px solid #f39c12; }
  .mw-bed-maintenance, .mw-bed-blocked { border-left:5px solid #999; background:#f7f7f7; }
  .mw-dirty { outline:2px dashed #f39c12; }
</style>
<script>
$(function () {
    var canAdmit  = {{ auth()->user()->can('medward.admission.create') ? 'true' : 'false' }};
    var canManage = {{ auth()->user()->can('medward.wards.manage') ? 'true' : 'false' }};
    var admitBase = '{{ route('medward.admissions.create') }}';
    var boardUrl  = '{{ route('medward.board.data') }}';
    var availUrl  = '{{ route('medward.board.available_beds') }}';
    var statusUrl = '{{ route('medward.board.bed_status') }}';
    var token     = '{{ csrf_token() }}';

    function labelFor(status) {
        return { available:'@lang('medward::lang.bed_status_available')', occupied:'@lang('medward::lang.bed_status_occupied')',
                 reserved:'@lang('medward::lang.bed_status_reserved')', maintenance:'@lang('medward::lang.bed_status_maintenance')',
                 blocked:'@lang('medward::lang.bed_status_blocked')' }[status] || status;
    }

    function render(wards) {
        var $b = $('#medward_board').empty();
        wards.forEach(function (w) {
            var $col = $('<div class="col-md-4 mw-ward-col">');
            $col.append('<h4>' + w.name + ' <small>(' + w.available + '/' + w.total + ' free)</small></h4>');
            var $grid = $('<div>');
            w.beds.forEach(function (bed) {
                var cls = 'mw-bed-card mw-bed-' + bed.status + (bed.cleaning_status === 'dirty' ? ' mw-dirty' : '');
                var $c = $('<div class="' + cls + '">');
                $c.append('<strong>' + bed.bed_number + '</strong> <span class="label label-' + bed.status_color + '">' + labelFor(bed.status) + '</span>');
                if (bed.patient_name) {
                    $c.append('<small>' + $('<div>').text(bed.patient_name).html() + (bed.is_icu ? ' <span class="label label-danger">ICU</span>' : '') + '</small>');
                    $c.append('<small class="text-muted">' + (bed.admission_no || '') + '</small>');
                } else {
                    $c.append('<small class="text-muted">@lang('medward::lang.empty')</small>');
                }
                $c.data('bed', bed);
                $grid.append($c);
            });
            $col.append($grid);
            $b.append($col);
        });
    }

    function load() {
        $.get(boardUrl).done(function (resp) { render(resp.wards || []); });
    }

    // Click a bed → context actions.
    $('#medward_board').on('click', '.mw-bed-card', function () {
        var bed = $(this).data('bed');
        if (!bed) { return; }
        if (bed.status === 'available' && canAdmit) {
            window.location = admitBase + '?bed_id=' + bed.id;
        } else if (bed.status === 'occupied' && canAdmit && bed.admission_id) {
            openTransfer(bed.admission_id);
        } else if (bed.status === 'occupied' && bed.admission_id) {
            window.location = '{{ url('med-ward/admissions') }}/' + bed.admission_id;
        } else if (canManage && (bed.status === 'maintenance' || bed.status === 'blocked')) {
            postStatus(bed.id, 'set_available');
        } else if (canManage && bed.cleaning_status === 'dirty') {
            postStatus(bed.id, 'mark_clean');
        }
    });

    function openTransfer(admissionId) {
        $('#tr_admission_id').val(admissionId);
        var $sel = $('#tr_bed_id').empty();
        $.get(availUrl).done(function (resp) {
            (resp.beds || []).forEach(function (b) {
                $sel.append('<option value="' + b.id + '">#' + b.bed_number + ' (' + b.bed_type + ')</option>');
            });
            if (!$sel.children().length) { $sel.append('<option value="">@lang('medward::lang.no_available_beds')</option>'); }
            $('#medward_transfer_modal').modal('show');
        });
    }

    function postStatus(bedId, action) {
        $.post(statusUrl, { _token: token, bed_id: bedId, action: action }).done(function (resp) {
            if (resp.success) { toastr.success(resp.msg); load(); } else { toastr.error(resp.msg); }
        });
    }

    window.medWardAfterSave = function () { load(); };

    load();
    setInterval(load, {{ $refreshSeconds * 1000 }});
});
</script>
@endsection
