@extends('layouts.admin')

@section('title', 'Provider Offers')

@section('content')
    <div class="d-flex flex-wrap justify-content-between align-items-end gap-1 mb-2">
        <div>
            <span class="loot-pill mb-1"><i data-feather="target"></i> Offer marketplace</span>
            <h1 class="loot-section-title mb-25">Provider Offers</h1>
            <p class="loot-muted mb-0">Sync real provider feed offers, then control which offers appear on the website.</p>
        </div>
        <div class="d-flex flex-wrap gap-1">
            <form method="POST" action="{{ route('admin.provider-offers.sync') }}">
                @csrf
                <button class="btn btn-loot"><i data-feather="refresh-cw" class="me-50"></i>Check & sync all</button>
            </form>
            <form method="POST" action="{{ route('admin.provider-offers.curate') }}">
                @csrf
                <button class="btn btn-outline-light"><i data-feather="trending-up" class="me-50"></i>Curate now</button>
            </form>
            <a class="btn btn-outline-light" href="{{ route('admin.activity') }}">
                <i data-feather="activity" class="me-50"></i>View activity
            </a>
        </div>
    </div>

    <div class="loot-admin-grid mb-2">
        <div class="loot-admin-card"><span>Total offers</span><strong>{{ number_format($stats['total']) }}</strong></div>
        <div class="loot-admin-card"><span>Allowed when live</span><strong>{{ number_format($stats['active']) }}</strong></div>
        <div class="loot-admin-card"><span>Hidden</span><strong>{{ number_format($stats['hidden']) }}</strong></div>
        <div class="loot-admin-card"><span>Hot</span><strong>{{ number_format($stats['hot']) }}</strong></div>
        <div class="loot-admin-card"><span>Live from API</span><strong>{{ number_format($stats['live']) }}</strong></div>
    </div>

    <section class="user-page-card">
        @if(session('status'))
            <div class="alert alert-success">{{ session('status') }}</div>
        @endif

        <form method="GET" class="admin-leads-filters">
            <div class="admin-filter-search">
                <i data-feather="search"></i>
                <input class="form-control" name="search" value="{{ request('search') }}" placeholder="Search offer, provider, external ID">
            </div>
            <select name="offerwall_id" class="form-select">
                <option value="">All providers</option>
                @foreach($offerwalls as $offerwall)
                    <option value="{{ $offerwall->id }}" {{ (string) request('offerwall_id') === (string) $offerwall->id ? 'selected' : '' }}>{{ $offerwall->name }}</option>
                @endforeach
            </select>
            <select name="category" class="form-select">
                <option value="">All categories</option>
                @foreach(['games','other','surveys','partners'] as $category)
                    <option value="{{ $category }}" {{ request('category') === $category ? 'selected' : '' }}>{{ ucfirst($category) }}</option>
                @endforeach
            </select>
            <select name="status" class="form-select">
                <option value="">All visibility</option>
                <option value="active" {{ request('status') === 'active' ? 'selected' : '' }}>Visible</option>
                <option value="hidden" {{ request('status') === 'hidden' ? 'selected' : '' }}>Hidden</option>
            </select>
            <button class="btn btn-loot">Apply</button>
            <a class="btn btn-outline-light" href="{{ route('admin.provider-offers') }}">Reset</a>
        </form>

        <div class="loot-feed-status-grid mb-2">
            @foreach($offerwalls as $offerwall)
                @php
                    $feed = $feedStates[$offerwall->id];
                    $ready = $feed['enabled'] && $feed['configured'];
                    $checkedAt = filled($feed['checked_at']) ? \Carbon\Carbon::parse($feed['checked_at']) : null;
                @endphp
                <article class="loot-feed-status-card {{ $ready ? 'is-ready' : 'is-missing' }}">
                    <div class="loot-feed-status-main">
                        <strong>{{ $offerwall->name }}</strong>
                        <span>{{ number_format($offerwall->provider_offers_count ?? 0) }} synced offers</span>
                        @if($checkedAt)
                            <small class="loot-muted">Checked {{ $checkedAt->diffForHumans() }} · {{ number_format($feed['count']) }} received</small>
                        @endif
                    </div>
                    <span class="loot-status {{ $feed['live'] ? 'success' : (($feed['success'] ?? null) === false ? 'danger' : 'warning') }}" title="{{ $feed['message'] }}">
                        @if(!$feed['enabled']) API off
                        @elseif(!$feed['configured']) Needs feed URL
                        @elseif(($feed['success'] ?? null) === false) Check failed
                        @elseif(($feed['success'] ?? null) === true && $feed['count'] < 1) Connected · no offers
                        @elseif(($feed['success'] ?? null) === true && !$feed['live']) Feed stale
                        @elseif($feed['live']) Live
                        @else Ready to check
                        @endif
                    </span>
                    @if($ready)
                        <form method="POST" action="{{ route('admin.provider-offers.sync-provider', $offerwall) }}">
                            @csrf
                            <button class="btn btn-sm btn-outline-light"><i data-feather="refresh-cw" class="me-25"></i>Check & sync</button>
                        </form>
                    @else
                        <a class="btn btn-sm btn-outline-light" href="{{ route('admin.offerwalls') }}">Configure</a>
                    @endif
                </article>
            @endforeach
        </div>

        <div class="admin-leads-toolbar">
            <form method="POST" action="{{ route('admin.provider-offers.bulk', request()->query()) }}" id="bulkOfferForm" class="d-flex flex-wrap gap-1 align-items-center">
                @csrf
                <div id="bulkOfferIds"></div>
                <select name="action" class="form-select" required>
                    <option value="">Bulk action</option>
                    <option value="show">Show on website</option>
                    <option value="hide">Hide from website</option>
                    <option value="mark_hot">Mark hot</option>
                    <option value="mark_featured">Mark featured</option>
                    <option value="clear">Clear hot/featured</option>
                    <option value="lock">Lock (exclude from auto-curation)</option>
                    <option value="unlock">Unlock</option>
                    <option value="delete">Delete selected</option>
                </select>
                <button type="submit" class="btn btn-outline-light">Apply to selected</button>
                <span class="loot-muted" id="selectedOfferCount">0 selected</span>
                <a class="btn btn-outline-light ms-auto" href="{{ route('admin.export.provider-offers', request()->query()) }}"><i data-feather="download" class="me-50"></i>Export CSV</a>
            </form>
        </div>

        <div class="table-responsive admin-leads-table-wrap">
            <table class="table admin-leads-table mb-0 align-middle">
                <thead>
                <tr>
                    <th><input type="checkbox" class="form-check-input" id="selectAllOffers"></th>
                    <th>Offer</th>
                    <th>Provider</th>
                    <th>Reward</th>
                    <th>Devices</th>
                    <th>Clicks</th>
                    <th>Status</th>
                    <th>Placement</th>
                    <th></th>
                </tr>
                </thead>
                <tbody>
                @forelse($offers as $offer)
                    @php
                        $image = $offer->icon_url ?: ($offer->icon_path ? Storage::url($offer->icon_path) : ($offer->offerwall?->photo_path ? Storage::url($offer->offerwall->photo_path) : null));
                        $feedLive = $offer->offerwall?->hasLiveApiFeed() ?? false;
                    @endphp
                    <tr>
                        <td><input type="checkbox" class="form-check-input offer-select" value="{{ $offer->id }}"></td>
                        <td>
                            <div class="d-flex align-items-center gap-1">
                                @if($image)
                                    <img src="{{ $image }}" alt="{{ $offer->name }}" style="width:48px;height:48px;border-radius:8px;object-fit:contain;background:#10151b;padding:4px;">
                                @endif
                                <div class="min-w-0">
                                    <strong>{{ Str::limit($offer->name, 42) }}</strong>
                                    <div class="loot-muted small">{{ Str::limit($offer->provider_offer_id ?: $offer->description, 74) }}</div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <strong>{{ optional($offer->offerwall)->name ?? 'No provider' }}</strong>
                            <div class="loot-muted small">ID {{ Str::limit($offer->provider_offer_id, 28) }}</div>
                            <div class="loot-muted small">{{ $offer->last_synced_at ? 'Synced '.$offer->last_synced_at->diffForHumans() : 'Not synced yet' }}</div>
                        </td>
                        <td><strong>{{ format_coins_as_usd($offer->reward_points) }}</strong><small class="d-block loot-muted">{{ number_format($offer->reward_points) }} coins</small></td>
                        <td>
                            @foreach($offer->normalizedDevices() as $device)
                                <span class="loot-status">{{ $device === 'ios' ? 'iOS' : ucfirst($device) }}</span>
                            @endforeach
                        </td>
                        <td>{{ number_format($offer->clicks_count) }}</td>
                        <td>
                            <form method="POST" action="{{ route('admin.provider-offers.update', $offer) }}">
                                @csrf
                                @method('PATCH')
                                <input type="hidden" name="is_active" value="{{ $offer->is_active ? 0 : 1 }}">
                                <button class="btn btn-sm {{ $offer->is_active ? 'btn-outline-success' : 'btn-outline-danger' }}">
                                    {{ $offer->is_active ? 'Visible' : 'Hidden' }}
                                </button>
                            </form>
                            @unless($feedLive)
                                <div class="loot-status warning mt-25">Not live from API</div>
                            @endunless
                        </td>
                        <td>
                            <div class="d-flex flex-wrap gap-50">
                                <form method="POST" action="{{ route('admin.provider-offers.update', $offer) }}">
                                    @csrf
                                    @method('PATCH')
                                    <input type="hidden" name="is_hot" value="{{ $offer->is_hot ? 0 : 1 }}">
                                    <button class="btn btn-sm {{ $offer->is_hot ? 'btn-loot' : 'btn-outline-light' }}">Hot</button>
                                </form>
                                <form method="POST" action="{{ route('admin.provider-offers.update', $offer) }}">
                                    @csrf
                                    @method('PATCH')
                                    <input type="hidden" name="is_featured" value="{{ $offer->is_featured ? 0 : 1 }}">
                                    <button class="btn btn-sm {{ $offer->is_featured ? 'btn-loot' : 'btn-outline-light' }}">Featured</button>
                                </form>
                                <form method="POST" action="{{ route('admin.provider-offers.update', $offer) }}" title="{{ $offer->curation_locked ? 'Unlock: allow auto-curation to manage this offer again' : 'Lock: auto-curation will never change this offer' }}">
                                    @csrf
                                    @method('PATCH')
                                    <input type="hidden" name="curation_locked" value="{{ $offer->curation_locked ? 0 : 1 }}">
                                    <button class="btn btn-sm {{ $offer->curation_locked ? 'btn-outline-warning' : 'btn-outline-light' }}">
                                        <i data-feather="{{ $offer->curation_locked ? 'lock' : 'unlock' }}"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-outline-light" data-bs-toggle="modal" data-bs-target="#providerOffer{{ $offer->id }}">Edit</button>
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="9">
                            <div class="loot-admin-empty">
                                <i data-feather="database"></i>
                                <strong>No real provider offers are synced yet</strong>
                                <span>Add each provider's official offer-feed URL and field mappings, then run Sync. Basketloot will only show offers imported from those real provider feeds.</span>
                                <a class="btn btn-loot" href="{{ route('admin.offerwalls') }}">Configure providers</a>
                            </div>
                        </td>
                    </tr>
                @endforelse
                </tbody>
            </table>
        </div>

        <div class="mt-2">{{ $offers->links() }}</div>
    </section>

    @push('scripts')
        <script>
            const selectAllOffers = document.getElementById('selectAllOffers');
            const offerCheckboxes = Array.from(document.querySelectorAll('.offer-select'));
            const selectedOfferCount = document.getElementById('selectedOfferCount');
            const bulkOfferIds = document.getElementById('bulkOfferIds');
            const bulkOfferForm = document.getElementById('bulkOfferForm');

            function syncBulkOfferState() {
                const selected = offerCheckboxes.filter((checkbox) => checkbox.checked).map((checkbox) => checkbox.value);
                selectedOfferCount.textContent = `${selected.length} selected`;
                bulkOfferIds.innerHTML = selected.map((id) => `<input type="hidden" name="ids[]" value="${id}">`).join('');
                if (selectAllOffers) {
                    selectAllOffers.checked = selected.length && selected.length === offerCheckboxes.length;
                }
            }

            selectAllOffers?.addEventListener('change', function () {
                offerCheckboxes.forEach((checkbox) => checkbox.checked = this.checked);
                syncBulkOfferState();
            });

            offerCheckboxes.forEach((checkbox) => checkbox.addEventListener('change', syncBulkOfferState));

            bulkOfferForm?.addEventListener('submit', function (event) {
                syncBulkOfferState();
                if (!bulkOfferIds.children.length) {
                    event.preventDefault();
                    alert('Select at least one offer first.');
                }
            });
        </script>
    @endpush

    @foreach($offers as $offer)
        <div class="modal fade" id="providerOffer{{ $offer->id }}" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <form method="POST" action="{{ route('admin.provider-offers.update', $offer) }}" class="modal-content">
                    @csrf
                    @method('PATCH')
                    <div class="modal-header">
                        <h4 class="modal-title loot-section-title">Edit offer</h4>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-1">
                            <label class="form-label">Name</label>
                            <input name="name" class="form-control" value="{{ $offer->name }}" required>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-1">
                                <label class="form-label">Reward points</label>
                                <input name="reward_points" type="number" step="0.01" class="form-control" value="{{ $offer->reward_points }}" required>
                            </div>
                            <div class="col-md-6 mb-1">
                                <label class="form-label">Category</label>
                                <select name="category" class="form-select">
                                    @foreach(['games','other','surveys','partners'] as $category)
                                        <option value="{{ $category }}" {{ $offer->category === $category ? 'selected' : '' }}>{{ ucfirst($category) }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="d-flex flex-wrap gap-2">
                            <label class="form-check form-switch">
                                <input type="hidden" name="is_active" value="0">
                                <input class="form-check-input" type="checkbox" name="is_active" value="1" {{ $offer->is_active ? 'checked' : '' }}>
                                <span class="form-check-label">Visible</span>
                            </label>
                            <label class="form-check form-switch">
                                <input type="hidden" name="is_hot" value="0">
                                <input class="form-check-input" type="checkbox" name="is_hot" value="1" {{ $offer->is_hot ? 'checked' : '' }}>
                                <span class="form-check-label">Hot</span>
                            </label>
                            <label class="form-check form-switch">
                                <input type="hidden" name="is_featured" value="0">
                                <input class="form-check-input" type="checkbox" name="is_featured" value="1" {{ $offer->is_featured ? 'checked' : '' }}>
                                <span class="form-check-label">Featured</span>
                            </label>
                            <label class="form-check form-switch">
                                <input type="hidden" name="curation_locked" value="0">
                                <input class="form-check-input" type="checkbox" name="curation_locked" value="1" {{ $offer->curation_locked ? 'checked' : '' }}>
                                <span class="form-check-label">Lock (exclude from auto-curation)</span>
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-light" data-bs-dismiss="modal">Cancel</button>
                        <button class="btn btn-loot">Save</button>
                    </div>
                </form>
            </div>
        </div>
    @endforeach
@endsection
