<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>Quotation {{ $transaction->invoice_no ?? '' }} — {{ $business->name ?? 'Clinic' }}</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Segoe UI', Tahoma, Arial, sans-serif; background: #f1f5f9;
       color: #1e293b; min-height: 100vh; padding: 14px; }
.wrap { max-width: 760px; margin: 0 auto; }

.header {
    background: linear-gradient(135deg, #1a3a5c 0%, #2563eb 60%, #3b82f6 100%);
    color: #fff; padding: 16px 22px; border-radius: 12px 12px 0 0;
    display: flex; align-items: center; gap: 14px;
}
.header .icon {
    width: 46px; height: 46px; border-radius: 11px;
    background: rgba(255,255,255,.18); border: 1.5px solid rgba(255,255,255,.32);
    display: flex; align-items: center; justify-content: center; font-size: 22px;
}
.header h1 { font-size: 17px; font-weight: 800; }
.header .sub { font-size: 11px; opacity: .88; margin-top: 2px; }

.card { background: #fff; padding: 18px 22px; border-bottom: 1px solid #e2e8f0; }
.card:last-of-type { border-radius: 0 0 12px 12px; border-bottom: 0; }
.card h2 { font-size: 12px; font-weight: 800; color: #1a3a5c; text-transform: uppercase;
           letter-spacing: .6px; margin-bottom: 10px; padding-bottom: 6px;
           border-bottom: 1px solid #e2e8f0; }

.grid3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; font-size: 12px; }
.lbl { color: #64748b; font-size: 10px; font-weight: 700; text-transform: uppercase;
       letter-spacing: .5px; margin-bottom: 2px; }
.val { color: #1e293b; font-weight: 700; }

table.lines { width: 100%; border-collapse: collapse; font-size: 12px; }
table.lines th, table.lines td { padding: 8px 6px; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
table.lines th { background: #f8fafc; font-size: 10px; font-weight: 700; color: #64748b;
                 text-transform: uppercase; letter-spacing: .5px; text-align: left; }
table.lines td.num { text-align: right; font-variant-numeric: tabular-nums; }
table.lines tr.total td { font-weight: 800; font-size: 14px; padding-top: 12px; }

.status-badge {
    display: inline-block; padding: 3px 12px; border-radius: 20px;
    font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .5px;
}
.s-sent     { background: #dbeafe; color: #1e40af; }
.s-viewed   { background: #e0e7ff; color: #3730a3; }
.s-approved { background: #ecfdf5; color: #065f46; }
.s-rejected { background: #fef2f2; color: #991b1b; }
.s-expired  { background: #fef3c7; color: #92400e; }

.canvas-wrap { background: #fff; border: 2px dashed #94a3b8; border-radius: 10px;
               touch-action: none; overflow: hidden; position: relative; }
.canvas-wrap canvas { display: block; width: 100%; height: 200px; cursor: crosshair; }
.canvas-hint { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
               color: #cbd5e1; font-size: 14px; pointer-events: none; user-select: none; }
.canvas-hint.hidden { display: none; }

.field { margin-bottom: 12px; }
.field label { display: block; font-size: 11px; font-weight: 700; color: #475569;
               text-transform: uppercase; letter-spacing: .5px; margin-bottom: 5px; }
.field input, .field textarea {
    width: 100%; padding: 11px 12px; border: 1.5px solid #cbd5e1; border-radius: 8px;
    font-size: 15px; background: #fff; outline: none; font-family: inherit;
}
.field input:focus, .field textarea:focus { border-color: #2563eb; }

.btn-row { display: flex; gap: 10px; margin-top: 12px; flex-wrap: wrap; }
.btn {
    padding: 12px 22px; border-radius: 8px; font-size: 14px; font-weight: 700;
    border: none; cursor: pointer; transition: filter .15s; flex: 1; min-width: 140px;
}
.btn-approve { background: #16a34a; color: #fff; }
.btn-approve:disabled { background: #94a3b8; cursor: not-allowed; }
.btn-reject  { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
.btn-clear   { background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; flex: 0; min-width: 90px; }

.flash { padding: 10px 14px; border-radius: 8px; font-size: 13px; margin-bottom: 12px; display: none; }
.flash.ok  { background: #ecfdf5; color: #065f46; border: 1px solid #a7f3d0; }
.flash.err { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }

.done-card {
    background: #ecfdf5; border: 2px solid #a7f3d0; border-radius: 12px;
    padding: 26px; text-align: center; margin-bottom: 12px;
}
.done-card .big { font-size: 40px; margin-bottom: 6px; }
.done-card h2 { font-size: 18px; color: #065f46; margin-bottom: 4px; }
.done-card .meta { color: #475569; font-size: 12px; }
</style>
</head>
<body>
<div class="wrap">

    <div class="header">
        <div class="icon">📄</div>
        <div>
            <h1>Quotation {{ $transaction->invoice_no }}</h1>
            <div class="sub">{{ $business->name ?? 'Clinic' }}
                @if($meta->expires_at) · Valid until {{ $meta->expires_at->format('d M Y') }} @endif
            </div>
        </div>
    </div>

    @if(in_array($meta->status, ['approved','rejected','expired']))
        <div class="card">
            <div class="done-card">
                @if($meta->status === 'approved')
                    <div class="big">✓</div>
                    <h2>Quotation approved</h2>
                    <div class="meta">
                        By <strong>{{ $meta->approved_by_name }}</strong>
                        · {{ optional($meta->approved_at)->format('d M Y, H:i') }}
                    </div>
                @elseif($meta->status === 'rejected')
                    <div class="big" style="color:#b91c1c;">✕</div>
                    <h2 style="color:#991b1b;">Quotation rejected</h2>
                    <div class="meta">
                        {{ optional($meta->rejected_at)->format('d M Y, H:i') }}
                        @if($meta->rejection_reason)<br><em>"{{ $meta->rejection_reason }}"</em>@endif
                    </div>
                @else
                    <div class="big" style="color:#b45309;">⏰</div>
                    <h2 style="color:#92400e;">Quotation expired</h2>
                    <div class="meta">Please contact the clinic for a new quote.</div>
                @endif
            </div>
        </div>
    @endif

    <div class="card">
        <h2>Patient & Contact</h2>
        <div class="grid3">
            <div>
                <div class="lbl">Patient</div>
                <div class="val">{{ optional($patient)->patient_name ?? '—' }}</div>
            </div>
            <div>
                <div class="lbl">Contact</div>
                <div class="val">{{ optional($transaction->contact)->name ?? '—' }}</div>
            </div>
            <div>
                <div class="lbl">Quotation date</div>
                <div class="val">{{ \Carbon\Carbon::parse($transaction->transaction_date)->format('d M Y') }}</div>
            </div>
        </div>
    </div>

    <div class="card">
        <h2>Items</h2>
        <table class="lines">
            <thead>
                <tr>
                    <th>Description</th>
                    <th class="num" style="width:60px;">Qty</th>
                    <th class="num" style="width:90px;">Unit price</th>
                    <th class="num" style="width:90px;">Line total</th>
                </tr>
            </thead>
            <tbody>
                @foreach($transaction->sell_lines as $line)
                    @php
                        $qty   = (float) $line->quantity;
                        $price = (float) $line->unit_price_inc_tax;
                        $disc  = (float) ($line->line_discount_amount ?? 0);
                        $tax   = (float) ($line->item_tax ?? 0);
                        $lineTotal = ($price * $qty) - $disc + $tax;
                    @endphp
                    <tr>
                        <td>{{ $line->item_description ?: (optional($line->product)->name ?? 'Item') }}</td>
                        <td class="num">{{ rtrim(rtrim(number_format($qty, 2, '.', ''), '0'), '.') }}</td>
                        <td class="num">{{ number_format($price, 2) }}</td>
                        <td class="num">{{ number_format($lineTotal, 2) }}</td>
                    </tr>
                @endforeach
                <tr class="total">
                    <td colspan="3" class="num">Total</td>
                    <td class="num">{{ number_format((float) $transaction->final_total, 2) }}</td>
                </tr>
            </tbody>
        </table>
    </div>

    @if(in_array($meta->status, ['sent', 'viewed']))
    <div class="card">
        <h2>Approve or reject</h2>
        <div id="flash" class="flash"></div>

        <div id="approve-pane">
            <div class="field">
                <label for="approved_by_name">Your full name *</label>
                <input type="text" id="approved_by_name" maxlength="191"
                       value="{{ optional($transaction->contact)->name ?: '' }}" autocomplete="off">
            </div>
            <label class="lbl" style="display:block;margin-bottom:6px;">Sign below to approve</label>
            <div class="canvas-wrap" id="canvas-wrap">
                <canvas id="sig-canvas"></canvas>
                <div class="canvas-hint" id="canvas-hint">Sign with finger or stylus</div>
            </div>
            <div class="btn-row">
                <button id="btn-clear" class="btn btn-clear" type="button">Clear</button>
                <button id="btn-reject" class="btn btn-reject" type="button">Reject</button>
                <button id="btn-approve" class="btn btn-approve" type="button">Approve quotation</button>
            </div>
        </div>

        <div id="reject-pane" style="display:none;">
            <div class="field">
                <label for="reject-reason">Reason for rejecting (optional)</label>
                <textarea id="reject-reason" rows="3" maxlength="500"
                          placeholder="Help the clinic understand..."></textarea>
            </div>
            <div class="btn-row">
                <button id="btn-cancel-reject" class="btn btn-clear" type="button" style="flex:1;">Cancel</button>
                <button id="btn-confirm-reject" class="btn btn-reject" type="button">Confirm rejection</button>
            </div>
        </div>
    </div>
    @endif

</div>

@if(in_array($meta->status, ['sent', 'viewed']))
<script>
(function () {
    var APPROVE_URL = '{{ route('clinic.quotations.public.approve', $meta->approval_token) }}';
    var REJECT_URL  = '{{ route('clinic.quotations.public.reject', $meta->approval_token) }}';
    var CSRF        = '{{ csrf_token() }}';

    // Canvas pad
    var canvas = document.getElementById('sig-canvas');
    var wrap   = document.getElementById('canvas-wrap');
    var hint   = document.getElementById('canvas-hint');
    var ctx    = canvas.getContext('2d');
    var dirty  = false, drawing = false, last = null;

    function size() {
        var dpr = window.devicePixelRatio || 1;
        var rect = wrap.getBoundingClientRect();
        canvas.width  = Math.floor(rect.width  * dpr);
        canvas.height = Math.floor(200 * dpr);
        canvas.style.height = '200px';
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.lineWidth = 2.4;
        ctx.strokeStyle = '#0f172a';
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, rect.width, 200);
    }
    size();
    window.addEventListener('resize', function () { if (!dirty) size(); });

    function pos(e) {
        var r = canvas.getBoundingClientRect();
        var x = (e.touches && e.touches[0]) ? e.touches[0].clientX : e.clientX;
        var y = (e.touches && e.touches[0]) ? e.touches[0].clientY : e.clientY;
        return { x: x - r.left, y: y - r.top };
    }
    canvas.addEventListener('mousedown', function (e) { e.preventDefault(); drawing = true; last = pos(e); hint.classList.add('hidden'); });
    canvas.addEventListener('touchstart', function (e) { e.preventDefault(); drawing = true; last = pos(e); hint.classList.add('hidden'); }, { passive: false });
    function move(e) {
        if (!drawing) return; e.preventDefault();
        var p = pos(e); ctx.beginPath(); ctx.moveTo(last.x, last.y); ctx.lineTo(p.x, p.y); ctx.stroke();
        last = p; dirty = true;
    }
    canvas.addEventListener('mousemove', move);
    canvas.addEventListener('touchmove',  move, { passive: false });
    function end() { drawing = false; last = null; }
    document.addEventListener('mouseup', end);
    canvas.addEventListener('touchend', end);
    canvas.addEventListener('touchcancel', end);

    document.getElementById('btn-clear').onclick = function () { size(); dirty = false; hint.classList.remove('hidden'); };

    function flash(kind, msg) {
        var f = document.getElementById('flash');
        f.className = 'flash ' + kind; f.textContent = msg; f.style.display = 'block';
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    document.getElementById('btn-approve').onclick = function () {
        var name = document.getElementById('approved_by_name').value.trim();
        if (!name) { flash('err', 'Please enter your full name.'); return; }
        if (!dirty) { flash('err', 'Please sign in the box above.'); return; }

        var btn = this; btn.disabled = true; btn.textContent = 'Submitting…';
        var fd = new FormData();
        fd.append('_token', CSRF);
        fd.append('png', canvas.toDataURL('image/png'));
        fd.append('approved_by_name', name);

        fetch(APPROVE_URL, { method: 'POST', body: fd, credentials: 'same-origin',
            headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } })
        .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, b: j }; }); })
        .then(function (res) {
            if (res.ok && res.b.success) { window.location.reload(); }
            else { flash('err', (res.b && res.b.msg) || 'Could not save approval.'); btn.disabled = false; btn.textContent = 'Approve quotation'; }
        })
        .catch(function () { flash('err', 'Network error.'); btn.disabled = false; btn.textContent = 'Approve quotation'; });
    };

    document.getElementById('btn-reject').onclick = function () {
        document.getElementById('approve-pane').style.display = 'none';
        document.getElementById('reject-pane').style.display = '';
    };
    document.getElementById('btn-cancel-reject').onclick = function () {
        document.getElementById('reject-pane').style.display = 'none';
        document.getElementById('approve-pane').style.display = '';
    };
    document.getElementById('btn-confirm-reject').onclick = function () {
        var reason = document.getElementById('reject-reason').value.trim();
        var btn = this; btn.disabled = true; btn.textContent = 'Submitting…';
        var fd = new FormData();
        fd.append('_token', CSRF); fd.append('reason', reason);

        fetch(REJECT_URL, { method: 'POST', body: fd, credentials: 'same-origin',
            headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } })
        .then(function (r) { return r.json().then(function (j) { return { ok: r.ok, b: j }; }); })
        .then(function (res) {
            if (res.ok && res.b.success) { window.location.reload(); }
            else { flash('err', (res.b && res.b.msg) || 'Could not save rejection.'); btn.disabled = false; btn.textContent = 'Confirm rejection'; }
        })
        .catch(function () { flash('err', 'Network error.'); btn.disabled = false; btn.textContent = 'Confirm rejection'; });
    };
})();
</script>
@endif

</body>
</html>
