@extends('layouts.app')

@section('title', 'Controlled Drug Register')

@section('css')
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header">
    <h1><i class="fa fa-shield-alt"></i> Controlled Drug Register
        <small style="color:#64748b;">Narcotics &amp; scheduled medicines</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="{{ route('clinic.dashboard') }}">@lang('clinicCore::lang.clinic')</a></li>
        <li class="active">Controlled Drug Register</li>
    </ol>
</section>

<section class="content">

    <div class="alert alert-warning" style="font-size:12.5px;line-height:1.55;">
        <i class="fa fa-info-circle"></i>
        Every IN and OUT for any medicine flagged as a controlled substance has to be recorded here with an
        immutable serial number, batch, running balance, issuing doctor and witness. Rows are <strong>insert-only</strong>
        — a mistake is fixed by adding a reversing entry, never by editing or deleting history.
        Mark a medicine as controlled from <a href="{{ route('clinic.medicines.index') }}">Pharmacy &rarr; edit medicine</a>.
    </div>

    {{-- Phase 3b — chain-of-custody integrity strip --}}
    <div class="alert" id="cr_integrity"
         style="font-size:12.5px;display:flex;align-items:center;gap:12px;background:#f1f5f9;border:1px solid #cbd5e1;color:#334155;">
        <i class="fa fa-fingerprint" style="font-size:18px;color:#475569;"></i>
        <div style="flex:1;">
            <strong>Chain integrity:</strong>
            @if($latestSeal)
                latest seal <code>{{ substr($latestSeal->hash, 0, 12) }}…</code>
                for <strong>{{ $latestSeal->seal_date->format('d M Y') }}</strong>
                ({{ $latestSeal->movement_count }} rows)
            @else
                <em>no seals yet</em>
            @endif
            @if($unsealedDays > 0)
                · <span style="color:#b45610;font-weight:700;">{{ $unsealedDays }} day{{ $unsealedDays==1?'':'s' }} still unsealed</span>
            @endif
            <span id="cr_verify_msg" style="margin-left:10px;"></span>
        </div>
        @can('clinic.manage_controlled')
        <button class="btn btn-xs btn-default" id="cr_seal_btn"><i class="fa fa-lock"></i> Seal now</button>
        <a class="btn btn-xs btn-default" href="{{ route('clinic.controlled-register.reconcile') }}">
            <i class="fa fa-balance-scale"></i> Stocktake
        </a>
        @endcan
        <a class="btn btn-xs btn-default" href="{{ route('clinic.controlled-register.print') }}" target="_blank">
            <i class="fa fa-print"></i> Statutory print
        </a>
        <button class="btn btn-xs btn-default" id="cr_verify_btn"><i class="fa fa-check-double"></i> Verify chain</button>
    </div>

    @if(($unverifiedCount ?? 0) > 0)
    <div class="alert alert-danger" style="font-size:12.5px;display:flex;align-items:center;gap:12px;">
        <i class="fa fa-exclamation-triangle" style="font-size:18px;"></i>
        <div style="flex:1;">
            <strong>{{ $unverifiedCount }} POS dispense{{ $unverifiedCount == 1 ? '' : 's' }}</strong>
            still need a verified issuing doctor + witness. They were auto-synced from POS sales without the cashier
            picking an authorised doctor. Click <strong>Resolve</strong> on each row below to attach the sign-off.
        </div>
        <button class="btn btn-sm btn-danger" id="filter_unverified">Show only unverified</button>
    </div>
    @endif

    @if(($expiringVets ?? collect())->isNotEmpty())
    <div class="alert alert-warning" style="font-size:12.5px;">
        <i class="fa fa-clock"></i> Permits requiring attention:
        @foreach($expiringVets as $av)
            @php $cls = $av->valid_until->isPast() ? 'danger' : 'warning'; @endphp
            <span class="label label-{{ $cls }}" style="margin-right:6px;">
                {{ optional($av->doctor)->name ?? '—' }}
                — {{ $av->valid_until->isPast() ? 'expired' : 'expires' }} {{ $av->valid_until->format('d M Y') }}
            </span>
        @endforeach
        <a href="{{ route('clinic.authorized-vets.index') }}" style="font-weight:600;">Manage authorised doctors →</a>
    </div>
    @endif

    {{-- Filters --}}
    <div class="box box-default" style="margin-bottom:14px;">
        <div class="box-body" style="padding:12px;">
            <div class="row">
                <div class="col-md-3">
                    <label>Medicine</label>
                    <select id="f_med" class="form-control input-sm">
                        <option value="">— All controlled medicines —</option>
                        @foreach($medicines as $m)
                            <option value="{{ $m->id }}">{{ $m->name }} <em>({{ \Modules\ClinicCore\Entities\ClcMedicine::schedules()[$m->controlled_schedule]['label'] ?? $m->controlled_schedule }})</em></option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label>Schedule</label>
                    <select id="f_schedule" class="form-control input-sm">
                        <option value="">All</option>
                        @foreach($schedules as $key => $cfg)
                            <option value="{{ $key }}">{{ $cfg['label'] }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label>Reason</label>
                    <select id="f_reason" class="form-control input-sm">
                        <option value="">All</option>
                        @foreach($reasons as $key => $cfg)
                            <option value="{{ $key }}">{{ $cfg['label'] }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label>From</label>
                    <input type="date" id="f_from" class="form-control input-sm">
                </div>
                <div class="col-md-2">
                    <label>To</label>
                    <input type="date" id="f_to" class="form-control input-sm">
                </div>
                <div class="col-md-1" style="padding-top:22px;text-align:right;">
                    @can('clinic.log_controlled')
                    <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#logMoveModal">
                        <i class="fa fa-plus"></i>
                    </button>
                    @endcan
                </div>
            </div>
        </div>
    </div>

    @if($medicines->isEmpty())
        <div class="alert alert-info" style="font-size:12.5px;">
            <i class="fa fa-info-circle"></i> No medicines are flagged as controlled yet.
            Open <a href="{{ route('clinic.medicines.index') }}">Pharmacy</a>, edit a medicine and pick a
            <strong>Controlled Substance Schedule</strong> in the orange panel to begin tracking it here.
        </div>
    @endif

    @component('components.widget', ['class' => 'box-primary'])
        <table class="table table-bordered table-striped" id="cr_table">
            <thead>
                <tr>
                    <th style="width:140px;">Serial / Date</th>
                    <th>Medicine</th>
                    <th style="width:90px;">Qty</th>
                    <th style="width:90px;">Balance</th>
                    <th style="width:120px;">Batch</th>
                    <th>Reason</th>
                    <th>Patient / Contact</th>
                    <th>Doctor &amp; sign-off</th>
                    <th>Notes</th>
                    <th style="width:110px;">Resolve</th>
                </tr>
            </thead>
        </table>
    @endcomponent
</section>

{{-- Resolve modal — verify a POS auto-synced dispense by attaching vet + witness --}}
@can('clinic.log_controlled')
<div class="modal fade" id="resolveModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" style="background:#fef2f2;border-bottom:1px solid #fecaca;">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title" style="color:#b91c1c;">
                    <i class="fa fa-user-check"></i> Verify POS dispense
                </h4>
            </div>
            <div class="modal-body">
                <p>
                    Attach the authorised issuing doctor and the in-clinic witness for the auto-synced
                    dispense of <strong id="rv_med">—</strong>.
                </p>
                <div class="form-group">
                    <label>Issuing doctor <span class="text-danger">*</span></label>
                    <select id="rv_doctor" class="form-control">
                        <option value="">— Select —</option>
                        @foreach($doctors as $d)
                            <option value="{{ $d->id }}">{{ $d->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group">
                    <label>Witness <span class="text-danger">*</span></label>
                    <select id="rv_witness" class="form-control">
                        <option value="">— Select —</option>
                        @foreach($witnesses as $u)
                            <option value="{{ $u->id }}">{{ trim($u->first_name.' '.$u->last_name) }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group">
                    <label>Note</label>
                    <input type="text" id="rv_notes" class="form-control" placeholder="optional">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button class="btn btn-warning" id="rv_save"><i class="fa fa-check"></i> Verify</button>
            </div>
        </div>
    </div>
</div>
@endcan

{{-- Log movement modal --}}
@can('clinic.log_controlled')
<div class="modal fade" id="logMoveModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <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-shield-alt"></i> Log Controlled-Drug Movement</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Medicine <span class="text-danger">*</span></label>
                            <select id="lm_med" class="form-control">
                                <option value="">— Select a controlled medicine —</option>
                                @foreach($medicines as $m)
                                    <option value="{{ $m->id }}" data-unit="{{ $m->unit }}">{{ $m->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Reason <span class="text-danger">*</span></label>
                            <select id="lm_reason" class="form-control">
                                @foreach($reasons as $key => $cfg)
                                    <option value="{{ $key }}" data-dir="{{ $cfg['direction'] }}">
                                        {{ $cfg['label'] }} ({{ strtoupper($cfg['direction']) }})
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Quantity <span class="text-danger">*</span></label>
                            <input type="number" id="lm_qty" class="form-control" min="0" step="0.001">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Unit</label>
                            <input type="text" id="lm_unit" class="form-control" placeholder="ml, tab…">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Batch No.</label>
                            <input type="text" id="lm_batch" class="form-control" placeholder="optional">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Expiry</label>
                            <input type="date" id="lm_expiry" class="form-control">
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Issuing doctor</label>
                            <select id="lm_doctor" class="form-control">
                                <option value="">— None —</option>
                                @foreach($doctors as $d)
                                    <option value="{{ $d->id }}">{{ $d->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Patient ID <small class="text-muted">(optional)</small></label>
                            <input type="number" id="lm_pet" class="form-control" placeholder="VC patient id">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label>Notes</label>
                    <textarea id="lm_notes" class="form-control" rows="2"></textarea>
                </div>

                <p class="text-muted" style="font-size:11px;">
                    <i class="fa fa-info-circle"></i>
                    A serial number and running balance will be assigned automatically. Rows cannot be edited or deleted afterwards.
                </p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" id="lm_save"><i class="fa fa-save"></i> Log movement</button>
            </div>
        </div>
    </div>
</div>
@endcan
@endsection

@section('javascript')
<script>
$(function () {

var crTable = $('#cr_table').DataTable({
    processing: true, serverSide: true, order: [],
    pageLength: 25,
    ajax: {
        url: '{{ route('clinic.controlled-register.list') }}',
        data: function (d) {
            d.medicine_id = $('#f_med').val();
            d.schedule    = $('#f_schedule').val();
            d.reason_code = $('#f_reason').val();
            d.date_from   = $('#f_from').val();
            d.date_to     = $('#f_to').val();
        }
    },
    columns: [
        { data: 'serial_no',    name: 'serial_no',
          render: function (d, t, row) { return '<strong>' + d + '</strong><br><small class="text-muted">' + (row.created_at || '') + '</small>'; } },
        { data: 'medicine_col', name: 'medicine.name', orderable: false },
        { data: 'qty_col',      name: 'qty', orderable: false },
        { data: 'balance_col',  name: 'balance_after' },
        { data: 'batch_no',     name: 'batch_no', defaultContent: '—' },
        { data: 'reason_col',   name: 'reason_code', orderable: false },
        { data: 'patient_col',  name: 'patient_id', orderable: false, searchable: false },
        { data: 'signoff_col',  name: 'doctor_id', orderable: false, searchable: false },
        { data: 'notes',        name: 'notes', defaultContent: '—' },
        { data: 'resolve_col',  name: 'resolve', orderable: false, searchable: false, defaultContent: '' }
    ]
});

$('#f_med, #f_schedule, #f_reason').on('change', () => crTable.ajax.reload());
$('#f_from, #f_to').on('change',   () => crTable.ajax.reload());

$('#filter_unverified').on('click', function () {
    $('#f_reason').val('dispense_unverified').trigger('change');
});

// ── Chain-integrity controls ──────────────────────────────
$('#cr_verify_btn').on('click', function () {
    var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
    $.get('{{ route('clinic.controlled-register.verify') }}').done(function (res) {
        var $strip = $('#cr_integrity'), $msg = $('#cr_verify_msg');
        $strip.removeClass('alert-success alert-danger');
        if (res.ok) {
            $strip.addClass('alert-success');
            $msg.html('<i class="fa fa-check-circle"></i> Chain verified — ' + res.seals + ' seal(s) intact.');
        } else {
            $strip.addClass('alert-danger');
            var b = res.first_breach || {};
            $msg.html('<i class="fa fa-skull-crossbones"></i> <strong>INTEGRITY BREACH</strong> on ' + b.date + ' — sealed ' + b.sealed_at + ' but rows no longer match.');
        }
    }).always(function () { $btn.prop('disabled', false).html('<i class="fa fa-check-double"></i> Verify chain'); });
});

$('#cr_seal_btn').on('click', function () {
    var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
    $.post('{{ route('clinic.controlled-register.seal') }}', { _token: '{{ csrf_token() }}' }).done(function (res) {
        if (res.success) {
            toastr.success(res.count ? ('Sealed ' + res.count + ' day(s).') : 'Nothing to seal — already up to date.');
            setTimeout(function () { location.reload(); }, 800);
        }
    }).always(function () { $btn.prop('disabled', false).html('<i class="fa fa-lock"></i> Seal now'); });
});

// Resolve unverified rows
var resolveId = null;
$(document).on('click', '.cr-resolve', function () {
    resolveId = $(this).data('id');
    $('#rv_med').text($(this).data('med') || '—');
    $('#rv_doctor,#rv_witness,#rv_notes').val('');
    $('#resolveModal').modal('show');
});
$('#rv_save').on('click', function () {
    if (!resolveId) return;
    if (!$('#rv_doctor').val() || !$('#rv_witness').val()) { toastr.warning('Pick a doctor AND a witness.'); return; }
    var $btn = $(this).prop('disabled', true);
    $.ajax({
        url: '{{ url('clinic/controlled-register') }}/' + resolveId + '/resolve',
        method: 'POST',
        data: { _token: '{{ csrf_token() }}',
                doctor_id: $('#rv_doctor').val(),
                witness_user_id: $('#rv_witness').val(),
                notes: $('#rv_notes').val() },
        success: function (res) {
            if (res.success) { toastr.success(res.msg); $('#resolveModal').modal('hide'); crTable.ajax.reload(); }
            else toastr.error(res.msg || 'Could not verify.');
        },
        error: function (xhr) {
            toastr.error((xhr.responseJSON && xhr.responseJSON.msg) || 'Could not verify.');
        },
        complete: function () { $btn.prop('disabled', false); }
    });
});

// Auto-fill unit from the picked medicine
$('#lm_med').on('change', function () {
    $('#lm_unit').val($(this).find('option:selected').data('unit') || '');
});

$('#lm_save').on('click', function () {
    var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
    $.ajax({
        url: '{{ route('clinic.controlled-register.store') }}', method: 'POST',
        data: {
            _token:      '{{ csrf_token() }}',
            medicine_id: $('#lm_med').val(),
            reason_code: $('#lm_reason').val(),
            qty:         $('#lm_qty').val(),
            unit:        $('#lm_unit').val(),
            batch_no:    $('#lm_batch').val(),
            expiry_date: $('#lm_expiry').val(),
            doctor_id:   $('#lm_doctor').val(),
            patient_id:      $('#lm_pet').val(),
            notes:       $('#lm_notes').val()
        },
        success: function (res) {
            if (res.success) {
                $('#logMoveModal').modal('hide');
                toastr.success(res.msg);
                crTable.ajax.reload();
                // Reset modal
                $('#lm_qty,#lm_batch,#lm_expiry,#lm_pet,#lm_notes,#lm_unit').val('');
            } else {
                toastr.error(res.msg || 'Could not log movement.');
            }
        },
        error: function (xhr) {
            var m = xhr.responseJSON && xhr.responseJSON.errors
                ? Object.values(xhr.responseJSON.errors)[0][0]
                : (xhr.responseJSON && xhr.responseJSON.msg) || 'Could not log movement.';
            toastr.error(m);
        },
        complete: function () { $btn.prop('disabled', false).html('<i class="fa fa-save"></i> Log movement'); }
    });
});

});
</script>
@endsection
