@extends('layouts.app')

@section('title', 'PWA Engagement')

@section('css')
<style>
    .vc-kpi-row  { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:12px; margin-bottom:18px; }
    .vc-kpi      { background:#fff; border-radius:12px; padding:16px 18px; box-shadow:0 1px 6px rgba(0,0,0,.06); border:1px solid #e8ecf1; }
    .vc-kpi .lbl { font-size:11px; text-transform:uppercase; letter-spacing:.5px; color:#64748b; font-weight:700; }
    .vc-kpi .num { font-size:28px; font-weight:800; color:#1e293b; margin-top:4px; line-height:1; }
    .vc-kpi .sub { font-size:11px; color:#94a3b8; margin-top:4px; }
    .vc-card     { background:#fff; border-radius:12px; box-shadow:0 1px 6px rgba(0,0,0,.06); border:1px solid #e8ecf1; padding:18px; margin-bottom:18px; }
    .vc-card-title { font-size:13px; font-weight:700; text-transform:uppercase; letter-spacing:.4px; color:#64748b; margin-bottom:14px; }
    table.vc-table { width:100%; border-collapse:collapse; font-size:13px; }
    table.vc-table th, table.vc-table td { text-align:left; padding:10px 12px; border-bottom:1px solid #f1f5f9; }
    table.vc-table th { font-size:11px; text-transform:uppercase; letter-spacing:.5px; color:#64748b; font-weight:700; background:#f8fafc; }
    .pill   { display:inline-block; padding:3px 9px; border-radius:12px; font-size:11px; font-weight:700; }
    .pill-ok    { background:#ecfdf5; color:#047857; border:1px solid #a7f3d0; }
    .pill-warn  { background:#fff7ed; color:#9a3412; border:1px solid #fed7aa; }
    .pill-off   { background:#f8fafc; color:#64748b; border:1px solid #e2e8f0; }
    .pill-ios   { background:#eff6ff; color:#1e40af; border:1px solid #bfdbfe; }
    .pill-android { background:#ecfdf5; color:#065f46; border:1px solid #a7f3d0; }
    .pill-desktop { background:#f3e8ff; color:#6b21a8; border:1px solid #e9d5ff; }
    .vc-link-btn  { color:#1d4ed8; font-weight:700; text-decoration:none; padding:3px 9px; border-radius:6px; }
    .vc-link-btn:hover { background:#dbeafe; }

    /* Owner-detail modal */
    .vc-modal-bg   { position:fixed; inset:0; background:rgba(15,23,42,.55); display:flex; align-items:flex-start; justify-content:center; padding:40px 16px; z-index:1050; overflow-y:auto; }
    .vc-modal      { background:#fff; border-radius:14px; max-width:840px; width:100%; box-shadow:0 24px 60px -10px rgba(15,23,42,.4); overflow:hidden; }
    .vc-modal-head { padding:20px 24px; border-bottom:1px solid #e8ecf1; display:flex; align-items:center; gap:14px; }
    .vc-modal-body { padding:20px 24px; }
    .vc-modal-close{ background:transparent; border:0; font-size:24px; color:#94a3b8; cursor:pointer; line-height:1; padding:4px 8px; border-radius:6px; }
    .vc-modal-close:hover { background:#f1f5f9; color:#0f172a; }
    .vc-section    { margin-top:18px; }
    .vc-section-title { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#64748b; margin-bottom:10px; }
    .vc-mini-row   { display:flex; align-items:flex-start; gap:10px; padding:10px 12px; border-radius:8px; background:#f8fafc; border:1px solid #f1f5f9; font-size:12.5px; margin-bottom:6px; }
    .vc-timeline   { border-left:2px solid #e2e8f0; padding-left:16px; }
    .vc-tl-row     { position:relative; padding:8px 0; font-size:12.5px; }
    .vc-tl-row::before { content:''; position:absolute; left:-22px; top:14px; width:9px; height:9px; border-radius:50%; background:#0d9488; box-shadow:0 0 0 3px #fff, 0 0 0 4px #d1fae5; }
    .vc-tl-when    { font-size:11px; color:#64748b; }
    .vc-tl-event   { font-weight:600; color:#0f172a; }
    .vc-tl-meta    { font-size:11px; color:#94a3b8; }
    .vc-danger-btn { background:#dc2626; color:#fff; border:0; padding:8px 16px; border-radius:8px; font-weight:700; font-size:13px; cursor:pointer; }
    .vc-danger-btn:hover { background:#b91c1c; }
    .vc-danger-btn:disabled { opacity:.5; cursor:wait; }
</style>
@endsection

@section('content')
<section class="content-header"><h1><i class="fas fa-chart-line"></i> Pet-Owner PWA · Engagement</h1></section>
<section class="content">

    @if(session('status'))
        <div class="alert alert-success" style="border-radius:8px;">{{ session('status') }}</div>
    @endif
    @if(session('warning'))
        <div class="alert alert-warning" style="border-radius:8px;">⚠️ {{ session('warning') }}</div>
    @endif
    @if(session('error'))
        <div class="alert alert-danger" style="border-radius:8px;">✖ {{ session('error') }}</div>
    @endif

    <div class="vc-kpi-row">
        <div class="vc-kpi">
            <div class="lbl">Owner accounts</div>
            <div class="num">{{ $kpis['total'] }}</div>
            <div class="sub">Provisioned for this clinic</div>
        </div>
        <div class="vc-kpi">
            <div class="lbl">Opened the app</div>
            <div class="num">{{ $kpis['seen'] }}
                <small style="font-size:13px;font-weight:600;color:#94a3b8;">
                    · {{ $kpis['total'] ? round($kpis['seen'] / $kpis['total'] * 100) : 0 }}%
                </small>
            </div>
            <div class="sub">At least once on any device</div>
        </div>
        <div class="vc-kpi">
            <div class="lbl">Installed to home screen</div>
            <div class="num">{{ $kpis['installed'] }}
                <small style="font-size:13px;font-weight:600;color:#94a3b8;">
                    · {{ $kpis['total'] ? round($kpis['installed'] / $kpis['total'] * 100) : 0 }}%
                </small>
            </div>
            <div class="sub">Standalone PWA running on phone/desktop</div>
        </div>
        <div class="vc-kpi">
            <div class="lbl">Push enabled</div>
            <div class="num">{{ $kpis['push_enabled'] }}
                <small style="font-size:13px;font-weight:600;color:#94a3b8;">
                    · {{ $kpis['total'] ? round($kpis['push_enabled'] / $kpis['total'] * 100) : 0 }}%
                </small>
            </div>
            <div class="sub">Will receive reminders + announcements</div>
        </div>
    </div>

    {{-- ─── Broadcast composer ──────────────────────────────────── --}}
    <div class="vc-card">
        <div class="vc-card-title">Send a push notification</div>
        <form method="POST" action="{{ route('vc.portal-engagement.broadcast') }}">
            @csrf
            <div class="form-group">
                <label>Title <small style="color:#94a3b8;">(max 120)</small></label>
                <input type="text" name="title" class="form-control" required maxlength="120" placeholder="Eid Mubarak from Happy Paws!">
            </div>
            <div class="form-group">
                <label>Message <small style="color:#94a3b8;">(max 300)</small></label>
                <textarea name="body" rows="2" class="form-control" required maxlength="300" placeholder="The clinic will be closed Tuesday & Wednesday — book your post-Eid visit now."></textarea>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label>Open URL on tap <small style="color:#94a3b8;">(optional)</small></label>
                        <input type="text" name="url" class="form-control" placeholder="/app/book">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>Category</label>
                        <select name="category" class="form-control" required>
                            <option value="marketing">Marketing / announcements</option>
                            <option value="vaccinations">Vaccinations</option>
                            <option value="appointments">Appointments</option>
                            <option value="lab">Lab results</option>
                        </select>
                        <p class="help-block" style="font-size:11px;margin-top:4px;">
                            Only owners who didn't opt out of this category receive it.
                        </p>
                    </div>
                </div>
            </div>
            <p style="font-size:12px;color:#64748b;margin:8px 0 14px;">
                Tip: tick rows below to target specific owners. Leave all unticked to send to <strong>everyone</strong>.
            </p>
            <button type="submit" class="btn btn-primary" id="vc-send-broadcast">
                <i class="fa fa-paper-plane"></i> Send broadcast
            </button>
        </form>
    </div>

    {{-- ─── Owner table ──────────────────────────────────────── --}}
    <div class="vc-card">
        <div class="vc-card-title">Owners & devices</div>
        <div style="overflow-x:auto;">
            <table class="vc-table" id="vc-owner-table">
                <thead>
                    <tr>
                        <th style="width:28px;"><input type="checkbox" id="vc-select-all"></th>
                        <th>Owner</th>
                        <th>Contact</th>
                        <th>Installed?</th>
                        <th>Push?</th>
                        <th>Devices</th>
                        <th>Platform</th>
                        <th>Last seen</th>
                        <th>Last login</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @forelse ($rows as $r)
                    <tr>
                        <td>
                            <input type="checkbox" class="vc-target" form="" data-owner-id="{{ $r['id'] }}">
                        </td>
                        <td>{{ $r['name'] }}</td>
                        <td>
                            @if($r['phone']){{ $r['phone'] }}@endif
                            @if($r['email']) <br><small>{{ $r['email'] }}</small>@endif
                        </td>
                        <td>
                            @if($r['installed_at'])
                                <span class="pill pill-ok">✓ Installed</span>
                            @elseif($r['last_seen_at'])
                                <span class="pill pill-warn">browser only</span>
                            @else
                                <span class="pill pill-off">never opened</span>
                            @endif
                        </td>
                        <td>
                            @if($r['push_enabled'])
                                <span class="pill pill-ok">✓ Enabled</span>
                            @else
                                <span class="pill pill-off">off</span>
                            @endif
                        </td>
                        <td>{{ $r['device_count'] }}</td>
                        <td>
                            @if($r['platform'])
                                <span class="pill pill-{{ $r['platform'] }}">{{ $r['platform'] }}</span>
                            @else
                                —
                            @endif
                        </td>
                        <td>
                            @if($r['last_seen_at'])
                                <span title="{{ $r['last_seen_at'] }}">{{ \Carbon\Carbon::parse($r['last_seen_at'])->diffForHumans() }}</span>
                            @else — @endif
                        </td>
                        <td>
                            @if($r['last_login_at'])
                                {{ \Carbon\Carbon::parse($r['last_login_at'])->diffForHumans() }}
                            @else — @endif
                        </td>
                        <td>
                            <button type="button" class="vc-link-btn"
                                    onclick="vcOpenOwnerDetail({{ $r['id'] }})">
                                View →
                            </button>
                        </td>
                    </tr>
                    @empty
                    <tr><td colspan="10" style="text-align:center;color:#94a3b8;padding:30px;">No portal owners provisioned yet.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</section>

<script>
    // Wire the per-row checkboxes into the broadcast form as hidden inputs.
    (function () {
        const form = document.querySelector('form[action="{{ route('vc.portal-engagement.broadcast') }}"]');
        if (!form) return;
        document.querySelectorAll('.vc-target').forEach(cb => {
            cb.addEventListener('change', () => {
                const existing = form.querySelector('input[name="owner_ids[]"][value="' + cb.dataset.ownerId + '"]');
                if (cb.checked && !existing) {
                    const h = document.createElement('input');
                    h.type = 'hidden';
                    h.name = 'owner_ids[]';
                    h.value = cb.dataset.ownerId;
                    h.dataset.injected = '1';
                    form.appendChild(h);
                } else if (!cb.checked && existing) {
                    existing.remove();
                }
            });
        });
        document.getElementById('vc-select-all')?.addEventListener('change', e => {
            document.querySelectorAll('.vc-target').forEach(cb => {
                cb.checked = e.target.checked;
                cb.dispatchEvent(new Event('change'));
            });
        });
    })();
</script>

{{-- ─── Owner detail modal ──────────────────────────────────────── --}}
<div id="vc-owner-modal" class="vc-modal-bg" style="display:none;" onclick="if(event.target===this) vcCloseOwnerModal()">
    <div class="vc-modal">
        <div class="vc-modal-head">
            <div style="flex:1;">
                <div id="vc-om-name" style="font-size:18px;font-weight:800;color:#0f172a;">—</div>
                <div id="vc-om-contact" style="font-size:12px;color:#64748b;margin-top:2px;">—</div>
            </div>
            <button type="button" id="vc-om-signout" class="vc-danger-btn">
                Sign out everywhere
            </button>
            <button type="button" class="vc-modal-close" onclick="vcCloseOwnerModal()" aria-label="Close">×</button>
        </div>
        <div class="vc-modal-body">
            <div id="vc-om-loading" style="padding:40px;text-align:center;color:#64748b;">Loading…</div>
            <div id="vc-om-content" style="display:none;">

                {{-- KPIs --}}
                <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;">
                    <div class="vc-mini-row" style="flex-direction:column;align-items:flex-start;">
                        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#64748b;">Devices</div>
                        <div id="vc-om-kpi-devices" style="font-size:22px;font-weight:800;color:#0f172a;">0</div>
                    </div>
                    <div class="vc-mini-row" style="flex-direction:column;align-items:flex-start;">
                        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#64748b;">Push subscriptions</div>
                        <div id="vc-om-kpi-subs" style="font-size:22px;font-weight:800;color:#0f172a;">0</div>
                    </div>
                    <div class="vc-mini-row" style="flex-direction:column;align-items:flex-start;">
                        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#64748b;">Active sessions</div>
                        <div id="vc-om-kpi-sessions" style="font-size:22px;font-weight:800;color:#0f172a;">0</div>
                    </div>
                </div>

                {{-- Devices --}}
                <div class="vc-section">
                    <div class="vc-section-title">Devices that opened the app</div>
                    <div id="vc-om-devices"></div>
                </div>

                {{-- Push subscriptions --}}
                <div class="vc-section">
                    <div class="vc-section-title">Push subscriptions</div>
                    <div id="vc-om-subs"></div>
                </div>

                {{-- Active sessions --}}
                <div class="vc-section">
                    <div class="vc-section-title">Active sessions (Bearer tokens)</div>
                    <div id="vc-om-sessions"></div>
                </div>

                {{-- Activity timeline --}}
                <div class="vc-section">
                    <div class="vc-section-title">Recent activity</div>
                    <div id="vc-om-activity" class="vc-timeline"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const M           = document.getElementById('vc-owner-modal');
    const C           = document.getElementById('vc-om-content');
    const L           = document.getElementById('vc-om-loading');
    const elName      = document.getElementById('vc-om-name');
    const elContact   = document.getElementById('vc-om-contact');
    const elDevices   = document.getElementById('vc-om-devices');
    const elSubs      = document.getElementById('vc-om-subs');
    const elSessions  = document.getElementById('vc-om-sessions');
    const elActivity  = document.getElementById('vc-om-activity');
    const elKpiDev    = document.getElementById('vc-om-kpi-devices');
    const elKpiSub    = document.getElementById('vc-om-kpi-subs');
    const elKpiSes    = document.getElementById('vc-om-kpi-sessions');
    const btnSignOut  = document.getElementById('vc-om-signout');

    let currentOwnerId = null;

    const fmt = (s) => s ? new Date(s).toLocaleString() : '—';
    const esc = (s) => (s == null ? '' : String(s).replace(/[&<>"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[m])));

    window.vcOpenOwnerDetail = async function (id) {
        currentOwnerId = id;
        M.style.display = 'flex';
        C.style.display = 'none';
        L.style.display = 'block';
        elName.textContent    = '—';
        elContact.textContent = '—';
        try {
            const r = await fetch('{{ url('/vet-clinic/portal-engagement/owner') }}/' + id, {
                headers: { 'Accept': 'application/json' },
                credentials: 'same-origin'
            });
            if (!r.ok) throw new Error('HTTP ' + r.status);
            const d = await r.json();
            renderOwnerDetail(d);
        } catch (e) {
            L.innerHTML = '<div style="color:#b91c1c;">Couldn\'t load: ' + esc(e.message) + '</div>';
        }
    };

    window.vcCloseOwnerModal = function () {
        M.style.display = 'none';
        currentOwnerId = null;
    };

    function renderOwnerDetail(d) {
        elName.textContent    = d.owner.name;
        elContact.textContent = [d.owner.phone, d.owner.email].filter(Boolean).join(' · ') || '—';

        elKpiDev.textContent = d.devices.length;
        elKpiSub.textContent = d.subscriptions.length;
        elKpiSes.textContent = d.sessions.length;

        elDevices.innerHTML = d.devices.length === 0
            ? '<div style="color:#94a3b8;font-size:12px;padding:6px 4px;">No devices have opened the app yet.</div>'
            : d.devices.map(x => `
                <div class="vc-mini-row">
                    <div style="flex:1;">
                        <div style="font-weight:600;color:#0f172a;">${esc(x.user_agent)}</div>
                        <div style="font-size:11px;color:#64748b;margin-top:2px;">
                            ${x.platform ? '<span class="pill pill-' + esc(x.platform) + '" style="font-size:10px;padding:1px 6px;">' + esc(x.platform) + '</span> · ' : ''}
                            ${x.installed_at ? '<span style="color:#047857;font-weight:600;">✓ Installed</span> · ' : '<span style="color:#9a3412;">Browser only</span> · '}
                            first ${fmt(x.first_seen_at)} · last ${fmt(x.last_seen_at)}
                        </div>
                    </div>
                </div>`).join('');

        elSubs.innerHTML = d.subscriptions.length === 0
            ? '<div style="color:#94a3b8;font-size:12px;padding:6px 4px;">No push subscriptions.</div>'
            : d.subscriptions.map(x => `
                <div class="vc-mini-row">
                    <div style="flex:1;">
                        <div style="font-weight:600;color:#0f172a;">${esc(x.user_agent)}</div>
                        <div style="font-size:11px;color:#64748b;margin-top:2px;">
                            Categories: ${esc((x.categories || []).join(', ') || '—')} · via ${esc(x.endpoint_host)}
                        </div>
                        <div style="font-size:11px;color:#64748b;">
                            Created ${fmt(x.created_at)} · last delivered ${fmt(x.last_used_at)}
                            ${x.consecutive_failures > 0 ? '<span style="color:#b91c1c;font-weight:600;"> · ' + x.consecutive_failures + ' recent failures</span>' : ''}
                        </div>
                    </div>
                </div>`).join('');

        elSessions.innerHTML = d.sessions.length === 0
            ? '<div style="color:#94a3b8;font-size:12px;padding:6px 4px;">No active sessions.</div>'
            : d.sessions.map(x => `
                <div class="vc-mini-row">
                    <div style="flex:1;">
                        <div style="font-weight:600;color:#0f172a;">${esc(x.user_agent)} ${x.ip ? '<span style="color:#64748b;font-weight:400;">· ' + esc(x.ip) + '</span>' : ''}</div>
                        <div style="font-size:11px;color:#64748b;margin-top:2px;">
                            Signed in ${fmt(x.created_at)} · last used ${fmt(x.last_used_at)}
                            ${x.expires_at ? ' · expires ' + fmt(x.expires_at) : ''}
                        </div>
                    </div>
                </div>`).join('');

        elActivity.innerHTML = d.activity.length === 0
            ? '<div style="color:#94a3b8;font-size:12px;padding:6px 4px;">Nothing to show yet.</div>'
            : d.activity.map(a => `
                <div class="vc-tl-row">
                    <div class="vc-tl-when">${fmt(a.when)}</div>
                    <div class="vc-tl-event">${esc(a.event)}</div>
                    <div class="vc-tl-meta">${esc(a.meta || '')}</div>
                </div>`).join('');

        L.style.display = 'none';
        C.style.display = 'block';
    }

    btnSignOut.addEventListener('click', async function () {
        if (!currentOwnerId) return;
        if (!confirm('Sign this owner out of every device? They\'ll need to log in again everywhere.')) return;
        btnSignOut.disabled = true;
        try {
            const r = await fetch('{{ url('/vet-clinic/portal-engagement/owner') }}/' + currentOwnerId + '/sign-out', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                },
                credentials: 'same-origin'
            });
            const d = await r.json();
            alert(d.message || ('Revoked ' + (d.revoked || 0) + ' session(s).'));
            // Reload the modal so the sessions section refreshes.
            await vcOpenOwnerDetail(currentOwnerId);
        } catch (e) {
            alert('Sign-out failed: ' + e.message);
        } finally {
            btnSignOut.disabled = false;
        }
    });

    document.addEventListener('keydown', e => { if (e.key === 'Escape' && M.style.display === 'flex') vcCloseOwnerModal(); });
})();
</script>
@endsection
