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

@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:16px 20px; box-shadow:0 1px 6px rgba(0,0,0,.08); margin-bottom:14px; border:1px solid #e8ecf1; }
.filter-row  { display:flex; gap:10px; flex-wrap:wrap; align-items:flex-end; }
.filter-field { display:flex; flex-direction:column; gap:4px; }
.filter-label { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#64748b; white-space:nowrap; }
.filter-field .form-control { height:34px; font-size:12px; border-radius:7px; border:1.5px solid #e2e8f0; }
#rxq_table td { vertical-align:middle; font-size:12.5px; }
#rxq_table_wrapper .dataTables_filter { display:none; }
.vc-table-box { background:#fff; border-radius:10px; overflow:hidden; box-shadow:0 1px 6px rgba(0,0,0,.08); border:1px solid #e8ecf1; }
.rxq-item { border:1px solid #eef2f7; border-radius:8px; padding:10px 12px; margin-bottom:8px; }
.rxq-item.done { background:#f0fdf4; border-color:#bbf7d0; }
.rxq-pill { display:inline-block; background:#f1f5f9; border:1px solid #e2e8f0; border-radius:12px; padding:1px 9px; font-size:11px; color:#475569; margin-right:5px; }
.rxq-ctrl { color:#b91c1c; font-weight:700; }
</style>
@include('clinicCore::partials._mobile_responsive')
@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-prescription-bottle-alt"></i>
        @lang('clinicCore::lang.pharmacy_dispense')
    </div>
</div>

<div class="filter-card">
    <div class="filter-row">
        <div class="filter-field" style="min-width:180px;">
            <span class="filter-label">@lang('clinicCore::lang.doctors')</span>
            <select id="rxq_doctor" class="form-control">
                <option value="">—</option>
                @foreach($doctors as $d)
                <option value="{{ $d->id }}">{{ $d->name }}</option>
                @endforeach
            </select>
        </div>
        <div class="filter-field" style="min-width:140px;">
            <span class="filter-label">@lang('clinicCore::lang.date_from')</span>
            <input type="text" id="rxq_from" class="form-control clc-datepick" placeholder="{{ session('business.date_format','d M Y') }}">
        </div>
        <div class="filter-field" style="min-width:140px;">
            <span class="filter-label">@lang('clinicCore::lang.date_to')</span>
            <input type="text" id="rxq_to" class="form-control clc-datepick" placeholder="{{ session('business.date_format','d M Y') }}">
        </div>
        <div class="filter-field" style="align-self:flex-end;">
            <button id="rxq_clear" class="btn btn-default" style="height:34px;">
                <i class="fa fa-times-circle" style="color:#ef4444;"></i> @lang('clinicCore::lang.cancel')
            </button>
        </div>
    </div>
</div>

<div class="vc-table-box">
    <div style="padding:14px;">
        <table class="table table-bordered table-striped table-hover" id="rxq_table" style="font-size:12.5px;">
            <thead style="background:#f8fafc;">
                <tr>
                    <th>@lang('clinicCore::lang.ref_no')</th>
                    <th>@lang('clinicCore::lang.patients')</th>
                    <th>@lang('clinicCore::lang.patient_contacts')</th>
                    <th>@lang('clinicCore::lang.doctors')</th>
                    <th>@lang('clinicCore::lang.date')</th>
                    <th>@lang('clinicCore::lang.dispense_progress')</th>
                    <th>@lang('clinicCore::lang.actions')</th>
                </tr>
            </thead>
        </table>
    </div>
</div>
</section>

{{-- ── Dispense panel modal ─────────────────────────────────────────────── --}}
<div id="rxqModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document"><div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><i class="fa fa-pills"></i> <span id="rxq_title"></span></h4>
    </div>
    <div class="modal-body" id="rxq_body">
        <div style="text-align:center;padding:20px;color:#94a3b8;"><i class="fa fa-spinner fa-spin"></i></div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">@lang('clinicCore::lang.close')</button>
    </div>
  </div></div>
</div>

{{-- ── Single-item dispense modal (FEFO guidance + witness) ─────────────── --}}
<div id="rxqItemModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document"><div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><i class="fa fa-pills"></i> @lang('clinicCore::lang.dispense') <span id="rxqi_name"></span></h4>
    </div>
    <div class="modal-body">
        <div id="rxqi_loading" style="text-align:center;padding:16px;color:#94a3b8;"><i class="fa fa-spinner fa-spin"></i></div>
        <div id="rxqi_msg" class="alert alert-warning" style="display:none;"></div>
        <div id="rxqi_controlled" class="alert alert-danger" style="display:none;">
            <i class="fa fa-lock"></i> <strong id="rxqi_sched"></strong> — @lang('clinicCore::lang.dispense_witness_required')
        </div>
        <div id="rxqi_form" style="display:none;">
            <div class="form-group">
                <label>@lang('clinicCore::lang.dispense_batch_guidance') <small class="text-muted">(FEFO)</small></label>
                <select id="rxqi_batch" class="form-control"></select>
                <small class="text-muted">@lang('clinicCore::lang.dispense_batch_display_only')</small>
            </div>
            <div class="form-group" id="rxqi_witness_group" style="display:none;">
                <label>@lang('clinicCore::lang.dispense_witness')</label>
                <select id="rxqi_witness" class="form-control"></select>
            </div>
            <div class="form-group">
                <label>@lang('clinicCore::lang.dispense_qty') <span id="rxqi_unit" class="text-muted"></span></label>
                <input type="number" step="0.0001" min="0.0001" id="rxqi_qty" class="form-control">
            </div>
            <div class="form-group">
                <label>Location</label>
                <select id="rxqi_location" class="form-control">
                    @foreach((auth()->user()->business?->locations ?? collect()) as $loc)
                        <option value="{{ $loc->id }}">{{ $loc->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
        <button type="button" class="btn btn-success" id="rxqi_save"><i class="fa fa-check"></i> @lang('clinicCore::lang.dispense')</button>
    </div>
  </div></div>
</div>
@endsection

@section('javascript')
<script>
var rxqTable = null;
var rxqToken = '{{ csrf_token() }}';
var ITEM_BASE = '{{ url('/clinic/prescriptions/items') }}';
var currentRxId = null, currentItemId = null, itemControlled = false;

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

$(document).ready(function () {
    if ($.fn.datepicker) { $('.clc-datepick').datepicker({ autoclose:true, format:'{{ strtolower(str_replace(["d","M","Y"],["dd","M","yyyy"], session("business.date_format","d M Y"))) }}' }); }

    rxqTable = $('#rxq_table').DataTable({
        processing: true, serverSide: true, order: [[4, 'desc']],
        ajax: {
            url: '{{ route('clinic.pharmacy.list') }}',
            data: function (d) {
                d.filter_doctor    = $('#rxq_doctor').val();
                d.filter_date_from = $('#rxq_from').val();
                d.filter_date_to   = $('#rxq_to').val();
            }
        },
        columns: [
            { data: 'ref_no_col',          name: 'ref_no',          orderable: false },
            { data: 'pet_name',            name: 'pet_name',        orderable: false },
            { data: 'owner_name',          name: 'owner_name',      orderable: false },
            { data: 'doctor_name',         name: 'doctor_name',     orderable: false },
            { data: 'prescribed_date_col', name: 'prescribed_date' },
            { data: 'progress_col',        name: 'progress',        orderable: false, searchable: false },
            { data: 'action',              name: 'action',          orderable: false, searchable: false }
        ],
        pageLength: 25,
        language: { processing: '<i class="fa fa-spinner fa-spin"></i> Loading…' }
    });

    $('#rxq_doctor').on('change', function () { rxqTable.ajax.reload(); });
    $('#rxq_from, #rxq_to').on('change', function () { rxqTable.ajax.reload(); });
    $('#rxq_clear').on('click', function () {
        $('#rxq_doctor').val(''); $('#rxq_from,#rxq_to').val('');
        rxqTable.ajax.reload();
    });
});

// ── Open dispense panel for one prescription ──
$(document).on('click', '.btn-open-rx', function () {
    currentRxId = $(this).data('id');
    $('#rxq_title').text('');
    $('#rxq_body').html('<div style="text-align:center;padding:20px;color:#94a3b8;"><i class="fa fa-spinner fa-spin"></i></div>');
    $('#rxqModal').modal('show');
    loadRxPanel();
});

function loadRxPanel() {
    $.get('{{ url('/clinic/pharmacy') }}/' + currentRxId + '/items').done(function (res) {
        renderRxPanel(res);
    }).fail(function () {
        $('#rxq_body').html('<div class="alert alert-danger">Could not load prescription.</div>');
    });
}

function renderRxPanel(res) {
    $('#rxq_title').text(res.ref_no + ' · ' + (res.patient || ''));
    var h = '';
    if (res.warnings && res.warnings.length) {
        h += '<div class="alert alert-warning"><strong><i class="fa fa-exclamation-triangle"></i> @lang('clinicCore::lang.safety_warnings')</strong><ul style="margin:6px 0 0;">';
        res.warnings.forEach(function (w) {
            h += '<li>' + rxqEsc(w.message) + (w.block ? ' <span class="label label-danger">@lang('clinicCore::lang.blocking')</span>' : '') + '</li>';
        });
        h += '</ul></div>';
    }
    res.items.forEach(function (it) {
        var done = !!it.dispensed_at;
        h += '<div class="rxq-item ' + (done ? 'done' : '') + '">'
           + '<div style="display:flex;justify-content:space-between;align-items:center;gap:10px;">'
           + '<div><strong>' + rxqEsc(it.medicine_name) + '</strong>'
           + (it.controlled ? ' <span class="rxq-ctrl"><i class="fa fa-lock"></i> ' + rxqEsc(it.schedule_label || 'Controlled') + '</span>' : '')
           + '<div style="margin-top:4px;">'
           + (it.dosage ? '<span class="rxq-pill">' + rxqEsc(it.dosage) + '</span>' : '')
           + (it.frequency ? '<span class="rxq-pill">' + rxqEsc(it.frequency) + '</span>' : '')
           + (it.quantity ? '<span class="rxq-pill">Qty: ' + rxqEsc(it.quantity) + '</span>' : '')
           + (it.prn ? '<span class="rxq-pill">PRN' + (it.prn_reason ? ' — ' + rxqEsc(it.prn_reason) : '') + '</span>' : '')
           + '</div></div>';
        if (done) {
            h += '<span class="label label-success"><i class="fa fa-check"></i> ' + rxqEsc(it.dispensed_at) + (it.dispensed_qty ? ' · ' + rxqEsc(it.dispensed_qty) : '') + '</span>';
        } else {
            h += '<button class="btn btn-sm btn-warning rxqi-open" data-id="' + it.id + '" data-name="' + rxqEsc(it.medicine_name) + '"><i class="fa fa-pills"></i> @lang('clinicCore::lang.dispense')</button>';
        }
        h += '</div></div>';
    });
    $('#rxq_body').html(h || '<div class="text-muted">@lang('clinicCore::lang.no_items')</div>');
}

// ── Open single-item dispense modal ──
$(document).on('click', '.rxqi-open', function () {
    currentItemId = $(this).data('id');
    $('#rxqi_name').text($(this).data('name'));
    $('#rxqi_loading').show();
    $('#rxqi_form').hide();
    $('#rxqi_msg').hide();
    $('#rxqi_controlled').hide();
    $('#rxqi_witness_group').hide();
    $('#rxqi_batch').empty(); $('#rxqi_witness').empty();
    itemControlled = false;
    $('#rxqItemModal').modal('show');

    $.get(ITEM_BASE + '/' + currentItemId + '/dispense-options').done(function (res) {
        $('#rxqi_loading').hide();
        if (res.msg && !res.linked && !res.controlled) { $('#rxqi_msg').text(res.msg).show(); return; }
        itemControlled = !!res.controlled;
        $('#rxqi_unit').text(res.unit ? '(' + res.unit + ')' : '');
        if (itemControlled) {
            $('#rxqi_sched').text(res.schedule_label || 'Controlled');
            $('#rxqi_controlled').show();
            (res.witnesses || []).forEach(function (w) { $('#rxqi_witness').append('<option value="' + w.id + '">' + rxqEsc(w.name) + '</option>'); });
            $('#rxqi_witness_group').toggle((res.witnesses || []).length > 0);
        }
        if (res.batches && res.batches.length) {
            res.batches.forEach(function (b) {
                var lbl = 'Batch ' + (b.lot_number || '—') + ' · exp ' + (b.exp_date || '—') + ' · ' + b.qty_available + ' avail';
                $('#rxqi_batch').append('<option value="' + b.purchase_line_id + '">' + lbl + '</option>');
            });
        } else {
            $('#rxqi_batch').append('<option value="">@lang('clinicCore::lang.dispense_no_batch')</option>');
        }
        $('#rxqi_qty').val(res.prescribed_qty || 1);
        $('#rxqi_form').show();
    });
});

function rxqiDispense($btn, confirmed) {
    $.post(ITEM_BASE + '/' + currentItemId + '/dispense', {
        _token: rxqToken,
        purchase_line_id: $('#rxqi_batch').val() || '',
        qty: $('#rxqi_qty').val(),
        location_id: $('#rxqi_location').val(),
        witness_user_id: itemControlled ? $('#rxqi_witness').val() : '',
        safety_confirmed: confirmed ? 1 : 0
    }).done(function (res) {
        if (res.success) {
            if (window.toastr) toastr.success(res.msg + (res.rx_completed ? ' · @lang('clinicCore::lang.rx_completed')' : ''));
            $('#rxqItemModal').modal('hide');
            loadRxPanel();
            if (rxqTable) rxqTable.ajax.reload(null, false);
        }
    }).fail(function (xhr) {
        var j = xhr.responseJSON || {};
        if (j.blocking && !confirmed) {
            var lines = (j.warnings || []).map(function (w) { return '• ' + w.message; }).join('\n');
            if (window.confirm((j.msg || 'Safety warning.') + '\n\n' + lines + '\n\n@lang('clinicCore::lang.dispense_safety_confirm')')) {
                rxqiDispense($btn, true); return;
            }
        } else {
            if (window.toastr) toastr.error(j.msg || 'Could not dispense.');
        }
    }).always(function () {
        $btn.prop('disabled', false).html('<i class="fa fa-check"></i> @lang('clinicCore::lang.dispense')');
    });
}

$('#rxqi_save').on('click', function () {
    var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> …');
    rxqiDispense($btn, false);
});
</script>
@endsection
