@extends('layouts.app')
@section('title', __('medportal::lang.health_tracking'))
@section('content')
<section class="content-header">
    <h1>@lang('medportal::lang.health_tracking')</h1>
    <p>@lang('medportal::lang.health_help')</p>
</section>
<section class="content">
    @if(! $hasClinic)
        @component('components.widget', ['class' => 'box-warning'])
            <p class="text-muted">@lang('medportal::lang.clinic_missing')</p>
        @endcomponent
    @else
    @component('components.widget', ['class' => 'box-primary'])
        <form method="GET" action="{{ route('mportal.health.index') }}" class="form-inline" style="margin-bottom:12px;">
            <div class="form-group">
                <label>@lang('medportal::lang.patient')</label>
                <select name="patient_id" class="form-control" onchange="this.form.submit()">
                    <option value="">@lang('medportal::lang.select_patient')</option>
                    @foreach($patients as $id => $name)
                        <option value="{{ $id }}" @selected($selectedId === (int) $id)>{{ $name }}</option>
                    @endforeach
                </select>
            </div>
            @if($selectedId)
            <button type="button" class="btn btn-primary btn-sm mportal-modal-btn" data-href="#addReading"
                onclick="$('#mportal-add-reading').modal('show');return false;">
                <i class="fa fa-plus"></i> @lang('medportal::lang.add_reading')
            </button>
            @endif
        </form>

        @if($selectedId)
            <h4>{{ $selectedName }}</h4>

            @if(! empty($series))
            <div style="margin-bottom:16px;">
                <canvas id="mportal-health-chart" height="90"></canvas>
            </div>
            @endif

            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead><tr>
                        <th>@lang('medportal::lang.metric')</th>
                        <th>@lang('medportal::lang.value')</th>
                        <th>@lang('medportal::lang.logged_at')</th>
                        <th>@lang('medportal::lang.source')</th>
                        <th>@lang('medportal::lang.notes')</th>
                    </tr></thead>
                    <tbody>
                    @forelse($logs as $l)
                        <tr>
                            <td>@lang('medportal::lang.metric_' . $l->metric)</td>
                            <td>{{ $l->value_text ?? $l->value_num }}</td>
                            <td>{{ optional($l->logged_at)->format('Y-m-d H:i') }}</td>
                            <td>@lang('medportal::lang.src_' . $l->source)</td>
                            <td>{{ $l->notes }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="5" class="text-center text-muted">@lang('medportal::lang.no_readings')</td></tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
        @endif
    @endcomponent

    {{-- Add-reading modal --}}
    @if($selectedId)
    <div class="modal fade" id="mportal-add-reading" tabindex="-1" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <form class="mportal-form" action="{{ route('mportal.health.store') }}" method="POST">
            {{ csrf_field() }}
            <input type="hidden" name="patient_id" value="{{ $selectedId }}">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">@lang('medportal::lang.add_reading')</h4>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <label>@lang('medportal::lang.metric') *</label>
                <select name="metric" class="form-control" required>
                  @foreach($metrics as $metric)
                    <option value="{{ $metric }}">@lang('medportal::lang.metric_' . $metric)</option>
                  @endforeach
                </select>
              </div>
              <div class="row">
                <div class="col-md-6 form-group">
                  <label>@lang('medportal::lang.value')</label>
                  <input type="number" step="any" name="value_num" class="form-control">
                </div>
                <div class="col-md-6 form-group">
                  <label>@lang('medportal::lang.value') (text)</label>
                  <input type="text" name="value_text" class="form-control" placeholder="@lang('medportal::lang.value_text_hint')">
                </div>
              </div>
              <div class="form-group">
                <label>@lang('medportal::lang.notes')</label>
                <input type="text" name="notes" class="form-control">
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">@lang('medportal::lang.cancel')</button>
              <button type="submit" class="btn btn-primary">@lang('medportal::lang.save')</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    @endif
    @endif
</section>
@endsection
@section('javascript')
@include('medportal::partials.crud_scripts')
@if(! empty($series))
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
$(function () {
    var series = @json($series);
    var palette = ['#3c8dbc', '#00a65a', '#f39c12', '#dd4b39', '#605ca8'];

    // Union of all x labels (dates), sorted.
    var labelSet = {};
    Object.keys(series).forEach(function (metric) {
        series[metric].forEach(function (p) { labelSet[p.x] = true; });
    });
    var labels = Object.keys(labelSet).sort();

    var datasets = [];
    var i = 0;
    Object.keys(series).forEach(function (metric) {
        var byX = {};
        series[metric].forEach(function (p) { byX[p.x] = p.y; });
        datasets.push({
            label: metric,
            data: labels.map(function (x) { return byX.hasOwnProperty(x) ? byX[x] : null; }),
            borderColor: palette[i % palette.length],
            backgroundColor: palette[i % palette.length],
            spanGaps: true,
            fill: false,
            tension: 0.25
        });
        i++;
    });
    var ctx = document.getElementById('mportal-health-chart');
    if (ctx && window.Chart) {
        new Chart(ctx, {
            type: 'line',
            data: { labels: labels, datasets: datasets },
            options: { plugins: { legend: { position: 'bottom' } } }
        });
    }
});
</script>
@endif
@endsection
