@extends('layouts.app')

@push('styles')
<link rel="stylesheet" href="{{ asset('css/TbSection/preTbRecord.css') }}">
<link rel="stylesheet" href="{{ asset('css/TbSection/preTbRecord.page.css') }}">
@endpush

@section('content')
@auth
@php
  $editingId = request()->query('edit');
  $riskOptionsCurrentExNoUk = [
    ['1', 'Current'],
    ['2', 'Ex'],
    ['3', 'No'],
    ['4', 'UK'],
  ];
  $riskOptionsYesNo = [
    ['1', 'Yes'],
    ['2', 'No'],
  ];
  $riskOptionsYesNoUk = [
    ['1', 'Yes'],
    ['2', 'No'],
    ['3', 'UK'],
  ];
  $symptomRiskRows = [
    [
      'symptom' => ['slug' => 'fever', 'label' => 'Fever'],
      'risk' => ['id' => 'alcohol', 'field' => 'alcohol', 'label' => 'Alcohol', 'options' => $riskOptionsCurrentExNoUk],
    ],
    [
      'symptom' => ['slug' => 'cough', 'label' => 'Cough'],
      'risk' => ['id' => 'smoking', 'field' => 'smoking', 'label' => 'Smoking', 'options' => $riskOptionsCurrentExNoUk],
    ],
    [
      'symptom' => ['slug' => 'hemoptysis', 'label' => 'Hemoptysis'],
      'risk' => ['id' => 'malnutrition', 'field' => 'malnutrition', 'label' => 'Malnutrition', 'options' => $riskOptionsYesNo],
    ],
    [
      'symptom' => ['slug' => 'weight_loss', 'label' => 'Weight loss'],
      'risk' => ['id' => 'PWID', 'field' => 'PWID', 'label' => 'PWID', 'options' => $riskOptionsCurrentExNoUk],
    ],
    [
      'symptom' => ['slug' => 'appetite_loss', 'label' => 'Loss of appetite'],
      'risk' => ['id' => 'PWUD', 'field' => 'PWUD', 'label' => 'PWUD', 'options' => $riskOptionsCurrentExNoUk],
    ],
    [
      'symptom' => ['slug' => 'chest_pain', 'label' => 'Chest pain'],
      'risk' => [
        'id' => 'DM',
        'field' => 'DM',
        'label' => 'DM',
        'options' => $riskOptionsYesNoUk,
        'tx' => [
          'id' => 'dm_tx_status',
          'field' => 'dm_tx_status',
          'wrap_id' => 'dm_tx_status_wrap',
          'options' => [
            ['1', 'on Tx'],
            ['2', 'not Tx'],
          ],
        ],
      ],
    ],
    [
      'symptom' => ['slug' => 'night_sweats', 'label' => 'Night sweats'],
      'risk' => [
        'id' => 'hiv_status',
        'field' => 'hiv_status',
        'label' => 'HIV',
        'options' => $riskOptionsYesNoUk,
        'tx' => [
          'id' => 'hiv_tx',
          'field' => 'hiv_tx',
          'wrap_id' => 'hiv_tx_wrap',
          'options' => [
            ['1', 'on Tx'],
            ['2', 'not Tx'],
          ],
        ],
      ],
    ],
    [
      'symptom' => ['slug' => 'neck_glands', 'label' => 'Neck glands'],
      'risk' => ['id' => 'his_tb_self', 'field' => 'his_tb_self', 'label' => 'Hist. of TB (self)', 'options' => $riskOptionsYesNoUk],
    ],
    [
      'symptom' => ['slug' => 'fatigue', 'label' => 'Fatigue'],
      'risk' => ['id' => 'his_tb_family', 'field' => 'his_tb_family', 'label' => 'Hist. of TB (family)', 'options' => $riskOptionsYesNoUk],
    ],
  ];
  $selectedSpecimens = static function ($value): array {
    if (is_array($value)) {
      return array_values(array_filter(array_map('trim', $value)));
    }
    return array_values(array_filter(array_map('trim', explode(',', (string) $value))));
  };
  $modeOfEntryOptions = [
    '1' => 'General',
    '2' => 'PLHIV',
    '3' => 'NCD',
    '7' => 'Diabetes',
    '4' => 'Remote (ICMV)',
    '5' => 'Remote (TB mobile)',
    '6' => 'Contact tracing',
  ];
  $modeOfEntryValue = old('mode_of_entry');
  $selectedModeOfEntry = $selectedSpecimens($modeOfEntryValue);
  if (empty($selectedModeOfEntry) && $editingId) {
    $selectedModeOfEntry = $selectedSpecimens(optional(\App\Models\PreTbRecord::find($editingId))->mode_of_entry);
  }
