@extends('layouts.app')
@section('title', $prescription->ref_no . ' — Prescription')

@section('css')
<style>
/* ── Prescription Hero ──────────────────────────────────── */
.rx-hero {
    background: linear-gradient(135deg, #1a3a5c 0%, #2980b9 60%, #3498db 100%);
    border-radius: 16px; padding: 26px 28px 0;
    margin-bottom: 22px; color: #fff; position: relative; overflow: hidden;
    box-shadow: 0 10px 36px rgba(0,0,0,.22);
}
.rx-hero::before {
    content: ''; position: absolute; inset: 0;
    background-image: radial-gradient(circle, rgba(255,255,255,.1) 1px, transparent 1px);
    background-size: 20px 20px; pointer-events: none;
}
.rx-hero-orb { position:absolute; border-radius:50%; pointer-events:none; filter:blur(36px); }
.rx-hero-orb-1 { width:240px;height:240px;top:-70px;right:-50px;background:rgba(255,255,255,.1); }
.rx-hero-orb-2 { width:160px;height:160px;bottom:-50px;left:-30px;background:rgba(255,255,255,.07); }

.rx-hero-content { position:relative;z-index:1;display:flex;align-items:flex-start;gap:18px;margin-bottom:22px; }
.rx-symbol-box {
    width:62px;height:62px;border-radius:14px;flex-shrink:0;
    background:rgba(255,255,255,.15);border:1.5px solid rgba(255,255,255,.3);
    display:flex;align-items:center;justify-content:center;
    font-size:32px;font-weight:900;font-family:serif;color:#fff;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.25),0 6px 16px rgba(0,0,0,.15);
}
.rx-hero-info h2 { margin:0 0 6px;font-size:22px;font-weight:800;letter-spacing:-.3px; }
.rx-hero-meta span {
    display:inline-flex;align-items:center;gap:4px;
    background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.18);
    border-radius:20px;padding:2px 9px;font-size:12px;margin-right:5px;
}
.rx-hero-actions { margin-left:auto;display:flex;gap:7px;flex-wrap:wrap;align-items:flex-start; }
.rx-hero-actions .btn {
    border:1.5px solid rgba(255,255,255,.3);color:#fff;
    background:rgba(255,255,255,.12);font-size:12px;font-weight:600;
    border-radius:8px;transition:all .18s;
}
.rx-hero-actions .btn:hover { background:rgba(255,255,255,.25);border-color:rgba(255,255,255,.55);transform:translateY(-1px); }
.rx-status-bar {
    position:relative;z-index:1;
    display:flex;align-items:center;gap:14px;
    background:rgba(0,0,0,.18);
    padding:13px 28px;margin:0 -28px;
    border-radius:0 0 16px 16px;
}
.rx-status-pill {
    display:flex;align-items:center;gap:6px;
    font-size:12px;font-weight:700;color:#fff;
}
.rx-status-dot { width:8px;height:8px;border-radius:50%; }

