<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Controlled Drug Register · {{ $business->name ?? 'Veterinary Clinic' }}</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
* { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }

body { font-family: 'Segoe UI', Tahoma, Arial, sans-serif; font-size: 11px; color: #1e293b; background: #fff; }
.page { max-width: 1080px; margin: 0 auto; padding: 18px 22px; page-break-after: always; }
.page:last-child { page-break-after: auto; }

.head {
    display: flex; justify-content: space-between; align-items: flex-end;
    border-bottom: 2px solid #1a3a5c; padding-bottom: 10px; margin-bottom: 12px;
}
.clinic { font-size: 16px; font-weight: 800; color: #1a3a5c; }
.clinic .sub { font-size: 10px; color: #64748b; font-weight: 500; margin-top: 2px; }
.title-tag {
    background: #1a3a5c; color: #fff; padding: 4px 12px; border-radius: 4px;
    font-size: 10px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase;
}

.meta { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0;
    border: 1px solid #cbd5e1; margin-bottom: 10px; }
.meta-cell { padding: 6px 10px; border-right: 1px solid #e2e8f0; }
.meta-cell:last-child { border-right: 0; }
.meta-lbl { font-size: 9px; color: #64748b; font-weight: 700; text-transform: uppercase; letter-spacing: .5px; }
.meta-val { font-size: 12px; font-weight: 700; color: #1e293b; margin-top: 1px; }

table.reg { width: 100%; border-collapse: collapse; margin-bottom: 14px; }
table.reg th, table.reg td { border: 1px solid #94a3b8; padding: 5px 7px; vertical-align: top; font-size: 10px; }
table.reg th { background: #1a3a5c; color: #fff; font-weight: 700; text-align: center; font-size: 10px; }
table.reg td.num { text-align: right; font-variant-numeric: tabular-nums; }
table.reg tr.opening td { background: #f1f5f9; font-style: italic; }
table.reg tr.in    td.dir   { color: #15803d; font-weight: 700; text-align: center; }
table.reg tr.out   td.dir   { color: #b91c1c; font-weight: 700; text-align: center; }
table.reg tr.adjust td.dir  { color: #475569; font-weight: 700; text-align: center; }
table.reg tfoot td { background: #f8fafc; font-weight: 700; }

.empty-row td { text-align: center; color: #94a3b8; font-style: italic; padding: 18px; }

.sign-row {
    display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 26px; margin-top: 22px;
    page-break-inside: avoid;
}
.sign-box { border-top: 1px solid #475569; padding-top: 4px; text-align: center; font-size: 10px; }
.sign-box .role { font-weight: 700; color: #1a3a5c; }
.sign-box .lbl  { color: #64748b; }

.notes-line {
    margin-top: 18px; font-size: 9px; color: #64748b;
    border-top: 1px dashed #cbd5e1; padding-top: 6px; text-align: center;
}

.toolbar { text-align: center; padding: 10px; background: #f1f5f9; }
.toolbar button {
    background: #2563eb; color: #fff; border: none; padding: 8px 22px;
    border-radius: 6px; font-size: 13px; cursor: pointer; font-weight: 600;
}

@media print {
    @page { size: A4 landscape; margin: 10mm; }
    body { padding: 0; }
    .page { padding: 0; }
    .no-print { display: none !important; }
}
</style>
</head>
<body>

<div class="toolbar no-print">
    <button onclick="window.print()">🖨 Print register</button>
</div>

@php
    $dateFmt = session('business.date_format', 'd M Y') ?: 'd M Y';
    $fmtQty  = function ($v) {
        return rtrim(rtrim(number_format((float) $v, 3, '.', ''), '0'), '.');
    };
@endphp

@foreach($medicines as $med)
    @php
        $rows       = $movements->get($med->id, collect());
        $opening    = (float) ($openingBalances[$med->id] ?? 0);
        $totalIn    = $rows->where('direction', 'in')->sum('qty');
        $totalOut   = $rows->where('direction', 'out')->sum('qty');
        $closing    = $rows->isNotEmpty() ? (float) $rows->last()->balance_after : $opening;
        $scheduleCfg = $schedules[$med->controlled_schedule] ?? null;
    @endphp
    <div class="page">

        <div class="head">
            <div class="clinic">
                {{ $business->name ?? 'Veterinary Clinic' }}
                <div class="sub">
                    @if(!empty($business->mobile))📞 {{ $business->mobile }} &nbsp;@endif
                    @if(!empty($business->email))✉ {{ $business->email }} &nbsp;@endif
                    @if(!empty($business->city))📍 {{ $business->city }}@endif
                </div>
            </div>
            <div class="title-tag">Controlled Drug Register · سجل العقاقير المخدرة</div>
        </div>

        <div class="meta">
            <div class="meta-cell">
                <div class="meta-lbl">Medicine</div>
                <div class="meta-val">{{ $med->name }}</div>
            </div>
            <div class="meta-cell">
                <div class="meta-lbl">Schedule</div>
                <div class="meta-val">{{ $scheduleCfg['label'] ?? '—' }}</div>
            </div>
            <div class="meta-cell">
                <div class="meta-lbl">Period</div>
                <div class="meta-val">{{ $from->format($dateFmt) }} → {{ $to->format($dateFmt) }}</div>
            </div>
            <div class="meta-cell">
                <div class="meta-lbl">Unit</div>
                <div class="meta-val">{{ $med->unit ?: '—' }}</div>
            </div>
        </div>

        <table class="reg">
            <thead>
                <tr>
                    <th style="width:18px;">#</th>
                    <th style="width:82px;">Date / Time</th>
                    <th style="width:68px;">Serial</th>
                    <th style="width:48px;">Dir</th>
                    <th style="width:90px;">Reason</th>
                    <th style="width:80px;">Batch</th>
                    <th>Owner / Pet</th>
                    <th>Issuing Vet · Witness</th>
                    <th style="width:54px;">Qty IN</th>
                    <th style="width:54px;">Qty OUT</th>
                    <th style="width:62px;">Balance</th>
                    <th style="width:60px;">Sign</th>
                </tr>
            </thead>
            <tbody>
                <tr class="opening">
                    <td colspan="10" style="text-align:right;">Opening balance carried forward</td>
                    <td class="num">{{ $fmtQty($opening) }}</td>
                    <td>&nbsp;</td>
                </tr>

                @forelse($rows as $i => $r)
                    @php
                        $reasonCfg = $reasons[$r->reason_code] ?? null;
                        $owner = optional($r->owner)->name;
                        $pet   = optional($r->pet)->petname;
                        $doc   = optional($r->doctor)->name;
                        $wit   = trim((optional($r->witness)->first_name ?? '') . ' ' . (optional($r->witness)->last_name ?? ''));
                    @endphp
                    <tr class="{{ $r->direction }}">
                        <td class="num">{{ $i + 1 }}</td>
                        <td>{{ optional($r->created_at)->format($dateFmt . ' H:i') }}</td>
                        <td>{{ $r->serial_no }}</td>
                        <td class="dir">{{ $r->direction === 'in' ? 'IN' : ($r->direction === 'out' ? 'OUT' : 'ADJ') }}</td>
                        <td>{{ $reasonCfg['label'] ?? $r->reason_code }}</td>
                        <td>{{ $r->batch_no ?: '—' }}</td>
                        <td>
                            @if($owner || $pet)
                                <strong>{{ $pet ?: '—' }}</strong>
                                @if($owner)<br><span style="color:#64748b;">{{ $owner }}</span>@endif
                            @else —
                            @endif
                        </td>
                        <td>
                            @if($doc)<strong>{{ $doc }}</strong>@endif
                            @if($wit)<br><span style="color:#64748b;">w: {{ $wit }}</span>@endif
                            @if(!$doc && !$wit) — @endif
                        </td>
                        <td class="num">{{ $r->direction === 'in' ? $fmtQty($r->qty) : '' }}</td>
                        <td class="num">{{ $r->direction === 'out' ? $fmtQty($r->qty) : '' }}</td>
                        <td class="num"><strong>{{ $fmtQty($r->balance_after) }}</strong></td>
                        <td>&nbsp;</td>
                    </tr>
                @empty
                    <tr class="empty-row">
                        <td colspan="12">No movements recorded in this period.</td>
                    </tr>
                @endforelse
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="8" style="text-align:right;">Period totals</td>
                    <td class="num">{{ $fmtQty($totalIn) }}</td>
                    <td class="num">{{ $fmtQty($totalOut) }}</td>
                    <td class="num">{{ $fmtQty($closing) }}</td>
                    <td>&nbsp;</td>
                </tr>
            </tfoot>
        </table>

        <div class="sign-row">
            <div class="sign-box">
                <div class="role">Pharmacist in charge</div>
                <div class="lbl">Signature · date</div>
            </div>
            <div class="sign-box">
                <div class="role">Authorised veterinarian</div>
                <div class="lbl">Signature · date</div>
            </div>
            <div class="sign-box">
                <div class="role">Inspector / auditor</div>
                <div class="lbl">Signature · date</div>
            </div>
        </div>

        <div class="notes-line">
            Generated {{ now()->format($dateFmt . ', H:i') }} ·
            This register is insert-only; any correction appears as an explicit ADJUST row.
        </div>

    </div>
@endforeach

@if($medicines->isEmpty())
    <div class="page">
        <div class="head">
            <div class="clinic">{{ $business->name ?? 'Veterinary Clinic' }}</div>
            <div class="title-tag">Controlled Drug Register</div>
        </div>
        <p style="padding:30px;text-align:center;color:#64748b;">
            No controlled medicines matched the chosen filters.
        </p>
    </div>
@endif

{{-- Item #8 - TPS branding footer --}}
@include('vetClinic::partials._print_branding', ['mode' => 'footer'])

<script>window.addEventListener('load', function () { setTimeout(function () { window.print(); }, 400); });</script>
</body>
</html>