@endphp
<div class="container-fluid pre-tb-record-container">
  <div class="row justify-content-center">
    <div class="col-12">
      <div class="card pre-tb-card shadow-sm mx-auto">
        <div class="card-header d-flex justify-content-between align-items-center">
          <div>
            <h2 class="mb-0">TB assessment</h2>
            @if ($editingId)
            <div class="mt-1">
              <span class="badge bg-warning text-dark">Editing record #{{ $editingId }}</span>
              <a href="{{ route('pretb_record.create') }}" class="ms-2 text-decoration-underline text-light">Create new</a>
            </div>
            @endif
          </div>
          <div class="d-flex flex-nowrap align-items-center gap-2">
            <a href="{{ route('pretb_record.create') }}" class="btn btn-outline-light btn-sm pretb-header-action-btn">Clear</a>
            <a href="{{ route('pretb_record.manage') }}" class="btn btn-outline-light btn-sm pretb-header-action-btn">Manage</a>
            <form method="POST" action="{{ route('pretb_record.export') }}" class="d-flex align-items-center tablet-hide-action">
              @csrf
              <input type="hidden" name="format" value="codes">
              <button type="submit" class="btn btn-outline-light btn-sm pretb-header-action-btn">Export (codes)</button>
            </form>

            <form method="POST" action="{{ route('pretb_record.export') }}" class="d-flex align-items-center tablet-hide-action">
              @csrf
              <input type="hidden" name="format" value="labels">
              <button type="submit" class="btn btn-outline-light btn-sm pretb-header-action-btn">Export (labels)</button>
            </form>

            <form method="POST" action="{{ route('pretb_record.export') }}" class="d-flex align-items-center tablet-hide-action">
              @csrf
              <input type="hidden" name="format" value="analysis">
              <button type="submit" class="btn btn-outline-light btn-sm">Export (analysis)</button>
            </form>

            <form method="POST" action="{{ route('pretb_record.export') }}" class="d-flex align-items-center tablet-hide-action">
              @csrf
              <input type="hidden" name="format" value="counts">
              <button type="submit" class="btn btn-outline-light btn-sm">Export (counts)</button>
            </form>

            <div class="dropdown tablet-only-actions">
              <button class="btn btn-outline-light btn-sm px-2"
                type="button"
                id="pretbTabletActions"
                data-bs-toggle="dropdown"
                aria-expanded="false"
                aria-label="More actions">
                <i class="bi bi-three-dots-vertical"></i>
              </button>
              <div class="dropdown-menu dropdown-menu-end dropdown-menu-dark p-2 tablet-actions-menu" aria-labelledby="pretbTabletActions">
                <form method="POST" action="{{ route('pretb_record.export') }}" class="mb-2">
                  @csrf
                  <input type="hidden" name="format" value="codes">
                  <button type="submit" class="dropdown-item">Export (codes)</button>
                </form>

                <form method="POST" action="{{ route('pretb_record.export') }}" class="mb-2">
                  @csrf
                  <input type="hidden" name="format" value="labels">
                  <button type="submit" class="dropdown-item">Export (labels)</button>
                </form>

                <form method="POST" action="{{ route('pretb_record.export') }}" class="mb-2">
                  @csrf
                  <input type="hidden" name="format" value="analysis">
                  <button type="submit" class="dropdown-item">Export (analysis)</button>
                </form>

                <form method="POST" action="{{ route('pretb_record.export') }}" class="mb-2">
                  @csrf
                  <input type="hidden" name="format" value="counts">
                  <button type="submit" class="dropdown-item">Export (counts)</button>
                </form>

              </div>
            </div>

          </div>
        </div>
        <div class="card-body">
          @if (session('status'))
          <div class="alert alert-success" id="pretb-status-alert">
            {{ session('status') }}
          </div>
          @endif

          @if ($errors->any())
          <div class="alert alert-danger">
            <div class="fw-bold mb-2">Please fix the following:</div>
            <ul class="mb-0">
              @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
              @endforeach
            </ul>
          </div>
          @endif

          @include('TB.partials.entry_context', ['currentPage' => 'pretb'])

          <div class="alert alert-secondary" id="pretbSyncPanel"
            data-download-url="{{ route('pretb_record.sync.download') }}"
            data-upload-url="{{ route('pretb_record.sync.upload') }}">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
              <div>
                <div class="fw-semibold">Browser entry queue</div>
                <div class="small text-muted">Pre-TB entries are saved in this browser first. Use Sync to upload them to the server.</div>
              </div>
              <div class="d-flex flex-wrap gap-2">
                <button type="button" class="btn btn-sm btn-outline-secondary" id="pretbOfflineToggle">Offline-only: Off</button>
                <button type="button" class="btn btn-sm btn-outline-primary" id="pretbSyncDownload">Download</button>
                <button type="button" class="btn btn-sm btn-outline-success" id="pretbSyncUpload">
                  Sync (<span id="pretbSyncPendingCount">0</span>)
                </button>
                <button type="button" class="btn btn-sm btn-outline-danger" id="pretbSyncClear">Clear pending</button>
              </div>
            </div>
            <div class="d-flex align-items-center justify-content-between gap-2 mt-2">
              <div class="small text-muted" id="pretbSyncStatus">Ready.</div>
              <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-outline-secondary" id="pretbSyncQueueToggle">Show queue</button>
                <button type="button" class="btn btn-sm btn-outline-secondary" id="pretbSyncQueueRefresh">Refresh</button>
              </div>
            </div>
            <div class="small mt-2 d-none" id="pretbSyncQueueList">No pending Pre-TB records.</div>
          </div>

          <form method="POST"
            action="{{ $editingId ? route('pretb_record.update', $editingId) : route('pretb_record.store') }}"
            id="pretb-record-form"
            data-lookup-url="{{ route('pretb_record.lookup') }}"
            data-csrf-token="{{ csrf_token() }}"
            enctype="multipart/form-data"
            novalidate>
            @csrf
            @if ($editingId)
            @method('PUT')
            @endif
            <input type="hidden" id="pretb_local_uuid" name="_local_uuid" value="">
            <input type="hidden" id="pretb_server_id" name="server_id" value="{{ $editingId ?: '' }}">
            <input type="hidden" id="pretb_clinic_name" name="clinic_name" value="{{ session('tb.clinic', config('tb_entry.default_clinic', 'Myitkyina')) }}">
            <input type="hidden" id="export_pdf_after_save" name="export_pdf_after_save" value="0">
            {{-- Patient & visit section --}}
            <div class="row g-3">
              <div class="col-12 col-md-6 col-lg-2 tablet-general-id-col">
                <label for="cid" class="form-label">General ID:</label>
                <input type="text"
                  class="form-control"
                  id="cid"
                  name="cid"
                  inputmode="numeric"
                  pattern="[0-9]{10,12}"
                  required
                  value="{{ old('cid') }}">
              </div>
              <div class="col-12 col-md-6 col-lg-3 tablet-patient-details-col">
                <label for="name" class="form-label">Name:</label>
                <input type="text" class="form-control" id="name" name="name" required value="{{ old('name') }}">
              </div>
              <div class="col-12 col-md-3 col-lg-2 tablet-patient-details-col">
                <label for="age" class="form-label">Age:</label>
                <input type="number" class="form-control" id="age" name="age" min="0" max="111" required value="{{ old('age') }}">
              </div>
              <div class="col-12 col-md-3 col-lg-1 tablet-patient-details-col">
                <label for="sex" class="form-label">Sex:</label>
                <select class="form-select" id="sex" name="sex" required>
                  <option value=""></option>
                  <option value="1" {{ old('sex') === '1' ? 'selected' : '' }}>M</option>
                  <option value="2" {{ old('sex') === '2' ? 'selected' : '' }}>F</option>
                </select>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-vitals-item">
                <label for="height" class="form-label">Height:</label>
                <div class="input-group">
                  <input type="number"
                    class="form-control"
                    id="height"
                    name="height"
                    step="0.1"
                    min="30"
                    max="250"
                    value="{{ old('height') }}">
                  <span class="input-group-text unit-text">cm</span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-vitals-item">
                <label for="weight" class="form-label">Weight:</label>
                <div class="input-group">
                  <input type="number"
                    class="form-control"
                    id="weight"
                    name="weight"
                    step="0.1"
                    min="1"
                    max="300"
                    value="{{ old('weight') }}">
                  <span class="input-group-text unit-text">kg</span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-vitals-item">
                <label for="bmi" class="form-label">BMI:</label>
                <input type="text"
                  class="form-control"
                  id="bmi"
                  name="bmi"
                  readonly
                  value="{{ old('bmi') }}">
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-vitals-item">
                @php $typeOfScreeningValue = old('type_of_screening'); @endphp
                <label for="type_of_screening" class="form-label">Type of assessment</label>
                <select class="form-select" id="type_of_screening" name="type_of_screening" required>
                  <option value="" {{ $typeOfScreeningValue === null ? 'selected' : '' }}></option>
                  <option value="New" {{ $typeOfScreeningValue === 'New' ? 'selected' : '' }}>New</option>
                  @if ($typeOfScreeningValue === 'Follow-up')
                  <option value="Follow-up" selected>Follow up</option>
                  @endif
                  <option value="Recheck" {{ $typeOfScreeningValue === 'Recheck' ? 'selected' : '' }}>Recheck</option>
                </select>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-entry-mode">
                <label for="mode_of_entry_dropdown" class="form-label">Mode of entry:</label>
                <div class="dropdown mode-entry-dropdown">
                  <button class="form-select text-start mode-entry-toggle"
                    type="button"
                    id="mode_of_entry_dropdown"
                    data-bs-toggle="dropdown"
                    data-bs-auto-close="outside"
                    aria-expanded="false"
                    data-placeholder="Select mode">
                    {{ empty($selectedModeOfEntry) ? 'Select mode' : implode(', ', array_map(fn($value) => $modeOfEntryOptions[$value] ?? $value, $selectedModeOfEntry)) }}
                  </button>
                  <div class="dropdown-menu dropdown-menu-dark mode-entry-menu" aria-labelledby="mode_of_entry_dropdown">
                    @foreach ($modeOfEntryOptions as $modeValue => $modeLabel)
                    <label class="dropdown-item mode-entry-option" for="mode_of_entry_{{ $modeValue }}">
                      <input class="form-check-input mode-entry-checkbox"
                        type="checkbox"
                        id="mode_of_entry_{{ $modeValue }}"
                        name="mode_of_entry[]"
                        value="{{ $modeValue }}"
                        data-label="{{ $modeLabel }}"
                        {{ in_array($modeValue, $selectedModeOfEntry, true) ? 'checked' : '' }}>
                      <span>{{ $modeLabel }}</span>
                    </label>
                    @endforeach
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-entry-screening-date">
                <label for="dofscrrening" class="form-label">Date of screening:</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="dofscrrening"
                    name="dofscrrening"
                    required
                    data-date-format="true"
                    value="{{ old('dofscrrening') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-entry-next-visit">
                <label for="dofnv" class="form-label">Date of next visit:</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="dofnv"
                    name="dofnv"
                    data-date-format="true"
                    value="{{ old('dofnv') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-entry-phone">
                <label for="phone" class="form-label">Phone no.</label>
                <input type="text"
                  class="form-control"
                  id="phone"
                  name="phone"
                  inputmode="tel"
                  autocomplete="tel"
                  maxlength="50"
                  value="{{ old('phone') }}">
              </div>
            </div>

            {{-- Symptoms / Risks section --}}
            <hr class="my-4">
            <h5 class="text-light">Symptoms/Risks</h5>
            <div class="row g-3">
              <div class="col-12">
                <label for="main_presenting_complaint" class="form-label">Main presenting complaint</label>
                <textarea class="form-control"
                  id="main_presenting_complaint"
                  name="main_presenting_complaint"
                  rows="2">{{ old('main_presenting_complaint') }}</textarea>
              </div>
              <div class="col-12">
                <small class="text-muted d-block mb-2">Please fill in ALL symptoms &amp; risk factors. For each symptom row: select symptom + days, or tick the right-side box to confirm "asked/no".</small>
                <div class="p-3 rounded symptom-dropdown">
                  <div class="symptom-risk-grid">
                    @foreach ($symptomRiskRows as $row)
                    @php
                    $slug = $row['symptom']['slug'];
                    $symptomLabel = $row['symptom']['label'];
                    $symptomPresent = old("symptoms.$slug.present");
                    $symptomReviewed = old("symptoms_reviewed.$slug");
                    $symptomChecked = $symptomPresent == '1' && $symptomReviewed != '1';
                    $symptomNoChecked = $symptomReviewed == '1';
                    $risk = $row['risk'];
                    @endphp
                    <div class="symptom-risk-row">
                      <div class="symptom-cell">
                        <div class="symptom-entry">
                          <div class="form-check mb-0">
                            <input class="form-check-input symptom-checkbox"
                              type="checkbox"
                              id="symptom_{{ $slug }}"
                              name="symptoms[{{ $slug }}][present]"
                              value="1"
                              {{ $symptomChecked ? 'checked' : '' }}
                              {{ $symptomNoChecked ? 'disabled' : '' }}>
                            <label class="form-check-label symptom-label" for="symptom_{{ $slug }}">{{ $symptomLabel }}</label>
                          </div>
                          <input type="number"
                            class="form-control form-control-sm symptom-days"
                            id="symptom_{{ $slug }}_days"
                            name="symptoms[{{ $slug }}][days]"
                            min="0"
                            max="365"
                            placeholder="days"
                            value="{{ old("symptoms.$slug.days") }}"
                            {{ $symptomChecked ? '' : 'disabled' }}>
                          <div class="form-check symptom-reviewed mb-0">
                            <input class="form-check-input"
                              type="checkbox"
                              id="symptom_{{ $slug }}_reviewed"
                              name="symptoms_reviewed[{{ $slug }}]"
                              value="1"
                              title="Tick if {{ strtolower($symptomLabel) }} is asked and not present"
                              {{ $symptomNoChecked ? 'checked' : '' }}
                              {{ $symptomChecked ? 'disabled' : '' }}>
                            <label class="form-check-label" for="symptom_{{ $slug }}_reviewed">No</label>
                          </div>
                        </div>
                      </div>
                      <div class="risk-cell">
                        <label for="{{ $risk['id'] }}" class="form-label">{{ $risk['label'] }}</label>
                        @if (!empty($risk['tx']))
                        <div class="risk-inline">
                          <select class="form-select" id="{{ $risk['id'] }}" name="{{ $risk['field'] }}" required>
                            <option value="" {{ old($risk['field']) === null ? 'selected' : '' }}></option>
                            @foreach ($risk['options'] as [$value, $optionLabel])
                            <option value="{{ $value }}" {{ old($risk['field']) === $value ? 'selected' : '' }}>{{ $optionLabel }}</option>
                            @endforeach
                          </select>
                          <div class="tx-inline" id="{{ $risk['tx']['wrap_id'] }}">
                            <label for="{{ $risk['tx']['id'] }}" class="form-label visually-hidden">Tx status</label>
                            <select class="form-select" id="{{ $risk['tx']['id'] }}" name="{{ $risk['tx']['field'] }}">
                              <option value="" {{ old($risk['tx']['field']) === null ? 'selected' : '' }}></option>
                              @foreach ($risk['tx']['options'] as [$txValue, $txLabel])
                              <option value="{{ $txValue }}" {{ old($risk['tx']['field']) === $txValue ? 'selected' : '' }}>{{ $txLabel }}</option>
                              @endforeach
                            </select>
                          </div>
                        </div>
                        @else
                        <select class="form-select" id="{{ $risk['id'] }}" name="{{ $risk['field'] }}" required>
                          <option value="" {{ old($risk['field']) === null ? 'selected' : '' }}></option>
                          @foreach ($risk['options'] as [$value, $optionLabel])
                          <option value="{{ $value }}" {{ old($risk['field']) === $value ? 'selected' : '' }}>{{ $optionLabel }}</option>
                          @endforeach
                        </select>
                        @endif
                      </div>
                    </div>
                    @endforeach
                  </div>
                </div>
              </div>
            </div>

            {{-- Chest X-ray / Sputum / Diagnostics section --}}
            <hr class="my-4">
            <div class="row g-3">
              <div class="col-12 col-md-6 col-lg-2 check-inline-group tablet-cxr-check">
                <label for="chest_xray_check" class="form-label">Chest X-ray</label>
                <input type="hidden" id="chest_xray" name="chest_xray" value="{{ old('chest_xray') === '1' ? '1' : '2' }}">
                <div class="yes-no-toggle">
                  <div class="form-check">
                    <input class="form-check-input"
                      type="checkbox"
                      id="chest_xray_check"
                      {{ old('chest_xray') === '1' ? 'checked' : '' }}>
                    <label class="form-check-label" for="chest_xray_check">Yes</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-cxr-date">
                <label for="chest_xray_date" class="form-label">Date</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="chest_xray_date"
                    name="chest_xray_date"
                    data-date-format="true"
                    value="{{ old('chest_xray_date') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-cxr-facility">
                <label for="chest_xray_fac" class="form-label ">Facility</label>
                <select class="form-select" id="chest_xray_fac" name="chest_xray_fac">
                  <option value="" {{ old('chest_xray_fac') === null ? 'selected' : '' }}></option>
                  <option value="1" {{ old('chest_xray_fac') === '1' ? 'selected' : '' }}>MAM Xray</option>
                  <option value="2" {{ old('chest_xray_fac') === '2' ? 'selected' : '' }}>Outside facility</option>
                </select>
              </div>
              <div class="col-12 col-md-6 col-lg-4 xray-upload-field">
                <label for="xray_image" class="form-label">X-ray image (optional)</label>
                <input type="hidden" name="xray_image_path" value="{{ old('xray_image_path') }}">
                <input type="file"
                  class="form-control"
                  id="xray_image"
                  name="xray_image"
                  accept=".jpg,.jpeg,.png,.webp,image/*">
                @if (old('xray_image_path'))
                <small class="d-block mt-1">
                  Current image:
                  <a href="{{ asset('storage/' . old('xray_image_path')) }}" target="_blank" rel="noopener">view</a>
                </small>
                @endif
              </div>
              <div class="col-12 col-md-6 col-lg-2">
                <label for="md_diagnosis" class="form-label">MD diagnosis:</label>
                <select class="form-select" id="md_diagnosis" name="md_diagnosis">
                  <option value="" {{ old('md_diagnosis') === null ? 'selected' : '' }}></option>
                  <option value="1" {{ old('md_diagnosis') === '1' ? 'selected' : '' }}>Normal</option>
                  <option value="2" {{ old('md_diagnosis') === '2' ? 'selected' : '' }}>Active TB</option>
                  <option value="4" {{ old('md_diagnosis') === '4' ? 'selected' : '' }}>Old TB (scar)</option>
                  <option value="3" {{ old('md_diagnosis') === '3' ? 'selected' : '' }}>Other</option>
                </select>
              </div>
              <div class="col-12 col-md-6 col-lg-4">
                <label for="md_diagnosis_oth" class="form-label">Other</label>
                <input type="text"
                  class="form-control"
                  id="md_diagnosis_oth"
                  name="md_diagnosis_oth"
                  value="{{ old('md_diagnosis_oth') }}">
              </div>
              <div class="col-12 col-md-4 col-lg-1">
                <label for="cad_score" class="form-label">CAD Score</label>
                <input type="number"
                  class="form-control"
                  id="cad_score"
                  name="cad_score"
                  step="0.01"
                  min="0"
                  value="{{ old('cad_score') }}">
              </div>
              <div class="col-12 col-md-8 col-lg-5">
                <label for="comment" class="form-label">Comment</label>
                <input type="text"
                  class="form-control"
                  id="comment"
                  name="comment"
                  value="{{ old('comment') }}">
              </div>
              <div class="tablet-row-break"></div>
              <div class="col-12 col-md-6 col-lg-2 check-inline-group tablet-radio-request">
                <label for="radio_request_check" class="form-label">Radiologist requested</label>
                <input type="hidden" id="radio_request" name="radio_request" value="{{ old('radio_request') === '1' ? '1' : '2' }}">
                <div class="yes-no-toggle">
                  <div class="form-check">
                    <input class="form-check-input"
                      type="checkbox"
                      id="radio_request_check"
                      {{ old('radio_request') === '1' ? 'checked' : '' }}>
                    <label class="form-check-label" for="radio_request_check">Yes</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-radio-date">
                <label for="radio_request_date" class="form-label">Date</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="radio_request_date"
                    name="radio_request_date"
                    data-date-format="true"
                    value="{{ old('radio_request_date') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-radio-result">
                <label for="radiologist_result" class="form-label">Result:</label>
                <select class="form-select" id="radiologist_result" name="radiologist_result">
                  <option value="" {{ old('radiologist_result') === null ? 'selected' : '' }}></option>
                  <option value="1" {{ old('radiologist_result') === '1' ? 'selected' : '' }}>Normal</option>
                  <option value="2" {{ old('radiologist_result') === '2' ? 'selected' : '' }}>Active TB</option>
                  <option value="3" {{ old('radiologist_result') === '3' ? 'selected' : '' }}>Old TB (scar)</option>
                  <option value="4" {{ old('radiologist_result') === '4' ? 'selected' : '' }}>Other</option>
                </select>
              </div>
              <div class="col-12 col-md-6 col-lg-6 tablet-radio-other">
                <label for="radiologist_result_oth" class="form-label">Other</label>
                <input type="text"
                  class="form-control"
                  id="radiologist_result_oth"
                  name="radiologist_result_oth"
                  value="{{ old('radiologist_result_oth') }}">
              </div>
              <div class="tablet-row-break"></div>
              <div class="col-12 col-md-6 col-lg-2 check-inline-group tablet-sputum-check">
                <label for="sputum_afb_check" class="form-label">Sputum AFB</label>
                <input type="hidden" id="sputum_afb" name="sputum_afb" value="{{ old('sputum_afb') === '1' ? '1' : '2' }}">
                <div class="yes-no-toggle">
                  <div class="form-check">
                    <input class="form-check-input"
                      type="checkbox"
                      id="sputum_afb_check"
                      {{ old('sputum_afb') === '1' ? 'checked' : '' }}>
                    <label class="form-check-label" for="sputum_afb_check">Yes</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-sputum-date">
                <label for="sputum_afb_date" class="form-label">Date</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="sputum_afb_date"
                    name="sputum_afb_date"
                    data-date-format="true"
                    value="{{ old('sputum_afb_date') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-sputum-result">
                <label for="sputum_afb_res" class="form-label">Result:</label>
                <select class="form-select" id="sputum_afb_res" name="sputum_afb_res">
                  <option value="" {{ old('sputum_afb_res') === null ? 'selected' : '' }}></option>
                  <option value="1" {{ old('sputum_afb_res') === '1' ? 'selected' : '' }}>Pos</option>
                  <option value="2" {{ old('sputum_afb_res') === '2' ? 'selected' : '' }}>Neg</option>
                </select>
              </div>
              <div class="tablet-row-break"></div>
              @php $geneXpertSpecimens = $selectedSpecimens(old('type_of_specimen_geneXpert')); @endphp
              <div class="col-12 col-md-6 col-lg-2 check-inline-group tablet-genexpert-check">
                <label for="genexpert_check" class="form-label">GeneXpert</label>
                <input type="hidden" id="genexpert" name="genexpert" value="{{ old('genexpert') === '1' ? '1' : '2' }}">
                <div class="yes-no-toggle">
                  <div class="form-check">
                    <input class="form-check-input"
                      type="checkbox"
                      id="genexpert_check"
                      {{ old('genexpert') === '1' ? 'checked' : '' }}>
                    <label class="form-check-label" for="genexpert_check">Yes</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-genexpert-date">
                <label for="genexpert_date" class="form-label">Date</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="genexpert_date"
                    name="genexpert_date"
                    data-date-format="true"
                    value="{{ old('genexpert_date') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-3 tablet-genexpert-specimen">
                <label class="form-label">Type of Specimen</label>
                <div class="d-flex flex-wrap gap-3 specimen-checkbox-group">
                  <div class="form-check specimen-check mb-0">
                    <input class="form-check-input"
                      type="checkbox"
                      id="type_of_specimen_geneXpert_sputum"
                      name="type_of_specimen_geneXpert[]"
                      value="Sputum"
                      {{ in_array('Sputum', $geneXpertSpecimens, true) ? 'checked' : '' }}>
                    <label class="form-check-label specimen-label" for="type_of_specimen_geneXpert_sputum">Sputum</label>
                  </div>
                  <div class="form-check specimen-check mb-0">
                    <input class="form-check-input"
                      type="checkbox"
                      id="type_of_specimen_geneXpert_stool"
                      name="type_of_specimen_geneXpert[]"
                      value="Stool"
                      {{ in_array('Stool', $geneXpertSpecimens, true) ? 'checked' : '' }}>
                    <label class="form-check-label specimen-label" for="type_of_specimen_geneXpert_stool">Stool</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-genexpert-result">
                <label for="genexpert_res" class="form-label">Result:</label>
                <select class="form-select" id="genexpert_res" name="genexpert_res">
                  <option value="" {{ old('genexpert_res') === null ? 'selected' : '' }}></option>
                  <option value="1" {{ old('genexpert_res') === '1' ? 'selected' : '' }}>N</option>
                  <option value="2" {{ old('genexpert_res') === '2' ? 'selected' : '' }}>T</option>
                  <option value="3" {{ old('genexpert_res') === '3' ? 'selected' : '' }}>TT</option>
                  <option value="4" {{ old('genexpert_res') === '4' ? 'selected' : '' }}>RR</option>
                  <option value="5" {{ old('genexpert_res') === '5' ? 'selected' : '' }}>TI</option>
                  <option value="6" {{ old('genexpert_res') === '6' ? 'selected' : '' }}>Invalid</option>
                </select>
              </div>
              <div class="tablet-row-break"></div>
              @php $truenatSpecimens = $selectedSpecimens(old('type_of_specimen_truenat')); @endphp
              <div class="col-12 col-md-6 col-lg-2 check-inline-group tablet-truenat-check">
                <label for="truenat_check" class="form-label">Truenat</label>
                <input type="hidden" id="truenat" name="truenat" value="{{ old('truenat') === '1' ? '1' : '2' }}">
                <div class="yes-no-toggle">
                  <div class="form-check">
                    <input class="form-check-input"
                      type="checkbox"
                      id="truenat_check"
                      {{ old('truenat') === '1' ? 'checked' : '' }}>
                    <label class="form-check-label" for="truenat_check">Yes</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-truenat-date">
                <label for="truenat_date" class="form-label">Date</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="truenat_date"
                    name="truenat_date"
                    data-date-format="true"
                    value="{{ old('truenat_date') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-3 tablet-truenat-specimen">
                <label class="form-label">Type of Specimen</label>
                <div class="d-flex flex-wrap gap-3 specimen-checkbox-group">
                  <div class="form-check specimen-check mb-0">
                    <input class="form-check-input"
                      type="checkbox"
                      id="type_of_specimen_truenat_sputum"
                      name="type_of_specimen_truenat[]"
                      value="Sputum"
                      {{ in_array('Sputum', $truenatSpecimens, true) ? 'checked' : '' }}>
                    <label class="form-check-label specimen-label" for="type_of_specimen_truenat_sputum">Sputum</label>
                  </div>
                  <div class="form-check specimen-check mb-0">
                    <input class="form-check-input"
                      type="checkbox"
                      id="type_of_specimen_truenat_stool"
                      name="type_of_specimen_truenat[]"
                      value="Stool"
                      {{ in_array('Stool', $truenatSpecimens, true) ? 'checked' : '' }}>
                    <label class="form-check-label specimen-label" for="type_of_specimen_truenat_stool">Stool</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-truenat-result">
                <label for="truenat_res" class="form-label">Result:</label>
                <select class="form-select" id="truenat_res" name="truenat_res">
                  <option value="" {{ old('truenat_res') === null ? 'selected' : '' }}></option>
                  <option value="1" {{ old('truenat_res') === '1' ? 'selected' : '' }}>N</option>
                  <option value="2" {{ old('truenat_res') === '2' ? 'selected' : '' }}>T</option>
                  <option value="3" {{ old('truenat_res') === '3' ? 'selected' : '' }}>RR</option>
                  <option value="4" {{ old('truenat_res') === '4' ? 'selected' : '' }}>TI</option>
                  <option value="5" {{ old('truenat_res') === '5' ? 'selected' : '' }}>Invalid</option>
                </select>
              </div>
              <div class="tablet-row-break"></div>
              <div class="col-12 col-md-6 col-lg-2 check-inline-group tablet-hiv-check">
                <label for="hiv_det_tested_check" class="form-label">HIV (determine)</label>
                <input type="hidden" id="hiv_det_tested" name="hiv_det" value="{{ old('hiv_det') === '1' ? '1' : '2' }}">
                <div class="yes-no-toggle">
                  <div class="form-check">
                    <input class="form-check-input"
                      type="checkbox"
                      id="hiv_det_tested_check"
                      {{ old('hiv_det') === '1' ? 'checked' : '' }}>
                    <label class="form-check-label" for="hiv_det_tested_check">Yes</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-hiv-date">
                <label for="hiv_det_date" class="form-label">Date</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="hiv_det_date"
                    name="hiv_det_date"
                    data-date-format="true"
                    value="{{ old('hiv_det_date') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-hiv-result">
                <label for="hiv_det" class="form-label">Result:</label>
                <select class="form-select" id="hiv_det" name="hiv_det_res">
                  <option value="" {{ old('hiv_det_res') === null ? 'selected' : '' }}></option>
                  <option value="1" {{ old('hiv_det_res') === '1' ? 'selected' : '' }}>R</option>
                  <option value="2" {{ old('hiv_det_res') === '2' ? 'selected' : '' }}>NR</option>
                </select>
              </div>
            </div>

            {{-- Diagnosis and Management section --}}
            <hr class="my-4">
            <h5 class="text-light">Diagnosis and Management</h5>
            <div class="row g-3">
              <div class="tablet-row-break"></div>
              <div class="col-12 col-md-6 col-lg-2 check-inline-group tablet-antibiotics-check">
                <label for="antibiotics" class="form-label">Antibiotics</label>
                <input type="hidden" id="antibiotics" name="antibiotics" value="{{ old('antibiotics') === '1' ? '1' : '2' }}">
                <div class="yes-no-toggle">
                  <div class="form-check">
                    <input class="form-check-input"
                      type="checkbox"
                      id="antibiotics_check"
                      {{ old('antibiotics') === '1' ? 'checked' : '' }}>
                    <label class="form-check-label" for="antibiotics_check">Yes</label>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-antibiotics-date">
                <label for="antibiotic_date" class="form-label">Date</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="antibiotic_date"
                    name="antibiotic_date"
                    data-date-format="true"
                    value="{{ old('antibiotic_date') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-8 col-lg-8 tablet-antibiotics-drug">
                <label for="drug" class="form-label">Drug:</label>
                <input type="text"
                  class="form-control"
                  id="drug"
                  name="drug"
                  value="{{ old('drug') }}">
              </div>
              <div class="w-100"></div>
              <div class="col-12 col-md-6 col-lg-2 tablet-tb-treat-date d-none">
                <label for="tb_treat_date" class="form-label">Date</label>
                <div class="input-group">
                  <input type="text"
                    class="form-control Gdate"
                    id="tb_treat_date"
                    name="tb_treat_date"
                    data-date-format="true"
                    disabled
                    value="{{ old('tb_treat_date') }}">
                  <span class="input-group-text dateimg">
                    <i class="bi bi-calendar3"></i>
                  </span>
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-2 tablet-tb-treat-regimen d-none">
                <label for="tb_treat_regimen" class="form-label">Regimen:</label>
                <select class="form-select" id="tb_treat_regimen" name="tb_treat_regimen" disabled>
                  <option value="" {{ old('tb_treat_regimen') === null ? 'selected' : '' }}></option>
                  <option value="1" {{ old('tb_treat_regimen') === '1' ? 'selected' : '' }}>IR</option>
                  <option value="2" {{ old('tb_treat_regimen') === '2' ? 'selected' : '' }}>RR</option>
                  <option value="3" {{ old('tb_treat_regimen') === '3' ? 'selected' : '' }}>CR</option>
                  <option value="4" {{ old('tb_treat_regimen') === '4' ? 'selected' : '' }}>MDR</option>
                </select>
              </div>
              <div class="col-12 col-md-6 col-lg-6 tablet-manage-other-full d-none">
                <label for="manage_oth" class="form-label">Other</label>
                <input type="text"
                  class="form-control"
                  id="manage_oth"
                  name="manage_oth"
                  disabled
                  value="{{ old('manage_oth') }}">
              </div>
              <div class="w-100"></div>
              <div class="col-12 tablet-tb-diagnosis-full">
                <div class="pretb-subtitle-label">TB Diagnosis</div>
                <div class="d-flex flex-wrap gap-3 tb-diagnosis-group">
                  @foreach (['DSTB', 'DRTB', 'No TB', 'Need recheck assessment'] as $tbDiagnosisOption)
                  <div class="form-check tb-diagnosis-check mb-0">
                    <input class="form-check-input"
                      type="radio"
                      id="tb_diagnosis_{{ $loop->index }}"
                      name="tb_diagnosis"
                      value="{{ $tbDiagnosisOption }}"
                      {{ old('tb_diagnosis') === $tbDiagnosisOption ? 'checked' : '' }}>
                    <label class="form-check-label tb-diagnosis-label" for="tb_diagnosis_{{ $loop->index }}">{{ $tbDiagnosisOption }}</label>
                  </div>
                  @endforeach
                </div>
              </div>
              <div class="w-100"></div>
              <div class="col-12 tablet-treatment-status-full">
                <div class="pretb-subtitle-label">If diagnosed as TB</div>
                <div class="d-flex flex-wrap gap-3 treatment-status-group">
                  @foreach (['Rx at MAM-NTP', 'Refer to NTP', 'LTFU', 'Expired', 'Other'] as $treatmentStatusOption)
                  <div class="form-check treatment-status-check mb-0">
                    <input class="form-check-input"
                      type="radio"
                      id="treatment_status_{{ $loop->index }}"
                      name="treatment_status"
                      value="{{ $treatmentStatusOption }}"
                      {{ old('treatment_status') === $treatmentStatusOption ? 'checked' : '' }}>
                    <label class="form-check-label treatment-status-label" for="treatment_status_{{ $loop->index }}">{{ $treatmentStatusOption }}</label>
                  </div>
                  @endforeach
                </div>
              </div>
              <div class="col-12 col-md-6 col-lg-4 {{ old('treatment_status') === 'Other' ? '' : 'd-none' }}" id="treatment_status_other_wrap">
                <label for="treatment_status_other" class="form-label">Other</label>
                <input type="text"
                  class="form-control"
                  id="treatment_status_other"
                  name="treatment_status_other"
                  value="{{ old('treatment_status_other') }}">
              </div>
              <div class="w-100"></div>
              <div class="col-12 col-md-6 col-lg-6 tablet-manage-remark-full">
                <label for="remark" class="form-label">Remark</label>
                <input type="text"
                  class="form-control"
                  id="remark"
                  name="remark"
                  value="{{ old('remark') }}">
              </div>
              <div class="w-100"></div>
              <div class="col-12 col-md-6 col-lg-2">
                <label for="md" class="form-label">MD</label>
                <select class="form-select" id="md" name="md">
                  <option value="" {{ old('md') === null ? 'selected' : '' }}></option>
                  @foreach (($mdInitials ?? []) as $mdInitial)
                  <option value="{{ $mdInitial }}" {{ old('md') === (string) $mdInitial ? 'selected' : '' }}>{{ $mdInitial }}</option>
                  @endforeach
                  @if (old('md') !== null && old('md') !== '' && !in_array(old('md'), $mdInitials ?? [], true))
                  <option value="{{ old('md') }}" selected>{{ old('md') }}</option>
                  @endif
                </select>
              </div>
              <div class="w-100"></div>
              <div class="col-12 text-end pt-2">
                @if ($editingId)
                <button type="submit"
                  class="btn btn-outline-danger me-2"
                  form="pretb-delete-form"
                  formnovalidate
                  onclick="return confirm('Delete this Pre-TB record? This cannot be undone.');">Delete</button>
                @endif
                <button type="submit" class="btn btn-primary px-4">{{ $editingId ? 'Save update locally' : 'Save locally' }}</button>
              </div>
            </div>
          </form>

          @if ($editingId)
          <form method="POST" action="{{ route('pretb_record.destroy', $editingId) }}" id="pretb-delete-form" class="d-none">
            @csrf
            @method('DELETE')
          </form>
          @endif
        </div>
      </div>
    </div>
  </div>
</div>
@endauth
@endsection

@push('scripts')
<script src="{{ asset('js/TbSection/preTbRecord.js') }}"></script>
<script src="{{ asset('js/TbSection/preTbRecordSync.js') }}?v={{ filemtime(public_path('js/TbSection/preTbRecordSync.js')) }}"></script>
@endpush
