@extends('backoffice.layouts.app')

@section('title', ' CRM')

@section('content')
<div class="container-fluid crm-page">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
                <div>
                    <h2 class="mb-1 d-flex align-items-center gap-2">
                        <i class="bi bi-person-lines-fill"></i>
                        <span> CRM</span>
                    </h2>
                    <p class="text-muted mb-0">Oyuncu detaylarını hızlı inceleyin.</p>
                </div>

            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form method="GET" action="{{ route('backoffice.crm.index') }}">
                <div class="row g-3 align-items-end">
                    <div class="col-lg-8">
                        <label class="form-label">Oyuncu Ara</label>
                        <input
                            type="text"
                            id="crmSearchInput"
                            name="q"
                            class="form-control"
                            value="{{ $search }}"
                            placeholder="Üye Adı"
                            autocomplete="off"
                        >
                    </div>
                    <div class="col-lg-4">
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary flex-fill">
                                <i class="bi bi-search me-1"></i>Ara
                            </button>
                            <a href="{{ route('backoffice.crm.index') }}" class="btn btn-light border flex-fill">
                                <i class="bi bi-arrow-counterclockwise me-1"></i>Temizle
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    @if($search !== '')
        <div class="row g-4">
            <div class="col-xxl-4 col-xl-5">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Eşleşen Profiller</h5>
                        <span class="badge bg-light text-dark border">{{ $profiles->count() }}</span>
                    </div>
                    <div class="card-body p-0">
                        @if($profiles->isEmpty())
                            <div class="p-4 text-muted">Eşleşen profil bulunamadı.</div>
                        @else
                            <div class="crm-profile-list">
                                @foreach($profiles as $profile)
                                    @php
                                        $isActive = (string) request('profile_type') === (string) $profile['selector_type']
                                            && (string) request('profile_value') === (string) $profile['selector_value'];
                                    @endphp
                                    <a
                                        href="{{ route('backoffice.crm.index', ['q' => $search, 'profile_type' => $profile['selector_type'], 'profile_value' => $profile['selector_value']]) }}"
                                        class="crm-profile-card {{ $isActive ? 'is-active' : '' }}"
                                    >
                                        <div class="d-flex justify-content-between align-items-start gap-3">
                                            <div>
                                                <div class="fw-semibold">{{ $profile['display_name'] }}</div>
                                                @if(!empty($profile['names']) && $profile['display_name'] !== ($profile['names'][0] ?? null))
                                                    <div class="small text-muted">{{ $profile['names'][0] }}</div>
                                                @endif
                                            </div>
                                            <span class="badge bg-dark-subtle text-dark-emphasis">{{ $profile['transactions_count'] }}</span>
                                        </div>
                                        @if(!empty($profile['account_holders']))
                                            <div class="small text-muted mt-2">Hesap Adı: {{ collect($profile['account_holders'])->take(2)->implode(', ') }}</div>
                                        @endif
                                        <div class="crm-profile-stats">
                                            <span class="crm-stat-chip success">Y: {{ number_format($profile['deposit_total'], 2, ',', '.') }}</span>
                                            <span class="crm-stat-chip danger">Ç: {{ number_format($profile['withdrawal_total'], 2, ',', '.') }}</span>
                                            <span class="crm-stat-chip neutral">Auto: {{ $profile['auto_transactions_count'] }}</span>
                                        </div>
                                    </a>
                                @endforeach
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            <div class="col-xxl-8 col-xl-7">
                @if(empty($profileDetails))
                    <div class="card border-0 shadow-sm h-100">
                        <div class="card-body d-flex align-items-center justify-content-center text-center text-muted min-vh-25">
                            Soldan bir profil seçerek detayları görüntüleyin.
                        </div>
                    </div>
                @else
                    <div class="d-grid gap-4">
                        <div class="card border-0 shadow-sm">
                            <div class="card-header bg-white d-flex justify-content-between align-items-start flex-wrap gap-3">
                                <div>
                                    <h5 class="mb-1">{{ $profileDetails['display_name'] }}</h5>
                                    <div class="small text-muted">
                                        @if($profileDetails['customer_player_ids']->isNotEmpty())
                                            Oyuncu ID: {{ $profileDetails['customer_player_ids']->implode(', ') }}
                                        @else
                                            Profil: {{ $profileDetails['selector_value'] }}
                                        @endif
                                    </div>
                                </div>
                                <div class="small text-muted text-end">
                                    <div>İlk işlem: {{ optional($profileDetails['first_transaction_at'])->format('d.m.Y H:i') ?: '-' }}</div>
                                    <div>Son işlem: {{ optional($profileDetails['last_transaction_at'])->format('d.m.Y H:i') ?: '-' }}</div>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row g-3 crm-summary-grid">
                                    <div class="col-md-6 col-xl-3">
                                        <div class="crm-summary-card">
                                            <div class="crm-summary-label">Toplam İşlem</div>
                                            <div class="crm-summary-value">{{ $profileDetails['total_transactions'] }}</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6 col-xl-3">
                                        <div class="crm-summary-card success">
                                            <div class="crm-summary-label">Toplam Yatırım</div>
                                            <div class="crm-summary-value">{{ number_format($profileDetails['deposit_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</div>
                                            <div class="crm-summary-sub">{{ $profileDetails['deposit_count'] }} işlem</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6 col-xl-3">
                                        <div class="crm-summary-card danger">
                                            <div class="crm-summary-label">Toplam Çekim</div>
                                            <div class="crm-summary-value">{{ number_format($profileDetails['withdrawal_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</div>
                                            <div class="crm-summary-sub">{{ $profileDetails['withdrawal_count'] }} işlem</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6 col-xl-3">
                                        <div class="crm-summary-card neutral">
                                            <div class="crm-summary-label">Auto / Bekleyen</div>
                                            <div class="crm-summary-value">{{ $profileDetails['total_auto_transactions'] }} / {{ $profileDetails['pending_count'] }}</div>
                                            <div class="crm-summary-sub">Onaylı toplam: {{ number_format($profileDetails['approved_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                        <div class="row g-4">
                            <div class="col-xl-7">
                                <div class="card border-0 shadow-sm h-100">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0">Son Auto İşlemler</h5>
                                    </div>
                                    <div class="card-body p-0">
                                        <div class="table-responsive">
                                            <table class="table table-sm align-middle mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Tarih</th>
                                                        <th>Tip</th>
                                                        <th>Durum</th>
                                                        <th>Tutar</th>
                                                        <th>Site</th>
                                                        <th>Finans</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @forelse($profileDetails['recent_auto_transactions'] as $transaction)
                                                        <tr>
                                                            <td>{{ optional($transaction->created_at)->format('d.m.Y H:i') }}</td>
                                                            <td>{{ $transaction->type === 'deposit' ? 'Yatırım' : 'Çekim' }}</td>
                                                            <td>{{ $transaction->status }}</td>
                                                            <td>{{ number_format((float) $transaction->amount, 2, ',', '.') }} {{ $transaction->currency }}</td>
                                                            <td>{{ $transaction->site?->name ?? '-' }}</td>
                                                            <td>{{ $transaction->financeGroup?->name ?? '-' }}</td>
                                                        </tr>
                                                    @empty
                                                        <tr>
                                                            <td colspan="6" class="text-center text-muted py-4">Auto işlem bulunmuyor.</td>
                                                        </tr>
                                                    @endforelse
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-5">
                                <div class="card border-0 shadow-sm h-100">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0">IP Adresleri</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="crm-ip-list">
                                            @forelse($profileDetails['ip_breakdown'] as $ip)
                                                <div class="crm-ip-item">
                                                    <div class="d-flex justify-content-between gap-3">
                                                        <div class="fw-semibold">{{ $ip['ip_address'] }}</div>
                                                        <span class="badge bg-light text-dark border">{{ $ip['count'] }}</span>
                                                    </div>
                                                </div>
                                            @empty
                                                <div class="text-muted">IP kaydı bulunmuyor.</div>
                                            @endforelse
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row g-4">
                            <div class="col-xl-6">
                                <div class="card border-0 shadow-sm h-100">
                                    <div class="card-header bg-white"><h5 class="mb-0">Site Dağılımı</h5></div>
                                    <div class="card-body">
                                        <div class="crm-tag-stack">
                                            @forelse($profileDetails['site_breakdown'] as $site)
                                                <div class="crm-stack-row">
                                                    <div>
                                                        <div class="fw-semibold">{{ $site['name'] }}</div>
                                                        <small class="text-muted">{{ $site['count'] }} işlem</small>
                                                    </div>
                                                    <span>{{ number_format($site['amount'], 2, ',', '.') }}</span>
                                                </div>
                                            @empty
                                                <div class="text-muted">Site verisi bulunmuyor.</div>
                                            @endforelse
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xl-6">
                                <div class="card border-0 shadow-sm h-100">
                                    <div class="card-header bg-white"><h5 class="mb-0">Finans Grupları</h5></div>
                                    <div class="card-body">
                                        <div class="crm-tag-stack">
                                            @forelse($profileDetails['finance_group_breakdown'] as $group)
                                                <div class="crm-stack-row">
                                                    <div>
                                                        <div class="fw-semibold">{{ $group['name'] }}</div>
                                                        <small class="text-muted">{{ $group['count'] }} işlem</small>
                                                    </div>
                                                    <span>{{ number_format($group['amount'], 2, ',', '.') }}</span>
                                                </div>
                                            @empty
                                                <div class="text-muted">Finans grup verisi bulunmuyor.</div>
                                            @endforelse
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endif
            </div>
        </div>
    @endif
</div>
@endsection

@push('styles')
<style>
    #crmSearchInput {
        text-transform: uppercase;
    }
    .crm-profile-list {
        display: grid;
        gap: 1px;
        background: #eef2f7;
    }
    .crm-profile-card {
        display: block;
        padding: 1rem 1.1rem;
        background: #fff;
        color: inherit;
        text-decoration: none;
        transition: background 0.15s ease, border-color 0.15s ease;
        border-left: 3px solid transparent;
    }
    .crm-profile-card:hover {
        background: #f8fbff;
        border-left-color: #0d6efd;
    }
    .crm-profile-card.is-active {
        background: #eef6ff;
        border-left-color: #0d6efd;
    }
    .crm-profile-stats {
        display: flex;
        flex-wrap: wrap;
        gap: 0.45rem;
        margin-top: 0.85rem;
    }
    .crm-stat-chip,
    .crm-tag {
        display: inline-flex;
        align-items: center;
        border-radius: 999px;
        padding: 0.28rem 0.65rem;
        font-size: 0.78rem;
        font-weight: 600;
    }
    .crm-stat-chip.success,
    .crm-tag {
        background: #e8f7ef;
        color: #166534;
    }
    .crm-stat-chip.danger {
        background: #fdecec;
        color: #b91c1c;
    }
    .crm-stat-chip.neutral,
    .crm-tag.crm-tag-alt {
        background: #eef2f7;
        color: #334155;
    }
    .crm-summary-card {
        height: 100%;
        border: 1px solid #e5e7eb;
        border-radius: 14px;
        padding: 1rem;
        background: #fff;
    }
    .crm-summary-card.success {
        background: linear-gradient(180deg, #f5fff8 0%, #ecfdf3 100%);
    }
    .crm-summary-card.danger {
        background: linear-gradient(180deg, #fff8f8 0%, #fff1f1 100%);
    }
    .crm-summary-card.neutral {
        background: linear-gradient(180deg, #fafcff 0%, #f3f7fb 100%);
    }
    .crm-summary-label {
        font-size: 0.82rem;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        color: #64748b;
        margin-bottom: 0.35rem;
    }
    .crm-summary-value {
        font-size: 1.2rem;
        font-weight: 700;
        color: #0f172a;
    }
    .crm-summary-sub {
        margin-top: 0.25rem;
        font-size: 0.82rem;
        color: #64748b;
    }
    .crm-detail-block {
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        padding: 1rem;
        background: #fff;
        height: 100%;
    }
    .crm-tag-list {
        display: flex;
        flex-wrap: wrap;
        gap: 0.45rem;
    }
    .crm-ip-list,
    .crm-tag-stack {
        display: grid;
        gap: 0.75rem;
    }
    .crm-ip-item,
    .crm-stack-row {
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        padding: 0.8rem 0.9rem;
        background: #fff;
    }
    .crm-stack-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
    }
    .min-vh-25 {
        min-height: 25vh;
    }
</style>
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('crmSearchInput');
    if (!searchInput) {
        return;
    }

    function normalizeCrmSearchValue(value) {
        return String(value || '')
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^A-Za-z\s]/g, '')
            .replace(/\s+/g, ' ')
            .trimStart()
            .toUpperCase();
    }

    function syncSearchValue() {
        const normalized = normalizeCrmSearchValue(searchInput.value);
        if (searchInput.value !== normalized) {
            const end = normalized.length;
            searchInput.value = normalized;
            searchInput.setSelectionRange(end, end);
        }
    }

    searchInput.addEventListener('input', syncSearchValue);
    searchInput.addEventListener('paste', function () {
        requestAnimationFrame(syncSearchValue);
    });
    syncSearchValue();
});
</script>
@endpush