@extends('layouts.app')

@section('title', 'Members')
@section('page-title', 'Members')
@section('page-subtitle', 'KYC, guarantors, status, and account numbers')

@section('content')
@php
    $showBranchField = $showBranchField ?? $branches->count() > 1;
    $filterKeys = ['status', 'kyc_status', 'registration_source', 'created', 'account_officer_id', 'customer_group_id'];
    if ($showBranchField) {
        $filterKeys[] = 'branch_id';
    }
    $activeFilters = request()->has('search') || request()->hasAny($filterKeys);
    $sourceLabels = ['staff' => 'Staff created', 'self_service' => 'Member requests'];
    $activeFilterChips = collect([
        request('search') ? 'Search: '.request('search') : null,
        request('status') ? 'Status: '.ucfirst(request('status')) : null,
        request('kyc_status') ? 'KYC: '.ucfirst(request('kyc_status')) : null,
        request('registration_source') ? 'Source: '.($sourceLabels[request('registration_source')] ?? request('registration_source')) : null,
        request('created') === 'this_month' ? 'Created this month' : null,
        $showBranchField && request('branch_id') ? 'Branch: '.($branches->firstWhere('id', (int) request('branch_id'))?->name ?? 'Selected branch') : null,
        request('account_officer_id') ? 'Officer: '.(request('account_officer_id') === 'unassigned' ? 'Unassigned' : ($accountOfficers->firstWhere('id', (int) request('account_officer_id'))?->name ?? 'Selected officer')) : null,
        request('customer_group_id') ? 'Group: '.($customerGroups->firstWhere('id', (int) request('customer_group_id'))?->name ?? 'Selected group') : null,
    ])->filter();
    $memberStatCards = [
        ['Total members', $memberStats['total'] ?? 0, 'All active and inactive member records.', 'bi-people', route('tenant.customers.index'), 'total'],
        ['New members', $memberStats['new_this_month'] ?? 0, 'Registered this month.', 'bi-person-plus', route('tenant.customers.index', ['created' => 'this_month']), 'new'],
        ['Member requests', $memberStats['member_requests'] ?? 0, 'Self-signups from the member website.', 'bi-person-check', route('tenant.customers.index', ['registration_source' => 'self_service']), 'request'],
        ['Pending KYC', $memberStats['pending_kyc'] ?? 0, 'Members still waiting for KYC approval.', 'bi-shield-exclamation', route('tenant.customers.index', ['kyc_status' => 'pending']), 'pending'],
    ];
@endphp

<section class="member-index-hero mb-4">
    <div class="member-index-copy">
        <span>Members desk</span>
        <h2>KYC, guarantors, status, and account numbers</h2>
        <p>Manage member records, self-service requests, account officer assignments, branch groups, KYC checks, and member account numbers from one cleaner workspace.</p>
        <div class="member-index-actions">
            @if(auth()->user()->hasPermission('customers.manage'))
                <a href="{{ route('tenant.customers.create') }}" class="btn btn-light"><i class="bi bi-person-plus me-1"></i> New member</a>
            @endif
            @if($activeFilters)
                <a href="{{ route('tenant.customers.index') }}" class="btn btn-outline-light"><i class="bi bi-x-circle me-1"></i> Clear filters</a>
            @endif
        </div>
    </div>
    <div class="member-stat-grid">
        @foreach($memberStatCards as [$label, $value, $hint, $icon, $url, $tone])
            <a href="{{ $url }}" class="member-stat-card {{ $tone }}">
                <i class="bi {{ $icon }}"></i>
                <span>{{ $label }}</span>
                <strong>{{ number_format($value) }}</strong>
                <small>{{ $hint }}</small>
            </a>
        @endforeach
    </div>
</section>

