<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Sign — {{ $consent->title }}</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body {
    font-family: 'Segoe UI', Tahoma, Arial, sans-serif;
    background: #f1f5f9; color: #1e293b; -webkit-tap-highlight-color: transparent;
}
.wrap { max-width: 920px; margin: 0 auto; padding: 14px; }
.header {
    background: linear-gradient(135deg, #1a3a5c 0%, #2563eb 60%, #3b82f6 100%);
    color: #fff; padding: 14px 18px; border-radius: 12px; margin-bottom: 14px;
    display: flex; align-items: center; gap: 12px;
}
.header .icon {
    width: 42px; height: 42px; border-radius: 10px;
    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; flex-shrink: 0;
}
.header h1 { font-size: 17px; font-weight: 800; }
.header .sub { font-size: 11px; opacity: .88; margin-top: 2px; }

.panel { background: #fff; border-radius: 12px; padding: 18px; margin-bottom: 14px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.04); border: 1px solid #e2e8f0; }
.panel h2 { font-size: 13px; font-weight: 800; color: #1a3a5c; text-transform: uppercase;
    letter-spacing: .6px; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid #e2e8f0; }

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

.consent-body {
    max-height: 36vh; overflow-y: auto; padding: 12px 14px;
    background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px;
    font-size: 13px; line-height: 1.55; white-space: pre-wrap;
}
.consent-body.rtl { direction: rtl; text-align: right; }

.lang-tabs { display: flex; gap: 6px; margin-bottom: 8px; }
.lang-tab {
    padding: 6px 14px; border-radius: 20px; font-size: 11px; font-weight: 700;
    cursor: pointer; background: #e2e8f0; color: #64748b; border: none;
}
.lang-tab.active { background: #2563eb; color: #fff; }

.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 {
    width: 100%; padding: 11px 12px; border: 1.5px solid #cbd5e1; border-radius: 8px;
    font-size: 15px; background: #fff; outline: none;
}
.field input:focus { border-color: #2563eb; }

.canvas-wrap {
    position: relative; background: #fff; border: 2px dashed #94a3b8;
    border-radius: 10px; touch-action: none; overflow: hidden;
}
.canvas-wrap canvas { display: block; width: 100%; height: 220px; 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; }

.btn-row { display: flex; gap: 10px; margin-top: 14px; flex-wrap: wrap; }
.btn {
    padding: 12px 22px; border-radius: 8px; font-size: 14px; font-weight: 700;
    border: none; cursor: pointer; transition: all .15s;
}
.btn-primary { background: #2563eb; color: #fff; }
.btn-primary:hover { background: #1d4ed8; }
.btn-primary:disabled { background: #94a3b8; cursor: not-allowed; }
.btn-ghost { background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; }
.btn-ghost:hover { background: #e2e8f0; }

.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; }

.note { font-size: 11px; color: #64748b; margin-top: 6px; line-height: 1.5; }

@if(!empty($existing))
.existing-banner {
    background: #fef3c7; border: 1px solid #fde68a; color: #92400e;
    padding: 10px 14px; border-radius: 8px; margin-bottom: 14px; font-size: 13px;
}
.existing-banner b { color: #78350f; }
@endif
</style>
</head>
<body>
<div class="wrap">

    <div class="header">
        <div class="icon">📝</div>
        <div>
            <h1>{{ $consent->title }}</h1>
            <div class="sub">{{ $business->name ?? 'Veterinary Clinic' }}
                · Issued {{ optional($consent->issued_at)->format('d M Y, H:i') }}</div>
        </div>
    </div>

    @if(!empty($existing))
        <div class="existing-banner">
            ⚠ This consent already has a digital signature captured on
            <b>{{ optional($existing->signed_at)->format('d M Y, H:i') }}</b>
            by <b>{{ $existing->signed_by_name }}</b>.
            Submitting again will <b>supersede</b> it (the old record stays in the audit trail).
        </div>
    @endif

    <div id="flash" class="flash"></div>

    <div class="panel">
        <h2>Patient & Owner</h2>
        <div class="pat-row">
            <div>
                <div class="lbl">Patient</div>
                <div class="val">{{ optional($consent->pet)->petname ?? '—' }}</div>
            </div>
            <div>
                <div class="lbl">Owner</div>
                <div class="val">{{ optional($consent->owner)->name ?? '—' }}</div>
            </div>
            <div>
                <div class="lbl">Appointment</div>
                <div class="val">{{ optional($consent->appointment)->ref_no ?? '—' }}</div>
            </div>
        </div>
    </div>

    <div class="panel">
        <h2>Consent Text</h2>

        @php
            $hasEn = !empty($consent->body_en);
            $hasAr = !empty($consent->body_ar);
        @endphp

        @if($hasEn && $hasAr)
            <div class="lang-tabs">
                <button class="lang-tab active" data-lang="en">English</button>
                <button class="lang-tab" data-lang="ar">العربية</button>
            </div>
        @endif

        @if($hasEn)
            <div id="body-en" class="consent-body">{{ $consent->body_en }}</div>
        @endif
        @if($hasAr)
            <div id="body-ar" class="consent-body rtl" style="{{ $hasEn ? 'display:none' : '' }}">{{ $consent->body_ar }}</div>
        @endif
    </div>

    <div class="panel">
        <h2>Signatory Details</h2>

        <div class="field">
            <label for="signed_by_name">Full name of person signing</label>
            <input type="text" id="signed_by_name" maxlength="191"
                value="{{ $consent->signatory_name }}" autocomplete="off">
        </div>
        <div class="field">
            <label for="signed_by_relation">Relationship to patient</label>
            <input type="text" id="signed_by_relation" maxlength="60"
                value="{{ $consent->signatory_relationship ?: 'Owner' }}" autocomplete="off">
        </div>

        <h2 style="margin-top:18px;">Signature</h2>
        <div class="canvas-wrap" id="canvas-wrap">
            <canvas id="sig-canvas"></canvas>
            <div class="canvas-hint" id="canvas-hint">Sign here with your finger or a stylus</div>
        </div>
        <div class="note">By submitting, you confirm you have read and agree to the consent above.
            A timestamped, hashed copy is kept by the clinic for audit.</div>

        <div class="btn-row">
            <button id="btn-clear" class="btn btn-ghost" type="button">Clear</button>
            <button id="btn-submit" class="btn btn-primary" type="button">Submit signature</button>
        </div>
    </div>

    <div style="text-align:center;font-size:12px;color:#64748b;padding:6px 0 18px;">
        No tablet handy?
        <a href="{{ route('vc.consents.print', $consent->id) }}" target="_blank"
           style="color:#2563eb;font-weight:700;text-decoration:underline;">
           Print to hand-sign on paper →
        </a>
        <div style="margin-top:4px;">After signing, upload the scan back via the appointment's
            <strong>Upload signed</strong> button to lock the consent and stamp the QR code.</div>
    </div>
</div>

<script>
(function () {
    // ---- Language tabs ----
    document.querySelectorAll('.lang-tab').forEach(function (tab) {
        tab.addEventListener('click', function () {
            document.querySelectorAll('.lang-tab').forEach(function (t) { t.classList.remove('active'); });
            tab.classList.add('active');
            var en = document.getElementById('body-en');
            var ar = document.getElementById('body-ar');
            if (en) en.style.display = (tab.dataset.lang === 'en') ? '' : 'none';
            if (ar) ar.style.display = (tab.dataset.lang === 'ar') ? '' : 'none';
        });
    });

    // ---- Canvas signature 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;
    var drawing = false;
    var last   = null;

    function sizeCanvas() {
        var dpr = window.devicePixelRatio || 1;
        var rect = wrap.getBoundingClientRect();
        canvas.width  = Math.floor(rect.width  * dpr);
        canvas.height = Math.floor(220 * dpr);
        canvas.style.height = '220px';
        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, 220);
    }
    sizeCanvas();
    window.addEventListener('resize', function () {
        // Resize preserves blank state only; we ignore mid-signing resizes.
        if (!dirty) sizeCanvas();
    });

    function pos(evt) {
        var rect = canvas.getBoundingClientRect();
        var clientX = (evt.touches && evt.touches[0]) ? evt.touches[0].clientX : evt.clientX;
        var clientY = (evt.touches && evt.touches[0]) ? evt.touches[0].clientY : evt.clientY;
        return { x: clientX - rect.left, y: clientY - rect.top };
    }
    function start(evt) {
        evt.preventDefault();
        drawing = true;
        last = pos(evt);
        hint.classList.add('hidden');
    }
    function move(evt) {
        if (!drawing) return;
        evt.preventDefault();
        var p = pos(evt);
        ctx.beginPath();
        ctx.moveTo(last.x, last.y);
        ctx.lineTo(p.x, p.y);
        ctx.stroke();
        last = p;
        dirty = true;
    }
    function end() { drawing = false; last = null; }

    canvas.addEventListener('mousedown', start);
    canvas.addEventListener('mousemove', move);
    document.addEventListener('mouseup', end);
    canvas.addEventListener('touchstart', start, { passive: false });
    canvas.addEventListener('touchmove',  move,  { passive: false });
    canvas.addEventListener('touchend',   end);
    canvas.addEventListener('touchcancel', end);

    document.getElementById('btn-clear').addEventListener('click', function () {
        sizeCanvas();
        dirty = false;
        hint.classList.remove('hidden');
    });

    // ---- Submit ----
    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-submit').addEventListener('click', function () {
        var name = document.getElementById('signed_by_name').value.trim();
        var rel  = document.getElementById('signed_by_relation').value.trim();
        if (!name) { flash('err', 'Please enter the signatory name.'); return; }
        if (!dirty) { flash('err', 'Please sign in the box above.'); return; }

        var btn = document.getElementById('btn-submit');
        btn.disabled = true; btn.textContent = 'Submitting…';

        var fd = new FormData();
        fd.append('_token', document.querySelector('meta[name="csrf-token"]').getAttribute('content'));
        fd.append('png', canvas.toDataURL('image/png'));
        fd.append('signed_by_name', name);
        fd.append('signed_by_relation', rel);

        fetch('{{ route('vc.consents.store-signature', $consent->id) }}', {
            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, body: j }; }); })
        .then(function (res) {
            if (!res.ok || !res.body.success) {
                flash('err', (res.body && res.body.msg) || 'Could not save signature.');
                btn.disabled = false; btn.textContent = 'Submit signature';
                return;
            }
            flash('ok', 'Signature captured. Hash: ' + res.body.short_hash + ' — opening printable copy…');
            setTimeout(function () { window.location = res.body.print_url; }, 900);
        })
        .catch(function () {
            flash('err', 'Network error. Please try again.');
            btn.disabled = false; btn.textContent = 'Submit signature';
        });
    });
})();
</script>
</body>
</html>