/* ── Side Card ──────────────────────────────────────────── */
.rx-side-card { background:#fff;border-radius:10px;box-shadow:0 1px 4px rgba(0,0,0,.08);margin-bottom:14px;overflow:hidden; }
.rx-side-card-hd { padding:10px 16px;background:#f8fafc;border-bottom:1px solid #f0f0f0;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#64748b; }
.rx-side-card-body { padding:14px 16px; }
.rx-info-row { display:flex;flex-direction:column;padding:7px 0;border-bottom:1px solid #f5f5f5; }
.rx-info-row:last-child { border-bottom:none; }
.rx-info-label { font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;color:#94a3b8;margin-bottom:3px; }
.rx-info-val { font-size:13px;color:#1e293b; }

/* ── Patient Mini ───────────────────────────────────────────── */
.rx-pet-mini { display:flex;align-items:center;gap:11px;margin-bottom:14px;padding-bottom:14px;border-bottom:1px solid #f0f0f0; }
.rx-pet-avatar { width:48px;height:48px;border-radius:50%;background:#f0f0f5;display:flex;align-items:center;justify-content:center;font-size:18px;color:#ccc;flex-shrink:0;overflow:hidden; }
.rx-pet-avatar img { width:48px;height:48px;border-radius:50%;object-fit:cover; }
.rx-pet-name { font-weight:700;font-size:15px;color:#2c3e50; }
.rx-pet-sub { font-size:12px;color:#94a3b8;margin-top:1px; }

/* ── Medicine List ──────────────────────────────────────── */
.rx-med-item {
    display:flex;gap:14px;align-items:flex-start;
    padding:14px 0;border-bottom:1px solid #f0f4f8;
}
.rx-med-item:last-child { border-bottom:none; }
.rx-med-num {
    width:30px;height:30px;border-radius:50%;flex-shrink:0;
    background:linear-gradient(135deg,#2980b9,#3498db);
    color:#fff;font-weight:800;font-size:13px;
    display:flex;align-items:center;justify-content:center;
}
.rx-med-name { font-weight:700;font-size:14px;color:#1e293b;margin-bottom:5px; }
.rx-med-detail { display:flex;flex-wrap:wrap;gap:6px;margin-bottom:4px; }
.rx-med-pill {
    display:inline-flex;align-items:center;gap:4px;
    background:#f1f5f9;border:1px solid #e2e8f0;
    border-radius:12px;padding:2px 10px;font-size:11.5px;color:#475569;font-weight:600;
}
.rx-med-pill i { font-size:9px;color:#94a3b8; }
.rx-med-note { font-size:11.5px;color:#64748b;font-style:italic;margin-top:3px; }
.rx-med-note i { color:#f39c12;margin-right:3px; }
.rx-empty { text-align:center;padding:32px;color:#94a3b8; }

/* ── Diagnosis / Notes box ──────────────────────────────── */
.rx-text-box { background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px 14px;font-size:13px;color:#334155;white-space:pre-wrap; }
</style>
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
@php
$statusColors = ['active'=>'#27ae60','completed'=>'#3498db','cancelled'=>'#e74c3c'];
$statusIcons  = ['active'=>'fa-check-circle','completed'=>'fa-flag-checkered','cancelled'=>'fa-times-circle'];
$sc = $statusColors[$prescription->status] ?? '#95a5a6';
$si = $statusIcons[$prescription->status] ?? 'fa-circle';
@endphp

<section class="content-header" style="display:none"></section>
<section class="content">

{{-- Hero --}}
<div class="rx-hero">
    <div class="rx-hero-orb rx-hero-orb-1"></div>
    <div class="rx-hero-orb rx-hero-orb-2"></div>

    <div class="rx-hero-content">
        <div class="rx-symbol-box">℞</div>
        <div class="rx-hero-info">
            <div style="background:rgba(255,255,255,.18);border:1px solid rgba(255,255,255,.28);border-radius:20px;padding:2px 10px;font-size:11px;font-weight:700;letter-spacing:.5px;display:inline-block;margin-bottom:6px;">
                {{ $prescription->ref_no }}
            </div>
            <h2>Prescription</h2>
            <div class="rx-hero-meta" style="color:rgba(255,255,255,.88);">
                <span><i class="fa fa-notes-medical"></i> {{ optional($prescription->pet)->patient_name ?? '—' }}</span>
                <span><i class="fa fa-user"></i> {{ optional($prescription->owner)->name ?? '—' }}</span>
                @if(optional($prescription->doctor)->name)
                <span><i class="fa fa-user-md"></i> {{ $prescription->doctor->name }}</span>
                @endif
                <span><i class="fa fa-calendar"></i> {{ optional($prescription->prescribed_date)->format('d M Y') }}</span>
            </div>
        </div>
        <div class="rx-hero-actions">
            @can('clinic.manage_prescriptions')
            <a href="{{ route('clinic.prescriptions.edit', $prescription->id) }}" class="btn btn-sm">
                <i class="fa fa-edit"></i> Edit
            </a>
            @endcan
            <a href="{{ route('clinic.prescriptions.print', $prescription->id) }}" target="_blank" class="btn btn-sm">
                <i class="fa fa-print"></i> Print
            </a>
            <a href="{{ route('clinic.prescriptions.index') }}" class="btn btn-sm">
                <i class="fa fa-list"></i> All Rx
            </a>
        </div>
    </div>

    <div class="rx-status-bar">
        <div class="rx-status-pill">
            <span class="rx-status-dot" style="background:{{ $sc }};box-shadow:0 0 0 3px {{ $sc }}44;"></span>
            <i class="fa {{ $si }}"></i>
            {{ ucfirst($prescription->status) }}
        </div>
        @if($prescription->valid_until)
        <div style="font-size:12px;color:rgba(255,255,255,.7);margin-left:10px;">
            <i class="fa fa-calendar-check"></i>
            Valid until {{ optional($prescription->valid_until)->format('d M Y') }}
        </div>
        @endif
        @if($prescription->appointment_id)
        <a href="{{ route('clinic.appointments.show', $prescription->appointment_id) }}"
           class="btn btn-xs" style="margin-left:auto;background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.3);color:#fff;">
            <i class="fa fa-calendar"></i> View Appointment
        </a>
        @endif
    </div>
</div>

<div class="row">

    {{-- Left sidebar --}}
    <div class="col-md-4">

        {{-- Patient --}}
        <div class="rx-side-card">
            <div class="rx-side-card-hd"><i class="fas fa-notes-medical fa-fw"></i> Patient</div>
            <div class="rx-side-card-body">
                <div class="rx-pet-mini">
                    <div class="rx-pet-avatar">
                        @if(optional($prescription->pet)->photo_url)
                            <img src="{{ $prescription->pet->photo_url }}" alt="">
                        @else
                            <i class="fas fa-notes-medical"></i>
                        @endif
                    </div>
                    <div>
                        <a href="{{ route('clinic.patients.show', $prescription->patient_id) }}" style="font-weight:700;font-size:15px;color:#2c3e50;text-decoration:none;">
                            {{ optional($prescription->pet)->patient_name ?? '—' }}
                        </a>
                        @if(config('cliniccore.show_animal_fields', false))
                        <div class="rx-pet-sub">
                            {{ optional($prescription->pet)->species }}
                            {{ optional($prescription->pet)->breed ? '· '.optional($prescription->pet)->breed : '' }}
                        </div>
                        @endif
                    </div>
                </div>

                <div class="rx-info-row">
                    <span class="rx-info-label"><i class="fa fa-user fa-fw"></i> Contact</span>
                    <span class="rx-info-val">{{ optional($prescription->owner)->name ?? '—' }}</span>
                    @if(optional($prescription->owner)->mobile)
                    <span style="font-size:12px;color:#94a3b8;">{{ $prescription->owner->mobile }}</span>
                    @endif
                </div>

                @if(optional($prescription->doctor)->name)
                <div class="rx-info-row">
                    <span class="rx-info-label"><i class="fa fa-user-md fa-fw"></i> Doctor</span>
                    <span class="rx-info-val">{{ $prescription->doctor->name }}</span>
                    @if($prescription->doctor->specialization)
                    <span style="font-size:12px;color:#94a3b8;">{{ $prescription->doctor->specialization }}</span>
                    @endif
                </div>
                @endif

                <div class="rx-info-row">
                    <span class="rx-info-label"><i class="fa fa-calendar fa-fw"></i> Prescribed Date</span>
                    <span class="rx-info-val">{{ optional($prescription->prescribed_date)->format('d M Y') ?? '—' }}</span>
                </div>

                @if($prescription->valid_until)
                <div class="rx-info-row">
                    <span class="rx-info-label"><i class="fa fa-calendar-check fa-fw"></i> Valid Until</span>
                    <span class="rx-info-val">{{ optional($prescription->valid_until)->format('d M Y') }}</span>
                </div>
                @endif
            </div>
        </div>

        {{-- Diagnosis --}}
        @if($prescription->diagnosis)
        <div class="rx-side-card">
            <div class="rx-side-card-hd"><i class="fa fa-stethoscope fa-fw"></i> Diagnosis</div>
            <div class="rx-side-card-body">
                <div class="rx-text-box">{{ $prescription->diagnosis }}</div>
            </div>
        </div>
        @endif

        {{-- Notes --}}
        @if($prescription->notes)
        <div class="rx-side-card">
            <div class="rx-side-card-hd"><i class="fa fa-sticky-note fa-fw"></i> Notes</div>
            <div class="rx-side-card-body">
                <div class="rx-text-box">{{ $prescription->notes }}</div>
            </div>
        </div>
        @endif

    </div>

    {{-- Medicines --}}
    <div class="col-md-8">
        <div class="rx-side-card">
            <div class="rx-side-card-hd" style="display:flex;align-items:center;justify-content:space-between;">
                <span><i class="fa fa-pills fa-fw"></i> Medicines Prescribed</span>
                <span class="label label-info" style="font-size:10px;">{{ $prescription->items->count() }} item(s)</span>
            </div>
            <div class="rx-side-card-body" style="padding:8px 16px;">
                @forelse($prescription->items as $i => $item)
                <div class="rx-med-item">
                    <div class="rx-med-num">{{ $i + 1 }}</div>
                    <div style="flex:1;min-width:0;">
                        <div class="rx-med-name">{{ $item->medicine_name }}</div>
                        <div class="rx-med-detail">
                            @if($item->dosage)
                            <span class="rx-med-pill"><i class="fa fa-flask"></i> {{ $item->dosage }}</span>
                            @endif
                            @if($item->frequency)
                            <span class="rx-med-pill"><i class="fa fa-clock"></i> {{ $item->frequency }}</span>
                            @endif
                            @if($item->duration_days)
                            <span class="rx-med-pill"><i class="fa fa-calendar"></i> {{ $item->duration_days }} days</span>
                            @endif
                            @if($item->quantity && $item->quantity > 1)
                            <span class="rx-med-pill"><i class="fa fa-hashtag"></i> Qty: {{ $item->quantity }}</span>
                            @endif
                            @if(!empty($item->prn))
                            <span class="rx-med-pill"><i class="fa fa-clock"></i> PRN{{ $item->prn_reason ? ' — '.$item->prn_reason : '' }}</span>
                            @endif
                            @if(($item->refills_allowed ?? 0) > 0)
                            <span class="rx-med-pill"><i class="fa fa-repeat"></i> {{ __('clinicCore::lang.refills') }}: <span class="rx-refills-count" data-item="{{ $item->id }}">{{ (int)($item->refills_used ?? 0) }}</span>/{{ (int)$item->refills_allowed }}</span>
                            @endif
                            @if(isset($item->substitutions_allowed) && !$item->substitutions_allowed)
                            <span class="rx-med-pill"><i class="fa fa-ban"></i> No substitution</span>
                            @endif
                        </div>
                        @if($item->instructions)
                        <div class="rx-med-note"><i class="fa fa-info-circle"></i> {{ $item->instructions }}</div>
                        @endif

                        @can('clinic.rx.refill')
                        @if(($item->refills_allowed ?? 0) > 0)
                        <div style="margin-top:6px;">
                            <button class="btn btn-xs btn-default rx-refill-btn"
                                    data-id="{{ $item->id }}"
                                    {{ (int)($item->refills_used ?? 0) >= (int)$item->refills_allowed ? 'disabled' : '' }}>
                                <i class="fa fa-repeat"></i> {{ __('clinicCore::lang.refill') }}
                                (<span class="rx-refills-left" data-item="{{ $item->id }}">{{ (int)$item->refills_allowed - (int)($item->refills_used ?? 0) }}</span> {{ __('clinicCore::lang.refills_left') }})
                            </button>
                        </div>
                        @endif
                        @endcan

                        @if(\Schema::hasColumn('clc_prescription_items', 'dispensed_at'))
                        <div style="margin-top:6px;font-size:11px;">
                            @if($item->dispensed_at)
                                <span class="label label-success" style="font-size:10px;">
                                    <i class="fa fa-check"></i> Dispensed
                                    {{ \Carbon\Carbon::parse($item->dispensed_at)->format('d M Y H:i') }}
                                    @if($item->dispensed_qty) · {{ $item->dispensed_qty }} @endif
                                </span>
                            @else
                                @if(auth()->user()->can('clinic.rx.dispense') || auth()->user()->can('clinic.manage_prescriptions'))
                                <button class="btn btn-xs btn-warning rx-dispense-btn"
                                        data-id="{{ $item->id }}" data-name="{{ $item->medicine_name }}">
                                    <i class="fa fa-pills"></i> {{ __('clinicCore::lang.dispense') }}
                                </button>
                                @endif
                            @endif
                        </div>
                        @endif
                    </div>
                </div>
                @empty
                <div class="rx-empty">
                    <i class="fa fa-pills fa-2x" style="color:#e2e8f0;margin-bottom:8px;display:block;"></i>
                    No medicines added.
                </div>
                @endforelse
            </div>
        </div>
    </div>

</div>
</section>

@if(\Schema::hasColumn('clc_prescription_items', 'dispensed_at'))
{{-- ── Dispense modal — FEFO batch picker over ERP purchase_lines ─────── --}}
<div id="rxDispenseModal" 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> Dispense <span id="rxd_name"></span></h4>
            </div>
            <div class="modal-body">
                <div id="rxd_loading" style="text-align:center;padding:18px;color:#94a3b8;">
                    <i class="fa fa-spinner fa-spin"></i> Loading available batches…
                </div>
                <div id="rxd_no_link" class="alert alert-warning" style="display:none;"></div>
                <div id="rxd_controlled" class="alert alert-danger" style="display:none;">
                    <i class="fa fa-lock"></i> <strong id="rxd_sched"></strong> — {{ __('clinicCore::lang.dispense_witness_required') }}
                </div>
                <div id="rxd_form" style="display:none;">
                    <div class="form-group">
                        <label>{{ __('clinicCore::lang.dispense_batch_guidance') }} <small class="text-muted">(FEFO)</small></label>
                        <select id="rxd_batch" class="form-control"></select>
                        <small class="text-muted">{{ __('clinicCore::lang.dispense_batch_display_only') }}</small>
                    </div>
                    <div class="form-group" id="rxd_witness_group" style="display:none;">
                        <label>{{ __('clinicCore::lang.dispense_witness') }}</label>
                        <select id="rxd_witness" class="form-control"></select>
                    </div>
                    <div class="form-group">
                        <label>{{ __('clinicCore::lang.dispense_qty') }} <span id="rxd_unit_lbl" class="text-muted"></span></label>
                        <input type="number" step="0.0001" min="0.0001" id="rxd_qty" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Location</label>
                        <select id="rxd_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 class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button class="btn btn-success" id="rxd_save"><i class="fa fa-check"></i> {{ __('clinicCore::lang.dispense') }}</button>
            </div>
        </div>
    </div>
</div>

<script>
$(function () {
    var TOKEN = $('meta[name="csrf-token"]').attr('content');
    var OPT_BASE   = '{{ url('/clinic/prescriptions/items') }}';
    var currentItemId = null;

    var isControlled = false;

    $(document).on('click', '.rx-dispense-btn', function () {
        currentItemId = $(this).data('id');
        $('#rxd_name').text($(this).data('name'));
        $('#rxd_loading').show();
        $('#rxd_form').hide();
        $('#rxd_no_link').hide();
        $('#rxd_controlled').hide();
        $('#rxd_witness_group').hide();
        $('#rxd_batch').empty();
        $('#rxd_witness').empty();
        isControlled = false;
        $('#rxDispenseModal').modal('show');

        $.get(OPT_BASE + '/' + currentItemId + '/dispense-options').done(function (res) {
            $('#rxd_loading').hide();
            if (res.msg && !res.linked && !res.controlled) {
                $('#rxd_no_link').text(res.msg).show();
                return;
            }
            isControlled = !!res.controlled;
            $('#rxd_unit_lbl').text(res.unit ? '(' + res.unit + ')' : '');

            if (isControlled) {
                $('#rxd_sched').text(res.schedule_label || 'Controlled');
                $('#rxd_controlled').show();
                (res.witnesses || []).forEach(function (w) {
                    $('#rxd_witness').append('<option value="' + w.id + '">' + w.name + '</option>');
                });
                $('#rxd_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';
                    $('#rxd_batch').append('<option value="' + b.purchase_line_id + '" data-qty="' + b.qty_available + '">' + lbl + '</option>');
                });
            } else {
                $('#rxd_batch').append('<option value="">{{ __('clinicCore::lang.dispense_no_batch') }}</option>');
            }
            $('#rxd_qty').val(1);
            $('#rxd_form').show();
        });
    });

    function doDispense($btn, confirmed) {
        $.post(OPT_BASE + '/' + currentItemId + '/dispense', {
            _token: TOKEN,
            purchase_line_id: $('#rxd_batch').val() || '',
            qty: $('#rxd_qty').val(),
            location_id: $('#rxd_location').val(),
            witness_user_id: isControlled ? $('#rxd_witness').val() : '',
            safety_confirmed: confirmed ? 1 : 0,
        }).done(function (res) {
            if (res.success) { toastr.success(res.msg); setTimeout(function () { window.location.reload(); }, 700); }
        }).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' + '{{ __('clinicCore::lang.dispense_safety_confirm') }}')) {
                    doDispense($btn, true);
                    return;
                }
            } else {
                toastr.error(j.msg || 'Could not dispense.');
            }
        }).always(function () {
            $btn.prop('disabled', false).html('<i class="fa fa-check"></i> {{ __('clinicCore::lang.dispense') }}');
        });
    }

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

{{-- SIFA P3-T5 — refill dispensing (independent of the ERP stock dispense above) --}}
@can('clinic.rx.refill')
<script>
$(function () {
    var RX_TOKEN = $('meta[name="csrf-token"]').attr('content') || '{{ csrf_token() }}';
    var RX_BASE  = '{{ url('/clinic/prescriptions/items') }}';
    $(document).on('click', '.rx-refill-btn', function () {
        var $btn = $(this);
        var itemId = $btn.data('id');
        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
        $.post(RX_BASE + '/' + itemId + '/refill', { _token: RX_TOKEN })
            .done(function (res) {
                if (res.success) {
                    if (window.toastr) toastr.success(res.msg);
                    $('.rx-refills-count[data-item="' + itemId + '"]').text(res.refills_used);
                    $('.rx-refills-left[data-item="' + itemId + '"]').text(res.refills_left);
                    $btn.html('<i class="fa fa-repeat"></i> {{ __('clinicCore::lang.refill') }} (' + res.refills_left + ' {{ __('clinicCore::lang.refills_left') }})');
                    $btn.prop('disabled', res.refills_left <= 0);
                }
            })
            .fail(function (xhr) {
                var m = (xhr.responseJSON && xhr.responseJSON.msg) || 'Could not record refill.';
                if (window.toastr) toastr.error(m); else alert(m);
                $btn.prop('disabled', false).html('<i class="fa fa-repeat"></i> {{ __('clinicCore::lang.refill') }}');
            });
    });
});
</script>
@endcan

@endsection
