@extends('layouts.app')
@section('title', __('clinicCore::lang.patient_contacts'))

@section('css')
<style>
.vc-page-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:18px; flex-wrap:wrap; gap:10px; }
.vc-page-title  { font-size:22px; font-weight:800; color:#1e293b; display:flex; align-items:center; gap:10px; }
.vc-page-title i { color:#2980b9; }
.vc-page-actions { display:flex; gap:8px; flex-wrap:wrap; }

.filter-card { background:#fff; border-radius:12px; padding:16px 20px; box-shadow:0 1px 6px rgba(0,0,0,.08); margin-bottom:14px; border:1px solid #e8ecf1; }
.filter-row  { display:flex; gap:10px; flex-wrap:wrap; align-items:flex-end; }
.filter-field { display:flex; flex-direction:column; gap:4px; }
.filter-label { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#64748b; white-space:nowrap; }
.filter-field .form-control { height:34px; font-size:12px; border-radius:7px; border:1.5px solid #e2e8f0; }
.search-wrap { position:relative; flex:1; min-width:220px; }
.search-wrap .fa { position:absolute; left:10px; top:50%; transform:translateY(-50%); color:#94a3b8; font-size:12px; }
.search-wrap input { padding-left:30px !important; }

.view-toggle { display:flex; gap:4px; }
.view-toggle-btn { width:32px; height:32px; border:1.5px solid #e2e8f0; border-radius:7px; background:#fff; display:flex; align-items:center; justify-content:center; cursor:pointer; color:#94a3b8; font-size:13px; transition:all .13s; }
.view-toggle-btn.active { background:#2980b9; border-color:#2980b9; color:#fff; }

#patient_contacts_table td { vertical-align:middle; font-size:12.5px; }
#patient_contacts_table_wrapper .dataTables_filter { display:none; }

.vc-table-box { background:#fff; border-radius:10px; overflow:hidden; box-shadow:0 1px 6px rgba(0,0,0,.08); border:1px solid #e8ecf1; }

/* ── Alert + Finance inline badges ── */
.vc-lbadge { display:inline-block; font-size:10px; font-weight:700; padding:2px 7px; border-radius:10px; white-space:nowrap; margin:1px 1px 2px; line-height:1.6; }
.vc-lbadge-danger  { background:#fef2f2; color:#b91c1c; border:1px solid #fca5a5; }
.vc-lbadge-warning { background:#fffbeb; color:#92400e; border:1px solid #fcd34d; }
.vc-lbadge-missed  { background:#f0f9ff; color:#075985; border:1px solid #93c5fd; }

/* ── Contact Cards ─── */
#owner_card_grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(260px,1fr)); gap:16px; }
.owner-card {
    background:#fff; border-radius:14px; border:1px solid #e8ecf1;
    box-shadow:0 2px 8px rgba(0,0,0,.06); overflow:hidden;
    transition:box-shadow .18s, transform .18s; display:flex; flex-direction:column;
}
.owner-card:hover { box-shadow:0 8px 24px rgba(0,0,0,.12); transform:translateY(-2px); }
.owner-card-header {
    padding:20px 18px 14px;
    background:linear-gradient(135deg,#2980b9,#6366f1);
    display:flex; align-items:center; gap:14px;
}
.owner-avatar {
    width:50px; height:50px; border-radius:50%; flex-shrink:0;
    background:rgba(255,255,255,.2); border:2px solid rgba(255,255,255,.4);
    display:flex; align-items:center; justify-content:center;
    font-size:20px; font-weight:700; color:#fff; text-transform:uppercase;
}
.owner-card-name { font-size:15px; font-weight:800; color:#fff; margin-bottom:2px; }
.owner-card-sub  { font-size:11.5px; color:rgba(255,255,255,.8); }
.owner-card-body { padding:14px 16px; flex:1; }
.owner-card-info span { display:flex; align-items:center; gap:8px; font-size:12px; color:#64748b; margin-bottom:6px; }
.owner-card-info i { color:#cbd5e1; width:14px; text-align:center; }
.owner-card-info a { color:#2980b9; text-decoration:none; }
.owner-card-info a:hover { text-decoration:underline; }
.owner-pets-badge {
    display:inline-flex; align-items:center; gap:6px;
    background:#eff6ff; color:#1d4ed8; font-size:11px; font-weight:700;
    padding:3px 10px; border-radius:12px; border:1px solid #bfdbfe;
    margin-top:6px;
}
.owner-card-footer { padding:10px 16px; background:#f8fafc; border-top:1px solid #f1f5f9; display:flex; gap:6px; justify-content:flex-end; }
</style>
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header" style="display:none"></section>
<section class="content">

<div class="vc-page-header">
    <div class="vc-page-title">
        <i class="fas fa-users"></i>
        @lang('clinicCore::lang.patient_contacts')
        <span style="font-size:13px;font-weight:500;color:#94a3b8;margin-left:4px;">
            · {{ $total }} contacts
        </span>
    </div>
    <div class="vc-page-actions">
        <div class="view-toggle" id="view_toggle">
            <button class="view-toggle-btn active" data-view="list" title="List View"><i class="fa fa-list"></i></button>
            <button class="view-toggle-btn" data-view="card" title="Card View"><i class="fa fa-th-large"></i></button>
        </div>
        @can('clinic.manage_patient_contacts')
        <a href="{{ route('clinic.patient-contacts.create') }}" class="btn btn-primary btn-sm">
            <i class="fa fa-plus"></i> Add Contact
        </a>
        @endcan
    </div>
</div>

{{-- Filter Card --}}
<div class="filter-card">
    <div class="filter-row">
        <div class="filter-field" style="flex:1;min-width:220px;">
            <span class="filter-label"><i class="fa fa-search fa-fw"></i> Search</span>
            <div class="search-wrap">
                <i class="fa fa-search"></i>
                <input type="text" id="owner_search" class="form-control" placeholder="Name, mobile, email…">
            </div>
        </div>
        <div class="filter-field" style="align-self:flex-end;">
            <button id="btn_clear_owner_filters" title="Clear filters"
                    style="height:34px;padding:0 14px;border-radius:7px;border:1.5px solid #e2e8f0;
                           background:#fff;color:#64748b;font-size:12px;font-weight:700;cursor:pointer;
                           display:inline-flex;align-items:center;gap:6px;transition:all .14s;">
                <i class="fa fa-times-circle" style="color:#ef4444;font-size:13px;"></i> Clear
            </button>
        </div>
    </div>
</div>

{{-- List View --}}
<div id="owner_list_view">
    <div class="vc-table-box">
        <div style="padding:14px;">
            <table class="table table-bordered table-striped table-hover" id="patient_contacts_table" style="font-size:12.5px;">
                <thead style="background:#f8fafc;">
                    <tr>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Contact</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Email</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Patients</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Alerts</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Financials</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Actions</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>

{{-- Card View --}}
<div id="owner_card_view" style="display:none;">
    <div id="owner_card_grid"></div>
    <div id="owner_card_empty" style="display:none;text-align:center;padding:60px 20px;background:#fff;border-radius:12px;border:2px dashed #e2e8f0;">
        <div style="font-size:48px;margin-bottom:12px;opacity:.3;">👥</div>
        <p style="color:#94a3b8;font-size:14px;">No patients found.</p>
    </div>
    <div id="owner_card_loading" style="text-align:center;padding:40px;"><i class="fa fa-spinner fa-spin fa-2x text-muted"></i></div>
</div>

</section>
@endsection

@section('javascript')
<script>
var currentView   = 'list';
var ownerTableInst = null;
var ownerAjaxUrl  = '{{ route('clinic.patient-contacts.list') }}';
var csrfToken     = '{{ csrf_token() }}';
window.clcActionTarget = '{{ $clcActionTarget ?? "_self" }}';

$(document).on('click', '#patient_contacts_table a.btn[href], .owner-card a.btn[href]', function (e) {
    if (window.clcActionTarget === '_blank') {
        e.preventDefault();
        window.open($(this).attr('href'), '_blank');
    }
});

$(document).ready(function () {
    initTable();
    initFilters();
    initViewToggle();
});

function initTable() {
    ownerTableInst = $('#patient_contacts_table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: ownerAjaxUrl,
            data: function (d) { d.filter_search = $('#owner_search').val(); }
        },
        columns: [
            { data: 'name_col',       name: 'name',     orderable: false },
            { data: 'email_col',      name: 'email',    orderable: false },
            { data: 'pets_count_col', name: 'patients',     orderable: false },
            { data: 'alerts_col',     name: 'alerts',   orderable: false, searchable: false },
            { data: 'finance_col',    name: 'finance',  orderable: false, searchable: false },
            { data: 'action',         name: 'action',   orderable: false, searchable: false }
        ],
        pageLength: 25,
        language: { processing: '<i class="fa fa-spinner fa-spin"></i> Loading…' }
    });
}

function loadCards() {
    $('#owner_card_loading').show();
    $('#owner_card_grid').hide();
    $('#owner_card_empty').hide();

    $.get(ownerAjaxUrl, { filter_search: $('#owner_search').val(), length: 100, start: 0 }, function (res) {
        $('#owner_card_loading').hide();
        var data = res.data || [];
        if (!data.length) { $('#owner_card_empty').show(); return; }

        var html = '';
        data.forEach(function (o) {
            var initial  = (o.name_plain || '?').charAt(0).toUpperCase();
            var overdue  = o.overdue_vax_raw  || 0;
            var dueSoon  = o.due_soon_vax_raw || 0;
            var missed   = o.missed_apt_raw   || 0;
            var dueAmt   = parseFloat(o.due_amount_raw  || 0);
            var invCount = parseInt(o.invoice_count_raw || 0);

            // Header gradient: red if overdue, yellow if due-soon, default blue-purple
            var hdrGrad = overdue
                ? 'linear-gradient(135deg,#7f1d1d,#b91c1c,#ef4444)'
                : (dueSoon ? 'linear-gradient(135deg,#78350f,#d97706,#f59e0b)' : 'linear-gradient(135deg,#2980b9,#6366f1)');

            html += '<div class="owner-card">';
            html += '  <div class="owner-card-header" style="background:' + hdrGrad + ';">';
            html += '    <div class="owner-avatar">' + initial + '</div>';
            html += '    <div style="flex:1;min-width:0;">';
            html += '      <div class="owner-card-name">' + (o.name_plain || '—') + '</div>';
            if (o.mobile_plain) html += '<div class="owner-card-sub"><i class="fa fa-phone"></i> ' + o.mobile_plain + '</div>';
            html += '    </div>';
            html += '  </div>';

            html += '  <div class="owner-card-body">';
            html += '    <div class="owner-card-info">';
            if (o.email_plain) html += '<span><i class="fa fa-envelope"></i><a href="mailto:' + o.email_plain + '">' + o.email_plain + '</a></span>';
            html += '    </div>';

            // Patients + alert badges row
            html += '    <div style="display:flex;flex-wrap:wrap;gap:4px;margin-top:8px;align-items:center;">';
            html += '      <div class="owner-pets-badge"><i class="fas fa-notes-medical"></i> ' + (o.pets_count || 0) + ' patient' + (o.pets_count !== 1 ? 's' : '') + '</div>';
            if (overdue)  html += '<span class="vc-lbadge vc-lbadge-danger"><i class="fa fa-exclamation-triangle"></i> ' + overdue + ' overdue</span>';
            if (dueSoon)  html += '<span class="vc-lbadge vc-lbadge-warning"><i class="fa fa-clock"></i> ' + dueSoon + ' due soon</span>';
            if (missed)   html += '<span class="vc-lbadge vc-lbadge-missed"><i class="fa fa-calendar-times"></i> ' + missed + ' missed</span>';
            html += '    </div>';

            // Financial row
            if (invCount) {
                html += '    <div style="margin-top:6px;font-size:11px;color:#64748b;">';
                html += '      <i class="fa fa-file-alt"></i> ' + invCount + ' invoice' + (invCount !== 1 ? 's' : '');
                if (dueAmt > 0) {
                    html += ' &nbsp;<span class="vc-lbadge vc-lbadge-danger"><i class="fa fa-exclamation-circle"></i> ' + dueAmt.toFixed(2) + ' due</span>';
                } else {
                    html += ' &nbsp;<span style="color:#16a34a;font-weight:700;"><i class="fa fa-check-circle"></i> Settled</span>';
                }
                html += '    </div>';
            }

            html += '  </div>';
            html += '  <div class="owner-card-footer">';
            html += '    <a href="' + o.show_url + '" class="btn btn-xs btn-info" title="View Profile"><i class="fa fa-eye"></i> Profile</a>';
            html += '  </div>';
            html += '</div>';
        });
        $('#owner_card_grid').html(html).show();
    }).fail(function () { $('#owner_card_loading').hide(); toastr.error('Failed to load.'); });
}

var filterTimer = null;
function initFilters() {
    $('#owner_search').on('input', function () {
        clearTimeout(filterTimer);
        filterTimer = setTimeout(applyFilters, 350);
    });
    $('#btn_clear_owner_filters').on('click', function () {
        $('#owner_search').val('');
        applyFilters();
    });
}

function applyFilters() {
    if (currentView === 'list') { if (ownerTableInst) ownerTableInst.ajax.reload(); }
    else { loadCards(); }
}

function initViewToggle() {
    $('#view_toggle .view-toggle-btn').on('click', function () {
        var view = $(this).data('view');
        if (view === currentView) return;
        currentView = view;
        $(this).addClass('active').siblings().removeClass('active');
        if (view === 'list') { $('#owner_list_view').show(); $('#owner_card_view').hide(); }
        else { $('#owner_list_view').hide(); $('#owner_card_view').show(); loadCards(); }
    });
}
</script>

{{-- #3b - shared unblock modal + handler. The list rows emit a
     .vc-unblock-btn button for blocked contacts; this partial gives that
     class a modal to open. --}}
@include('clinicCore::partials._unblock_modal')

{{-- #3 (this turn) - shared Send Message modal. List rows emit a
     .vc-send-msg-btn button; this partial provides the modal +
     submit handler. --}}
@include('clinicCore::partials._send_message_modal')
@endsection
