@extends('layouts.admin')

@section('title', 'Leads')

@section('content')
    @php
        $pointName = site_setting('points_name', config('rewards.points_name'));
        $activeFilters = collect(request()->only(['search', 'status', 'type', 'provider', 'date_from', 'date_to']))->filter();
    @endphp

    <div class="d-flex flex-wrap justify-content-between align-items-center gap-1 mb-2">
        <div>
            <span class="loot-status success">Postback center</span>
            <h1 class="loot-section-title mt-1 mb-25">Leads</h1>
            <p class="loot-muted mb-0">Track offerwall conversions, review suspicious rewards, and export filtered records.</p>
        </div>
        <a class="btn btn-loot" href="{{ route('admin.leads.export', request()->query()) }}">
            <i data-feather="download" class="me-50"></i> Export CSV
        </a>
    </div>

    @if(session('success'))
        <div class="alert alert-success"><div class="alert-body">{{ session('success') }}</div></div>
    @endif
    @if($errors->any())
        <div class="alert alert-danger"><div class="alert-body">{{ $errors->first() }}</div></div>
    @endif

    <div class="loot-admin-grid mb-2">
        <div class="loot-admin-card">
            <span>Total leads</span>
            <strong>{{ number_format($stats['total']) }}</strong>
        </div>
        <div class="loot-admin-card">
            <span>Approved</span>
            <strong>{{ number_format($stats['approved']) }}</strong>
        </div>
        <div class="loot-admin-card">
            <span>Held review</span>
            <strong>{{ number_format($stats['held']) }}</strong>
        </div>
        <div class="loot-admin-card">
            <span>Payout</span>
            <strong>${{ number_format($stats['payout'], 2) }}</strong>
        </div>
    </div>

    <section class="user-page-card admin-leads-shell">
        <form method="GET" action="{{ route('admin.leads') }}" class="admin-leads-filters">
            <div class="admin-filter-search">
                <i data-feather="search"></i>
                <input type="search" name="search" class="form-control" value="{{ request('search') }}"
                       placeholder="Search user, email, offer, trx, ip">
            </div>
            <select name="status" class="form-select">
                <option value="">All statuses</option>
                @foreach(['approved' => 'Approved', 'held' => 'Held', 'rejected' => 'Rejected', 'chargeback' => 'Chargeback'] as $value => $label)
                    <option value="{{ $value }}" {{ request('status') === $value ? 'selected' : '' }}>{{ $label }}</option>
                @endforeach
            </select>
            <select name="type" class="form-select">
                <option value="">All types</option>
                @foreach(['offer' => 'Offer', 'survey' => 'Survey', 'reward' => 'Reward', 'bonus' => 'Bonus'] as $value => $label)
                    <option value="{{ $value }}" {{ request('type') === $value ? 'selected' : '' }}>{{ $label }}</option>
                @endforeach
            </select>
            <select name="provider" class="form-select">
                <option value="">All providers</option>
                @foreach($providers as $provider)
                    <option value="{{ $provider }}" {{ request('provider') === $provider ? 'selected' : '' }}>{{ $provider }}</option>
                @endforeach
            </select>
            <input type="date" name="date_from" class="form-control" value="{{ request('date_from') }}">
            <input type="date" name="date_to" class="form-control" value="{{ request('date_to') }}">
            <select name="per_page" class="form-select">
                @foreach([15, 25, 50, 100] as $size)
                    <option value="{{ $size }}" {{ (int) request('per_page', 15) === $size ? 'selected' : '' }}>{{ $size }} / page</option>
                @endforeach
            </select>
            <button class="btn btn-loot" type="submit">Apply</button>
            <a href="{{ route('admin.leads') }}" class="btn btn-outline-light">Reset</a>
        </form>

        @if($activeFilters->count())
            <div class="admin-active-filters">
                <strong>Active filters</strong>
                @foreach($activeFilters as $key => $value)
                    <span>{{ Str::headline($key) }}: {{ $value }}</span>
                @endforeach
            </div>
        @endif

        <div class="admin-leads-toolbar">
            <form method="POST" action="{{ route('admin.leads.bulk', request()->query()) }}" id="bulkLeadForm" class="d-flex flex-wrap gap-1 align-items-center">
                @csrf
                <div id="bulkLeadIds"></div>
                <select name="action" class="form-select" required>
                    <option value="">Bulk action</option>
                    <option value="approve">Approve selected</option>
                    <option value="hold">Hold for review</option>
                    <option value="reject">Reject and reverse points</option>
                    <option value="chargeback">Charge back all credited points</option>
                </select>
                <button type="submit" class="btn btn-outline-light">Apply to selected</button>
                <span class="loot-muted" id="selectedLeadCount">0 selected</span>
            </form>
        </div>

        <div class="table-responsive admin-leads-table-wrap">
            <table class="table admin-leads-table mb-0">
                <thead>
                <tr>
                    <th><input type="checkbox" class="form-check-input" id="selectAllLeads"></th>
                    <th>User</th>
                    <th>Lead</th>
                    <th>Type</th>
                    <th>Status</th>
                    <th>{{ ucfirst($pointName) }}</th>
                    <th>Payout</th>
                    <th>IP</th>
                    <th>Date</th>
                    <th></th>
                </tr>
                </thead>
                <tbody>
                @forelse($leads as $lead)
                    @php
                        $statusClass = $lead->status === 'approved' ? 'success' : ($lead->status === 'held' ? 'warning' : 'danger');
                    @endphp
                    <tr>
                        <td><input type="checkbox" class="form-check-input lead-select" value="{{ $lead->id }}"></td>
                        <td>
                            <div class="d-flex align-items-center gap-1">
                                <img src="{{ optional($lead->user)->avatar() }}" class="rounded-circle" alt="{{ optional($lead->user)->username }}" width="38" height="38">
                                <div>
                                    <a class="admin-lead-user" href="{{ $lead->user ? route('admin.users.view', $lead->user_id) : '#' }}">
                                        {{ optional($lead->user)->username ?? 'Deleted user' }}
                                    </a>
                                    <div class="loot-muted small">{{ optional($lead->user)->email ?? 'No email' }}</div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <strong>{{ html_entity_decode($lead->offer_name ?: 'Offer completed') }}</strong>
                            <div class="loot-muted small">
                                {{ $lead->company }} @if($lead->offer_id) / {{ $lead->offer_id }} @endif
                            </div>
                            @if($lead->trx)
                                <div class="loot-muted small">TRX {{ $lead->trx }}</div>
                            @endif
                        </td>
                        <td><span class="loot-status">{{ ucfirst($lead->type ?: 'offer') }}</span></td>
                        <td>
                            <span class="loot-status {{ $statusClass }}">{{ ucfirst($lead->status ?: 'approved') }}</span>
                            @if($lead->points_reversed_at)
                                <div class="loot-muted small">No coins currently credited</div>
                            @endif
                        </td>
                        <td>
                            <strong>{{ format_coins_as_usd($lead->credited_points) }}</strong>
                            <small class="d-block loot-muted">{{ number_format((float) $lead->credited_points) }} / {{ number_format((float) ($lead->original_points ?? $lead->points)) }} coins credited</small>
                        </td>
                        <td>${{ number_format((float) $lead->payout, 2) }}</td>
                        <td>
                            <span>{{ $lead->ip ?: 'N/A' }}</span>
                            @if($lead->country)
                                <div class="loot-muted small">{{ $lead->country }}</div>
                            @endif
                        </td>
                        <td>
                            {{ $lead->created_at->format('M d, Y') }}
                            <div class="loot-muted small">{{ $lead->created_at->diffForHumans() }}</div>
                        </td>
                        <td class="text-end">
                            <button class="btn btn-sm btn-outline-light" type="button" data-bs-toggle="modal" data-bs-target="#leadModal{{ $lead->id }}">
                                Review
                            </button>
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="10" class="text-center py-4">
                            <h4 class="loot-section-title">No leads found</h4>
                            <p class="loot-muted mb-0">Try changing filters or wait for offerwall postbacks.</p>
                        </td>
                    </tr>
                @endforelse
                </tbody>
            </table>
        </div>

        <div class="d-flex flex-wrap justify-content-between align-items-center gap-1 mt-2">
            <span class="loot-muted">Showing {{ $leads->firstItem() ?? 0 }} to {{ $leads->lastItem() ?? 0 }} of {{ number_format($leads->total()) }} leads</span>
            {{ $leads->onEachSide(1)->links() }}
        </div>
    </section>

    @foreach($leads as $lead)
        <div class="modal fade" id="leadModal{{ $lead->id }}" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <form method="POST" action="{{ route('admin.leads.update', array_merge(['lead' => $lead->id], request()->query())) }}" class="modal-content">
                    @csrf
                    @method('PATCH')
                    <input type="hidden" name="adjustment_token" value="{{ (string) Str::uuid() }}">
                    <div class="modal-header">
                        <div>
                            <h4 class="modal-title loot-section-title">Review lead #{{ $lead->id }}</h4>
                            <p class="loot-muted mb-0">{{ $lead->company }} / {{ html_entity_decode($lead->offer_name ?: 'Offer completed') }}</p>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="loot-action-grid mb-2">
                            <div class="loot-stat-card">
                                <span>User</span>
                                <strong>{{ optional($lead->user)->username ?? 'Deleted' }}</strong>
                                <p class="loot-muted mb-0">{{ optional($lead->user)->email }}</p>
                            </div>
                            <div class="loot-stat-card">
                                <span>Credited reward</span>
                                <strong>{{ format_coins_as_usd($lead->credited_points) }}</strong>
                                <small class="d-block loot-muted">{{ number_format((float) $lead->credited_points, 2) }} coins credited</small>
                                <p class="loot-muted mb-0">Original: {{ number_format((float) ($lead->original_points ?? $lead->points), 2) }} coins</p>
                            </div>
                            <div class="loot-stat-card">
                                <span>Payout</span>
                                <strong>${{ number_format((float) $lead->payout, 2) }}</strong>
                                <p class="loot-muted mb-0">{{ $lead->ip ?: 'No IP' }}</p>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-1">
                                <label class="form-label">Status</label>
                                <select name="status" class="form-select">
                                    @foreach(['approved' => 'Approved', 'held' => 'Held for review', 'rejected' => 'Rejected', 'chargeback' => 'Chargeback'] as $value => $label)
                                        <option value="{{ $value }}" {{ ($lead->status ?: 'approved') === $value ? 'selected' : '' }}>{{ $label }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-4 mb-1">
                                <label class="form-label">Type</label>
                                <select name="type" class="form-select">
                                    @foreach(['offer' => 'Offer', 'survey' => 'Survey', 'reward' => 'Reward', 'bonus' => 'Bonus'] as $value => $label)
                                        <option value="{{ $value }}" {{ ($lead->type ?: 'offer') === $value ? 'selected' : '' }}>{{ $label }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-4 mb-1">
                                <label class="form-label">Reverse points on reject</label>
                                <div class="form-check form-switch mt-50">
                                    <input class="form-check-input" type="checkbox" name="reverse_points" value="1" id="reverse{{ $lead->id }}" {{ (float) $lead->credited_points > 0 ? 'checked' : '' }}>
                                    <label class="form-check-label" for="reverse{{ $lead->id }}">Enabled</label>
                                </div>
                            </div>
                            <div class="col-md-4 mb-1">
                                <label class="form-label">Balance action</label>
                                <select name="balance_action" class="form-select lead-balance-action">
                                    <option value="none">No separate adjustment</option>
                                    <option value="release">Release partial reward</option>
                                    <option value="chargeback">Charge back reward</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-1">
                                <label class="form-label">Amount</label>
                                <input type="number" name="adjustment_amount" class="form-control" min="0.0001" step="0.0001" placeholder="Blank = full chargeback">
                            </div>
                            <div class="col-md-4 mb-1">
                                <label class="form-label">Amount unit</label>
                                <select name="adjustment_unit" class="form-select">
                                    <option value="coins">Coins</option>
                                    <option value="usd">USD (converted to coins)</option>
                                </select>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Admin note</label>
                                <textarea name="admin_note" class="form-control" rows="3" placeholder="Add fraud notes, provider ticket ID, or review context">{{ $lead->admin_note }}</textarea>
                            </div>
                            <div class="col-12 mt-1">
                                <small class="loot-muted">A partial release remains Held so the remaining balance can be released later. Fully released leads become Approved; zero-balance reversals become Chargebacks. Adjustments also update referral commission.</small>
                            </div>
                            @if($lead->adjustments->isNotEmpty())
                                <div class="col-12 mt-1">
                                    <label class="form-label">Balance audit trail</label>
                                    <div class="table-responsive">
                                        <table class="table table-sm mb-0">
                                            <thead><tr><th>Time</th><th>Action</th><th>Change</th><th>Credited after</th><th>Admin</th></tr></thead>
                                            <tbody>
                                            @foreach($lead->adjustments as $adjustment)
                                                <tr>
                                                    <td>{{ $adjustment->created_at->format('M d, Y H:i') }}</td>
                                                    <td>{{ Str::headline($adjustment->action) }}</td>
                                                    <td>{{ $adjustment->points > 0 ? '+' : '' }}{{ number_format($adjustment->points, 2) }}</td>
                                                    <td>{{ number_format($adjustment->credited_after, 2) }}</td>
                                                    <td>{{ optional($adjustment->admin)->username ?? 'System' }}</td>
                                                </tr>
                                            @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            @endif
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-loot">Save review</button>
                    </div>
                </form>
            </div>
        </div>
    @endforeach

    <section class="user-page-card mt-2" id="lead-rules">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-1 mb-1">
            <div>
                <h3 class="loot-section-title mb-25"><i data-feather="filter" class="me-50"></i>Auto-approve rules</h3>
                <p class="loot-muted mb-0">Automatically approve, hold, or reject incoming leads that match a provider/offer/user filter. Rules run top to bottom; the first match wins.</p>
            </div>
            <form method="POST" action="{{ route('admin.leads.default-status') }}" class="d-flex align-items-center gap-1">
                @csrf
                <label class="loot-muted mb-0">Default for non-matching leads</label>
                <select name="leads_default_status" class="form-select" style="max-width:160px;">
                    <option value="approved" {{ $defaultStatus === 'approved' ? 'selected' : '' }}>Approve</option>
                    <option value="hold" {{ $defaultStatus === 'hold' ? 'selected' : '' }}>Hold for review</option>
                </select>
                <label class="loot-muted mb-0" title="Held leads are approved automatically after this many hours. 0 disables auto-approval.">Auto-approve held after</label>
                <div class="input-group" style="max-width:130px;">
                    <input type="number" name="leads_auto_approve_hours" class="form-control" min="0" max="720"
                           value="{{ site_int('leads_auto_approve_hours', 0) }}">
                    <span class="input-group-text">h</span>
                </div>
                <button class="btn btn-outline-light">Save</button>
            </form>
        </div>

        <form method="POST" action="{{ route('admin.leads.rules.store') }}" class="admin-leads-filters mb-1">
            @csrf
            <select name="match_field" class="form-select">
                <option value="company">Provider/Company</option>
                <option value="offer_name">Offer name</option>
                <option value="offer_id">Offer ID / code</option>
                <option value="user_id">User ID</option>
                <option value="country">Country code</option>
                <option value="trx">Transaction ID</option>
                <option value="points">Reward coins</option>
                <option value="payout">Provider payout USD</option>
            </select>
            <select name="match_operator" class="form-select">
                <option value="equals">equals</option>
                <option value="contains">contains</option>
                <option value="greater_than">is greater than</option>
                <option value="greater_than_or_equal">is at least</option>
                <option value="less_than">is less than</option>
                <option value="less_than_or_equal">is at most</option>
            </select>
            <input name="match_value" class="form-control" placeholder="Value (e.g. Adgem, US, 12345)" required>
            <select name="action" class="form-select">
                <option value="approve">Auto-approve</option>
                <option value="hold">Hold for review</option>
                <option value="reject">Auto-reject (reverse points)</option>
            </select>
            <button class="btn btn-loot">Add rule</button>
        </form>

        <div class="table-responsive admin-leads-table-wrap">
            <table class="table admin-leads-table mb-0">
                <thead><tr><th>When</th><th>Then</th><th>Status</th><th></th></tr></thead>
                <tbody>
                    @forelse($rules as $rule)
                        <tr>
                            <td><code>{{ $rule->match_field }}</code> {{ $rule->match_operator }} <strong>{{ $rule->match_value }}</strong></td>
                            <td>
                                @php $badge = ['approve'=>'success','hold'=>'warning','reject'=>'danger'][$rule->action]; @endphp
                                <span class="badge badge-light-{{ $badge }}">{{ ucfirst($rule->action) }}</span>
                            </td>
                            <td>
                                <form method="POST" action="{{ route('admin.leads.rules.toggle', $rule) }}" class="d-inline">
                                    @csrf
                                    <button class="btn btn-sm {{ $rule->is_active ? 'btn-outline-success' : 'btn-outline-secondary' }}">
                                        {{ $rule->is_active ? 'Active' : 'Paused' }}
                                    </button>
                                </form>
                            </td>
                            <td>
                                <form method="POST" action="{{ route('admin.leads.rules.destroy', $rule) }}" class="d-inline" onsubmit="return confirm('Delete this rule?')">
                                    @csrf @method('DELETE')
                                    <button class="btn btn-sm btn-outline-danger">Delete</button>
                                </form>
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="4" class="text-center loot-muted py-3">No rules yet — new leads use the default status above.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </section>
@endsection

@push('scripts')
    <script>
        const selectAllLeads = document.getElementById('selectAllLeads');
        const leadCheckboxes = Array.from(document.querySelectorAll('.lead-select'));
        const selectedLeadCount = document.getElementById('selectedLeadCount');
        const bulkLeadIds = document.getElementById('bulkLeadIds');
        const bulkLeadForm = document.getElementById('bulkLeadForm');

        function syncBulkLeadState() {
            const selected = leadCheckboxes.filter((checkbox) => checkbox.checked).map((checkbox) => checkbox.value);
            selectedLeadCount.textContent = `${selected.length} selected`;
            bulkLeadIds.innerHTML = selected.map((id) => `<input type="hidden" name="ids[]" value="${id}">`).join('');
            if (selectAllLeads) {
                selectAllLeads.checked = selected.length && selected.length === leadCheckboxes.length;
            }
        }

        selectAllLeads?.addEventListener('change', function () {
            leadCheckboxes.forEach((checkbox) => checkbox.checked = this.checked);
            syncBulkLeadState();
        });

        leadCheckboxes.forEach((checkbox) => checkbox.addEventListener('change', syncBulkLeadState));

        bulkLeadForm?.addEventListener('submit', function (event) {
            syncBulkLeadState();
            if (!bulkLeadIds.children.length) {
                event.preventDefault();
                alert('Select at least one lead first.');
            }
        });
    </script>
@endpush
