@extends('layouts.app')
@section('title', __('vetClinic::lang.pets'))

@section('css')
<style>
/* ── Page Header ─────────────────────────────────── */
.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:#8e44ad; }
.vc-page-actions { display:flex; gap:8px; flex-wrap:wrap; }

/* ── Stats Row ─────────────────────────────────── */
.pet-stats-row { display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:12px; margin-bottom:18px; }
.pet-stat-box {
    background:#fff; border-radius:10px; padding:14px 18px;
    box-shadow:0 1px 4px rgba(0,0,0,.08); border-top:4px solid;
    display:flex; align-items:center; gap:12px; cursor:pointer;
    transition:box-shadow .15s, transform .12s;
}
.pet-stat-box:hover { box-shadow:0 4px 14px rgba(0,0,0,.12); transform:translateY(-1px); }
.pet-stat-icon { font-size:22px; opacity:.25; }
.pet-stat-num  { font-size:24px; font-weight:800; line-height:1; }
.pet-stat-lbl  { font-size:10px; text-transform:uppercase; letter-spacing:.5px; color:#94a3b8; margin-top:2px; }

/* ── Filter Card ─────────────────────────────────── */
.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:200px; }
.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 ─────────────────────────────────── */
.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:#3b82f6; border-color:#3b82f6; color:#fff; }

/* ── DataTable ─────────────────────────────────── */
#pets_table td { vertical-align:middle; font-size:12.5px; }
#pets_table_wrapper .dataTables_filter { display:none; }
.export-bar { display:flex; align-items:center; gap:8px; margin-bottom:10px; justify-content:flex-end; }