<section class="member-directory-card">
    <div class="member-directory-head">
        <div>
            <span>Directory</span>
            <h3>Find and update members quickly</h3>
        </div>
        <form class="customer-search-form" id="customerSearchForm" method="GET">
            @foreach($filterKeys as $filter)
                @if(request()->filled($filter))
                    <input type="hidden" name="{{ $filter }}" value="{{ request($filter) }}">
                @endif
            @endforeach
            <div class="input-group input-group-sm">
                <span class="input-group-text"><i class="bi bi-search"></i></span>
                <input name="search" value="{{ request('search') }}" class="form-control customer-search-input" placeholder="Search name, phone, account no." data-auto-filter>
            </div>
        </form>
    </div>

    <div class="member-filter-strip">
        <div class="member-filter-top">
            <div>
                <span>Smart filters</span>
                <strong>Refine the directory</strong>
            </div>
            @if($activeFilters)
                <a href="{{ route('tenant.customers.index') }}" class="btn btn-sm btn-light"><i class="bi bi-x-circle me-1"></i> Reset</a>
            @endif
        </div>
        <form class="customer-filter-form d-flex flex-wrap gap-2" id="customerFilterForm" method="GET">
            @if(request()->filled('search'))
                <input type="hidden" name="search" value="{{ request('search') }}">
            @endif
            <select name="status" class="form-select form-select-sm customer-filter-select" onchange="this.form.submit()">
                <option value="">All statuses</option>
                <option @selected(request('status') === 'active') value="active">Active</option>
                <option @selected(request('status') === 'inactive') value="inactive">Inactive</option>
                <option @selected(request('status') === 'suspended') value="suspended">Suspended</option>
            </select>
            <select name="kyc_status" class="form-select form-select-sm customer-filter-select" onchange="this.form.submit()">
                <option value="">All KYC</option>
                <option @selected(request('kyc_status') === 'pending') value="pending">Pending KYC</option>
                <option @selected(request('kyc_status') === 'verified') value="verified">Verified KYC</option>
                <option @selected(request('kyc_status') === 'rejected') value="rejected">Rejected KYC</option>
            </select>
            <select name="registration_source" class="form-select form-select-sm customer-filter-select" onchange="this.form.submit()">
                <option value="">All sources</option>
                <option @selected(request('registration_source') === 'staff') value="staff">Staff created</option>
                <option @selected(request('registration_source') === 'self_service') value="self_service">Member requests</option>
            </select>
            @if($showBranchField)
                <select name="branch_id" class="form-select form-select-sm customer-filter-select" onchange="this.form.submit()">
                    <option value="">All branches</option>
                    @foreach($branches as $branch)
                        <option value="{{ $branch->id }}" @selected((string) request('branch_id') === (string) $branch->id)>{{ $branch->name }}</option>
                    @endforeach
                </select>
            @endif
            <select name="account_officer_id" class="form-select form-select-sm customer-filter-select" onchange="this.form.submit()">
                <option value="">All officers</option>
                <option value="unassigned" @selected(request('account_officer_id') === 'unassigned')>Unassigned</option>
                @if($canAssignAccountOfficers)
                    @foreach($accountOfficers as $officer)
                        <option value="{{ $officer->id }}" @selected((string) request('account_officer_id') === (string) $officer->id)>{{ $officer->name }}</option>
                    @endforeach
                @else
                    <option value="{{ auth()->id() }}" @selected((string) request('account_officer_id') === (string) auth()->id())>My members</option>
                @endif
            </select>
            <select name="customer_group_id" class="form-select form-select-sm customer-filter-select" onchange="this.form.submit()">
                <option value="">All groups</option>
                @foreach($customerGroups as $group)
                    <option value="{{ $group->id }}" @selected((string) request('customer_group_id') === (string) $group->id)>{{ $group->name }}</option>
                @endforeach
            </select>
            @if($activeFilters)
                <a href="{{ route('tenant.customers.index') }}" class="btn btn-sm btn-outline-secondary">Clear</a>
            @endif
        </form>
        @if($activeFilterChips->isNotEmpty())
            <div class="member-active-filters">
                @foreach($activeFilterChips as $chip)
                    <span><i class="bi bi-funnel"></i> {{ $chip }}</span>
                @endforeach
            </div>
        @endif
    </div>

    <div class="member-directory-body">
        <div class="customer-bulk-panel member-action-panel">
            <div class="customer-bulk-header d-flex flex-wrap gap-2 justify-content-between align-items-center mb-3">
                <div class="member-action-title">
                    <span><i class="bi bi-sliders2"></i></span>
                    <div>
                        <div class="fw-semibold">Member actions</div>
                        <div class="small text-muted">Select records below, then apply branch, officer, group, status, or KYC updates.</div>
                    </div>
                </div>
                @if(auth()->user()->hasPermission('customers.manage'))
                    <div class="member-selected-pill"><span id="selectedCustomersCount">0</span> selected</div>
                @endif
            </div>

            @if(auth()->user()->hasPermission('customers.manage'))
                <form method="POST" action="{{ route('tenant.customers.bulk-update') }}" id="customerBulkForm">
                    @csrf
                    <div class="row g-2 align-items-end">
                        <div class="col-lg-3">
                            <label class="form-label">Bulk action</label>
                            <select name="bulk_action" id="customerBulkAction" class="form-select" required>
                                <option value="">Choose action</option>
                                @if($canAssignAccountOfficers)
                                    <option value="assign_account_officer">Assign account officer</option>
                                    <option value="remove_account_officer">Remove account officer</option>
                                @endif
                                @if($showBranchField)
                                    <option value="assign_branch">Assign branch</option>
                                    <option value="remove_branch">Reset to default branch</option>
                                @endif
                                <option value="assign_customer_group">Assign member group</option>
                                <option value="remove_customer_group">Remove member group</option>
                                <option value="set_status">Set member status</option>
                                <option value="set_kyc">Set KYC status</option>
                            </select>
                        </div>
                        @if($canAssignAccountOfficers)
                            <div class="col-lg-3 bulk-target d-none" data-bulk-target="assign_account_officer">
                                <label class="form-label">Account officer</label>
                                <select name="account_officer_id" class="form-select">
                                    <option value="">Select officer</option>
                                    @foreach($accountOfficers as $officer)
                                        <option value="{{ $officer->id }}">{{ $officer->name }} - {{ $officer->roleLabel() }}</option>
                                    @endforeach
                                </select>
                            </div>
                        @endif
                        @if($showBranchField)
                            <div class="col-lg-3 bulk-target d-none" data-bulk-target="assign_branch">
                                <label class="form-label">Branch</label>
                                <select name="branch_id" class="form-select">
                                    @foreach($branches as $branch)
                                        <option value="{{ $branch->id }}" @selected((string) ($defaultBranchId ?? '') === (string) $branch->id)>{{ $branch->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        @endif
                        <div class="col-lg-3 bulk-target d-none" data-bulk-target="assign_customer_group">
                            <label class="form-label">Member group</label>
                            <select name="customer_group_id" class="form-select">
                                <option value="">Select group</option>
                                @foreach($customerGroups as $group)
                                    <option value="{{ $group->id }}">{{ $group->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-3 bulk-target d-none" data-bulk-target="set_status">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="">Select status</option>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="suspended">Suspended</option>
                            </select>
                        </div>
                        <div class="col-lg-3 bulk-target d-none" data-bulk-target="set_kyc">
                            <label class="form-label">KYC</label>
                            <select name="kyc_status" class="form-select">
                                <option value="">Select KYC</option>
                                <option value="pending">Pending</option>
                                <option value="verified">Verified</option>
                                <option value="rejected">Rejected</option>
                            </select>
                        </div>
                        <div class="col-lg-3">
                            <button class="btn btn-primary w-100" id="customerBulkSubmit" disabled>
                                <i class="bi bi-check2-square me-1"></i> Apply to selected
                            </button>
                        </div>
                    </div>
                    <div class="member-action-note"><i class="bi bi-info-circle me-1"></i> Bulk changes only affect the members checked in the table below.</div>
                </form>
            @endif
        </div>

        <div class="table-responsive member-table-shell">
            <table class="table member-table">
                <thead><tr>@if(auth()->user()->hasPermission('customers.manage'))<th style="width:42px"><input class="form-check-input" type="checkbox" id="selectAllCustomers"></th>@endif<th>Photo</th><th>Account</th><th>Name</th><th>Group</th><th>Account Officer</th><th></th></tr></thead>
                <tbody>
                @forelse($customers as $customer)
                    @php($initials = strtoupper(substr((string) $customer->first_name, 0, 1).substr((string) $customer->last_name, 0, 1)))
                    <tr>
                        @if(auth()->user()->hasPermission('customers.manage'))
                            <td><input class="form-check-input customer-select" form="customerBulkForm" type="checkbox" name="customer_ids[]" value="{{ $customer->id }}"></td>
                        @endif
                        <td>
                            @if($customer->photo_path)
                                <a href="{{ asset('uploads/'.$customer->photo_path) }}" target="_blank" rel="noopener" class="member-photo-frame" title="View profile image">
                                    <img src="{{ asset('uploads/'.$customer->photo_path) }}" alt="{{ $customer->fullName() }}">
                                </a>
                            @else
                                <span class="member-photo-frame member-photo-placeholder">{{ $initials }}</span>
                            @endif
                        </td>
                        <td><span class="member-account-pill">{{ $customer->account_number }}</span></td>
                        <td>
                            <div class="member-name-cell">
                                <div>
                                    <div class="fw-semibold">{{ $customer->fullName() }}</div>
                                    <small class="member-subtext">
                                        <i class="bi bi-building"></i> {{ $customer->branch?->name ?? 'Head Office' }}
                                        @if($customer->registration_source === 'self_service')
                                            <span class="member-source-pill">Member request</span>
                                        @endif
                                    </small>
                                </div>
                            </div>
                        </td>
                        <td><span class="member-muted-line"><i class="bi bi-collection"></i> {{ $customer->customerGroup?->name ?? 'Ungrouped' }}</span></td>
                        <td><span class="member-muted-line"><i class="bi bi-person-badge"></i> {{ $customer->accountOfficer?->name ?? 'Unassigned' }}</span></td>
                        <td><a class="btn btn-sm btn-outline-primary" href="{{ route('tenant.customers.show', $customer) }}">Open</a></td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="{{ auth()->user()->hasPermission('customers.manage') ? 7 : 6 }}" class="text-center text-muted py-5">
                            No members match the current filters.
                        </td>
                    </tr>
                @endforelse
                </tbody>
            </table>
        </div>
        {{ $customers->links() }}
    </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const searchForm = document.getElementById('customerSearchForm');
    const searchInput = searchForm?.querySelector('[data-auto-filter]');
    const action = document.getElementById('customerBulkAction');
    const targets = document.querySelectorAll('[data-bulk-target]');
    const selectAll = document.getElementById('selectAllCustomers');
    const checkboxes = document.querySelectorAll('.customer-select');
    const submit = document.getElementById('customerBulkSubmit');
    const selectedCount = document.getElementById('selectedCustomersCount');

    const updateTargets = () => {
        targets.forEach((target) => {
            target.classList.toggle('d-none', target.dataset.bulkTarget !== action?.value);
        });
    };

    const updateSelection = () => {
        const count = Array.from(checkboxes).filter((checkbox) => checkbox.checked).length;
        if (selectedCount) selectedCount.textContent = count;
        if (submit) submit.disabled = count === 0 || ! action?.value;
        if (selectAll) selectAll.checked = count > 0 && count === checkboxes.length;
    };

    action?.addEventListener('change', () => {
        updateTargets();
        updateSelection();
    });

    selectAll?.addEventListener('change', () => {
        checkboxes.forEach((checkbox) => {
            checkbox.checked = selectAll.checked;
        });
        updateSelection();
    });

    checkboxes.forEach((checkbox) => checkbox.addEventListener('change', updateSelection));

    let searchTimer = null;
    searchInput?.addEventListener('input', () => {
        window.clearTimeout(searchTimer);
        searchTimer = window.setTimeout(() => searchForm.submit(), 450);
    });

    updateTargets();
    updateSelection();
});
</script>
@endsection