/* ── Card Grid ─────────────────────────────────── */
#pet_card_grid {
    display:grid; grid-template-columns:repeat(auto-fill,minmax(240px,1fr)); gap:16px;
    margin-top:4px;
}
.pet-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;
}
.pet-card:hover { box-shadow:0 8px 24px rgba(0,0,0,.12); transform:translateY(-3px); }
.pet-card-photo {
    height:130px; background:linear-gradient(135deg,#f8fafc,#e8ecf1);
    display:flex; align-items:center; justify-content:center;
    overflow:hidden; position:relative;
}
.pet-card-photo img { width:100%; height:100%; object-fit:cover; }
.pet-card-photo .pc-species-icon { font-size:52px; opacity:.18; }
.pet-card-status-dot {
    position:absolute; top:10px; right:10px;
    width:10px; height:10px; border-radius:50%;
    border:2px solid #fff; box-shadow:0 1px 3px rgba(0,0,0,.2);
}
.pet-card-body { padding:14px 16px; flex:1; }
.pet-card-name {
    font-size:16px; font-weight:800; color:#1e293b; margin-bottom:3px;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
    text-decoration:none; display:block;
}
.pet-card-name:hover { color:#2980b9; }
.pet-card-sub { font-size:11.5px; color:#94a3b8; margin-bottom:8px; }
.pet-card-info { font-size:11.5px; color:#64748b; display:flex; flex-direction:column; gap:3px; }
.pet-card-info span { display:flex; align-items:center; gap:6px; }
.pet-card-info i { color:#cbd5e1; width:12px; text-align:center; }
.pet-card-footer {
    padding:10px 16px; background:#f8fafc; border-top:1px solid #f1f5f9;
    display:flex; gap:6px; justify-content:flex-end;
}
.pet-card-owner {
    padding:10px 16px 0; font-size:11.5px; color:#64748b;
    border-top:1px solid #f8fafc; display:flex; align-items:center; gap:6px;
}
.pet-card-owner a { color:#2980b9; text-decoration:none; font-weight:600; }
.pet-card-owner a:hover { text-decoration:underline; }

/* ── Table Box ─────────────────────────────────── */
.vc-table-box {
    background:#fff; border-radius:10px; overflow:hidden;
    box-shadow:0 1px 6px rgba(0,0,0,.08); border:1px solid #e8ecf1;
}
</style>
@include('vetClinic::partials._mobile_responsive')
@endsection

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

{{-- Page Header --}}
<div class="vc-page-header">
    <div class="vc-page-title">
        <i class="fas fa-paw"></i>
        @lang('vetClinic::lang.pets')
        <span style="font-size:13px;font-weight:500;color:#94a3b8;margin-left:4px;">
            · {{ $stats['total'] }} registered
        </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('vet_clinic.manage_pets')
        <a href="{{ route('vc.pets.create') }}" class="btn btn-primary btn-sm">
            <i class="fa fa-plus"></i> Add Pet
        </a>
        @endcan
    </div>
</div>

{{-- Stats Row --}}
<div class="pet-stats-row">
    <div class="pet-stat-box" style="border-color:#8e44ad;" data-filter-status="">
        <div class="pet-stat-icon" style="color:#8e44ad;"><i class="fas fa-paw"></i></div>
        <div>
            <div class="pet-stat-num" style="color:#8e44ad;">{{ $stats['total'] }}</div>
            <div class="pet-stat-lbl">Total Pets</div>
        </div>
    </div>
    <div class="pet-stat-box" style="border-color:#22c55e;" data-filter-status="active">
        <div class="pet-stat-icon" style="color:#22c55e;"><i class="fas fa-check-circle"></i></div>
        <div>
            <div class="pet-stat-num" style="color:#22c55e;">{{ $stats['active'] }}</div>
            <div class="pet-stat-lbl">Active</div>
        </div>
    </div>
    <div class="pet-stat-box" style="border-color:#94a3b8;" data-filter-status="">
        <div class="pet-stat-icon" style="color:#94a3b8;"><i class="fas fa-heart-broken"></i></div>
        <div>
            <div class="pet-stat-num" style="color:#94a3b8;">{{ $stats['deceased'] }}</div>
            <div class="pet-stat-lbl">Deceased</div>
        </div>
    </div>
    @foreach($speciesCounts as $sp => $cnt)
    @php $spIcon = ['dog'=>'🐕','cat'=>'🐈','rabbit'=>'🐇','bird'=>'🦜','fish'=>'🐟'][$sp] ?? '🐾'; @endphp
    <div class="pet-stat-box" style="border-color:#3b82f6;" data-filter-species="{{ $sp }}">
        <div class="pet-stat-icon" style="font-size:26px;">{{ $spIcon }}</div>
        <div>
            <div class="pet-stat-num" style="color:#3b82f6;">{{ $cnt }}</div>
            <div class="pet-stat-lbl">{{ ucfirst($sp) }}</div>
        </div>
    </div>
    @endforeach
</div>

{{-- Filter Card --}}
<div class="filter-card">
    <div class="filter-row">
        <div class="filter-field" style="flex:1;min-width:200px;">
            <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="pet_search" class="form-control" placeholder="Pet name, owner, breed, chip…">
            </div>
        </div>
        <div class="filter-field" style="min-width:130px;">
            <span class="filter-label"><i class="fa fa-paw fa-fw"></i> Species</span>
            <select id="pet_species" class="form-control">
                <option value="">All Species</option>
                <option value="dog">🐕 Dog</option>
                <option value="cat">🐈 Cat</option>
                <option value="rabbit">🐇 Rabbit</option>
                <option value="bird">🦜 Bird</option>
                <option value="fish">🐟 Fish</option>
                <option value="other">🐾 Other</option>
            </select>
        </div>
        <div class="filter-field" style="min-width:120px;">
            <span class="filter-label"><i class="fa fa-toggle-on fa-fw"></i> Status</span>
            <select id="pet_status" class="form-control">
                <option value="">All Status</option>
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
            </select>
        </div>
        <div class="filter-field" style="align-self:flex-end;">
            <button id="btn_clear_pet_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 (DataTable) --}}
<div id="pet_list_view">
    <div class="vc-table-box">
        <div style="padding:14px;">
            <table class="table table-bordered table-striped table-hover" id="pets_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;">Pet</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Owner</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Species</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Age</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Stats</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Vaccines</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Chronic</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Status</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="pet_card_view" style="display:none;">
    <div id="pet_card_grid"></div>
    <div id="pet_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 pets found matching your filters.</p>
    </div>
    <div id="pet_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 petTableInst    = null;
var petAjaxUrl      = '{{ route('vc.pets.list') }}';
var deleteBaseUrl   = '{{ url('vet-clinic/pets') }}';
var csrfToken       = '{{ csrf_token() }}';
var speciesIcons    = {dog:'🐕',cat:'🐈',rabbit:'🐇',bird:'🦜',fish:'🐟'};
window.vcActionTarget = '{{ $vcActionTarget ?? "_self" }}';

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

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

    // Re-init popovers after each DataTable draw (DOM replaced on redraw)
    $('#pets_table').on('draw.dt', function () {
        $('[data-toggle="popover"]').popover({ container: 'body' });
    });
});

/* ── DataTable ─────────────────────────────── */
function initTable() {
    petTableInst = $('#pets_table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: petAjaxUrl,
            data: function (d) {
                d.filter_search  = $('#pet_search').val();
                d.filter_species = $('#pet_species').val();
                d.filter_status  = $('#pet_status').val();
            }
        },
        columns: [
            { data: 'petname_col',       name: 'petname',  orderable: true },
            { data: 'owner_col',         name: 'owner_name', orderable: false },
            { data: 'species_col',       name: 'species', orderable: true },
            { data: 'age',               name: 'age', orderable: false },
            { data: 'stats_col',         name: 'stats', orderable: false, searchable: false },
            { data: 'vaccine_alert_col', name: 'vaccine_alert', orderable: false, searchable: false },
            { data: 'chronic_col',       name: 'chronic', orderable: false, searchable: false },
            { data: 'status_badge',      name: 'status', orderable: false },
            { data: 'action',            name: 'action', orderable: false, searchable: false }
        ],
        order: [[0, 'asc']],
        pageLength: 25,
        language: { processing: '<i class="fa fa-spinner fa-spin"></i> Loading…' }
    });
}

/* ── Card View Loader ──────────────────────── */
function loadCards() {
    $('#pet_card_loading').show();
    $('#pet_card_grid').hide();
    $('#pet_card_empty').hide();

    $.get(petAjaxUrl, {
        filter_search:  $('#pet_search').val(),
        filter_species: $('#pet_species').val(),
        filter_status:  $('#pet_status').val(),
        length: 100, start: 0
    }, function (res) {
        $('#pet_card_loading').hide();
        var data = res.data || [];
        if (!data.length) {
            $('#pet_card_empty').show(); return;
        }
        var html = '';
        data.forEach(function (p) {
            var icon    = speciesIcons[p.species ? p.species.toLowerCase() : ''] || '🐾';
            var photo   = p.photo_url
                ? '<img src="' + p.photo_url + '" alt="">'
                : '<div class="pc-species-icon">' + icon + '</div>';
            var dotColor = p.status === 'active' ? '#22c55e' : '#ef4444';
            var genderIcon = p.gender === 'male' ? '♂' : (p.gender === 'female' ? '♀' : '');
            html += '<div class="pet-card">';
            html += '  <div class="pet-card-photo">' + photo;
            html += '    <div class="pet-card-status-dot" style="background:' + dotColor + ';"></div>';
            html += '  </div>';
            html += '  <div class="pet-card-body">';
            html += '    <a href="' + p.show_url + '" class="pet-card-name">' + (p.petname || '—') + '</a>';
            html += '    <div class="pet-card-sub">' + icon + ' ' + (p.species ? p.species.charAt(0).toUpperCase()+p.species.slice(1) : '') + (p.breed ? ' · ' + p.breed : '') + (genderIcon ? ' ' + genderIcon : '') + '</div>';
            html += '    <div class="pet-card-info">';
            if (p.age_str) html += '<span><i class="fa fa-birthday-cake"></i>' + p.age_str + '</span>';
            if (p.microchip_no) html += '<span><i class="fas fa-microchip"></i>' + p.microchip_no + '</span>';
            html += '    </div>';
            // Smart stats row
            html += '  <div style="display:flex;gap:10px;font-size:11px;color:#64748b;margin-top:8px;padding-top:8px;border-top:1px solid #f1f5f9;">';
            html += '    <span title="Appointments"><i class="fa fa-calendar" style="color:#3b82f6;"></i>&nbsp;' + (p.appointments_count || 0) + '</span>';
            html += '    <span title="Vaccinations"><i class="fas fa-syringe" style="color:#27ae60;"></i>&nbsp;' + (p.vaccinations_count || 0) + '</span>';
            if (p.chronic_count > 0) html += '    <span title="Chronic Conditions"><i class="fas fa-heartbeat" style="color:#ef4444;"></i>&nbsp;' + p.chronic_count + '</span>';
            html += '  </div>';
            // Vaccine alert badge
            if (p.overdue_vax > 0) {
                html += '  <div style="margin-top:6px;"><span class="badge" style="background:#ef4444;font-size:10px;"><i class="fas fa-exclamation-triangle"></i> ' + p.overdue_vax + ' Overdue Vaccine</span></div>';
            } else if (p.due_soon_vax > 0) {
                html += '  <div style="margin-top:6px;"><span class="badge" style="background:#f59e0b;font-size:10px;"><i class="fa fa-clock"></i> ' + p.due_soon_vax + ' Due Soon</span></div>';
            }
            html += '  </div>';
            if (p.owner_name_plain) {
                html += '  <div class="pet-card-owner"><i class="fa fa-user fa-fw" style="color:#cbd5e1;"></i><a href="' + (p.owner_url || '#') + '">' + p.owner_name_plain + '</a></div>';
            }
            html += '  <div class="pet-card-footer">';
            html += '    <a href="' + p.show_url + '" class="btn btn-xs btn-info" title="View"><i class="fa fa-eye"></i></a>';
            html += '    <a href="' + p.edit_url + '" class="btn btn-xs btn-warning" title="Edit"><i class="fa fa-edit"></i></a>';
            html += '    <button class="btn btn-xs btn-danger btn-delete-pet-card" data-id="' + p.id + '" title="Delete"><i class="fa fa-trash"></i></button>';
            html += '  </div>';
            html += '</div>';
        });
        $('#pet_card_grid').html(html).show();
    }).fail(function () {
        $('#pet_card_loading').hide();
        toastr.error('Failed to load pets.');
    });
}

/* ── Filters ───────────────────────────────── */
var filterTimer = null;
function initFilters() {
    $('#pet_search').on('input', function () {
        clearTimeout(filterTimer);
        filterTimer = setTimeout(applyFilters, 350);
    });
    $('#pet_species, #pet_status').on('change', function () { applyFilters(); });

    // Stat box quick filters
    $('[data-filter-status]').on('click', function () {
        var status = $(this).data('filter-status') || '';
        $('#pet_status').val(status);
        applyFilters();
    });
    $('[data-filter-species]').on('click', function () {
        var sp = $(this).data('filter-species') || '';
        $('#pet_species').val(sp);
        applyFilters();
    });

    $('#btn_clear_pet_filters').on('click', function () {
        $('#pet_search').val('');
        $('#pet_species, #pet_status').val('');
        applyFilters();
    });

}

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

/* ── View Toggle ───────────────────────────── */
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') {
            $('#pet_list_view').show();
            $('#pet_card_view').hide();
        } else {
            $('#pet_list_view').hide();
            $('#pet_card_view').show();
            loadCards();
        }
    });
}

/* ── Delete (list) ─────────────────────────── */
$(document).on('click', '.btn-delete-pet, .btn-delete-pet-card', function () {
    if (!confirm('@lang('vetClinic::lang.are_you_sure')')) return;
    var id = $(this).data('id');
    var $el = $(this);
    $.ajax({
        url: deleteBaseUrl + '/' + id,
        method: 'DELETE',
        data: { _token: csrfToken },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg);
                if (petTableInst) petTableInst.ajax.reload();
                $el.closest('.pet-card').fadeOut(300, function () { $(this).remove(); });
            }
        }
    });
});
</script>
@endsection
