@extends('layouts.admin.app')

@section('title', translate('Customer Quality Report'))

@push('css_or_js')
    <style>
        .customer-quality-pagination {
            max-width: 100%;
            overflow-x: auto;
        }

        .customer-quality-pagination .pagination {
            flex-wrap: wrap;
            margin-bottom: 0;
        }
    </style>
@endpush

@php
    use App\CentralLogics\Helpers;
    use App\Services\Customer\CustomerQualityService;

    $highAudienceKey = CustomerQualityService::HIGH_AUDIENCE_KEY;
    $riskAudienceKey = CustomerQualityService::RISK_AUDIENCE_KEY;
    $audienceNames = CustomerQualityService::AUDIENCE_NAMES;
    $statusMappings = data_get($settings, 'status_mappings', []);
    $metaWriteAllowed = (bool) data_get($metaWriteEligibility, 'allowed', false);
    $metaWriteReasons = (array) data_get($metaWriteEligibility, 'reasons', []);
    $asyncQueueAvailable = config('queue.default') !== 'sync';
    $autoSyncAvailable = $metaWriteAllowed && $asyncQueueAvailable;
    $automaticRemovalChecked = $metaWriteAllowed && (bool) data_get($settings, 'automatic_removal_enabled', false);

    $statusClasses = [
        'high_quality' => 'badge-soft-success',
        'high_return' => 'badge-soft-danger',
        'high_cancel' => 'badge-soft-warning',
        'blacklisted_fake' => 'badge-soft-dark',
        'excluded_internal' => 'badge-soft-warning',
        'standard' => 'badge-soft-secondary',
    ];
@endphp

@section('content')
    <div class="content container-fluid">
        <div class="page-header d-flex flex-wrap align-items-center justify-content-between">
            <h1 class="page-header-title mb-2">
                <span class="page-header-icon">
                    <i class="tio-user"></i>
                </span>
                <span>{{ translate('Customer Quality Report') }}</span>
            </h1>
            <form action="{{ route('admin.customer-quality.refresh-metrics') }}" method="post" class="mb-2">
                @csrf
                <button type="submit" class="btn btn-outline-primary">
                    <i class="tio-refresh"></i>
                    {{ translate('Refresh Cached Calculation') }}
                </button>
            </form>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-sm-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h6>{{ translate('Total Customers') }}</h6>
                        <h3>{{ $totals['customers'] }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h6>{{ translate('High Cancel Customers') }}</h6>
                        <h3>{{ $totals['high_cancel'] }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h6>{{ translate('High Quality Customers') }}</h6>
                        <h3>{{ $totals['high_quality'] }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h6>{{ translate('High Return Customers') }}</h6>
                        <h3>{{ $totals['high_return'] }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h6>{{ translate('Delivered Amount') }}</h6>
                        <h3>{{ Helpers::format_currency($totals['delivered_amount']) }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3"><div class="card h-100"><div class="card-body"><h6>{{ translate('Manual Blacklist') }}</h6><h3>{{ $totals['manual_blacklist'] }}</h3></div></div></div>
            <div class="col-sm-6 col-lg-3"><div class="card h-100"><div class="card-body"><h6>{{ translate('Internal/Test Excluded') }}</h6><h3>{{ $totals['excluded_internal'] }}</h3></div></div></div>
            <div class="col-sm-6 col-lg-3"><div class="card h-100"><div class="card-body"><h6>{{ translate('Invalid Phone') }}</h6><h3>{{ $totals['invalid_phone'] }}</h3></div></div></div>
            <div class="col-sm-6 col-lg-3"><div class="card h-100"><div class="card-body"><h6>{{ translate('Risk Unique Eligible') }}</h6><h3>{{ $totals['risk_unique'] }}</h3><small>Cancel only: {{ $totals['high_cancel_only'] }} | Return only: {{ $totals['high_return_only'] }} | Both: {{ $totals['high_cancel_return_overlap'] }}</small></div></div></div>
        </div>

        <div class="card mb-3">
            <div class="card-body">
                <form action="{{ route('admin.customer-quality.index') }}" method="get">
                    <div class="row g-3">
                        <div class="col-sm-6 col-md-4">
                            <label class="sr-only" for="customer-quality-search">{{ translate('Search name, mobile, email or customer ID') }}</label>
                            <input id="customer-quality-search" type="search" name="search" value="{{ request('search') }}" class="form-control" placeholder="{{ translate('Search name, mobile, email or customer ID') }}">
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <label class="sr-only" for="customer-quality-status-filter">{{ translate('Customer Quality Status') }}</label>
                            <select id="customer-quality-status-filter" name="quality_status" class="form-control">
                                <option value="">{{ translate('All Status') }}</option>
                                <option value="high_quality" {{ request('quality_status') === 'high_quality' ? 'selected' : '' }}>{{ translate('High Quality') }}</option>
                                <option value="high_return" {{ request('quality_status') === 'high_return' ? 'selected' : '' }}>{{ translate('High Return') }}</option>
                                <option value="high_cancel" {{ request('quality_status') === 'high_cancel' ? 'selected' : '' }}>{{ translate('High Cancel') }}</option>
                                <option value="blacklisted_fake" {{ request('quality_status') === 'blacklisted_fake' ? 'selected' : '' }}>{{ translate('Blacklisted/Fake') }}</option>
                                <option value="manual_blacklist" {{ request('quality_status') === 'manual_blacklist' ? 'selected' : '' }}>{{ translate('Manual Blacklist') }}</option>
                                <option value="excluded_internal" {{ request('quality_status') === 'excluded_internal' ? 'selected' : '' }}>{{ translate('Internal/Test Excluded') }}</option>
                                <option value="invalid_phone" {{ request('quality_status') === 'invalid_phone' ? 'selected' : '' }}>{{ translate('Invalid Phone') }}</option>
                                <option value="meta_eligible" {{ request('quality_status') === 'meta_eligible' ? 'selected' : '' }}>{{ translate('Meta Eligible') }}</option>
                                <option value="meta_not_eligible" {{ request('quality_status') === 'meta_not_eligible' ? 'selected' : '' }}>{{ translate('Meta Not Eligible') }}</option>
                            </select>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <label class="sr-only" for="customer-quality-sort">{{ translate('Sort') }}</label>
                            <select id="customer-quality-sort" name="sort" class="form-control">
                                <option value="total_orders_desc" {{ request('sort') === 'total_orders_desc' ? 'selected' : '' }}>{{ translate('Total Orders') }}</option>
                                <option value="receive_rate_desc" {{ request('sort') === 'receive_rate_desc' ? 'selected' : '' }}>{{ translate('Receive Rate') }}</option>
                                <option value="return_rate_desc" {{ request('sort') === 'return_rate_desc' ? 'selected' : '' }}>{{ translate('Return Rate') }}</option>
                                <option value="delivered_amount_desc" {{ request('sort') === 'delivered_amount_desc' ? 'selected' : '' }}>{{ translate('Delivered Amount') }}</option>
                                <option value="average_order_value_desc" {{ request('sort') === 'average_order_value_desc' ? 'selected' : '' }}>{{ translate('Average Order Value') }}</option>
                            </select>
                        </div>
                        <div class="col-sm-6 col-md-2">
                            <button class="btn btn--primary btn-block" type="submit">{{ translate('Go') }}</button>
                            <a class="btn btn-outline-warning btn-block mt-2" href="{{ route('admin.customer-quality.invalid-phones.csv') }}">{{ translate('Invalid Phone CSV') }}</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header border-0">
                <h4 class="card-title">{{ translate('Meta Audience Sync') }}</h4>
            </div>
            <div class="card-body">
                <form action="{{ route('admin.customer-quality.settings') }}" method="post" class="mb-4">
                    @csrf
                    <div class="alert alert-info mb-3" role="status">
                        {{ translate('Saving settings recalculates the Customer Quality metrics in the same transaction.') }}
                    </div>
                    @if(!$metaWriteAllowed || !$asyncQueueAvailable)
                        <div class="alert alert-warning mb-3" id="customer-quality-meta-write-warning" role="alert">
                            <strong>{{ translate('Meta write controls are locked for safety.') }}</strong>
                            <ul class="mb-0 pl-3">
                                @foreach($metaWriteReasons as $reason)<li>{{ $reason }}</li>@endforeach
                                @if(!$asyncQueueAvailable)<li>{{ translate('Auto Sync requires an asynchronous queue driver and a running worker.') }}</li>@endif
                            </ul>
                        </div>
                    @endif

                    <fieldset class="border rounded p-3 mb-3">
                        <legend class="h5 w-auto px-2 mb-0">{{ translate('Safety Controls') }}</legend>
                        <div class="row g-3">
                            <div class="col-md-6 col-xl-3">
                                <label class="form-label" for="customer-quality-auto-sync">{{ translate('Auto Sync') }}</label>
                                <label class="toggle-switch toggle-switch-sm d-block mt-2" for="customer-quality-auto-sync">
                                    <input type="checkbox" name="auto_sync_enabled" value="1" class="toggle-switch-input" id="customer-quality-auto-sync" {{ $autoSyncAvailable && data_get($settings, 'auto_sync_enabled') ? 'checked' : '' }} {{ $autoSyncAvailable ? '' : 'disabled' }} @if(!$autoSyncAvailable) aria-describedby="customer-quality-meta-write-warning" @endif>
                                    <span class="toggle-switch-label"><span class="toggle-switch-indicator"></span></span>
                                </label>
                            </div>
                            <div class="col-md-6 col-xl-3">
                                <label class="form-label" for="customer-quality-auto-removal">{{ translate('Automatic Removal') }}</label>
                                <label class="toggle-switch toggle-switch-sm d-block mt-2" for="customer-quality-auto-removal">
                                    <input type="checkbox" name="automatic_removal_enabled" value="1" class="toggle-switch-input" id="customer-quality-auto-removal" {{ $automaticRemovalChecked ? 'checked' : '' }} {{ $metaWriteAllowed ? '' : 'disabled' }} @if(!$metaWriteAllowed) aria-describedby="customer-quality-meta-write-warning" @endif>
                                    <span class="toggle-switch-label"><span class="toggle-switch-indicator"></span></span>
                                </label>
                            </div>
                            <div class="col-md-6 col-xl-3">
                                <label class="form-label" for="customer-quality-lookalike-sync">{{ translate('Lookalike Sync') }}</label>
                                <label class="toggle-switch toggle-switch-sm d-block mt-2" for="customer-quality-lookalike-sync">
                                    <input type="checkbox" name="lookalike_sync_enabled" value="1" class="toggle-switch-input" id="customer-quality-lookalike-sync" {{ data_get($settings, 'lookalike_sync_enabled', false) ? 'checked' : '' }}>
                                    <span class="toggle-switch-label"><span class="toggle-switch-indicator"></span></span>
                                </label>
                            </div>
                            <div class="col-md-6 col-xl-3">
                                <label class="form-label" for="customer-quality-max-removal">{{ translate('Maximum Removal %') }}</label>
                                <input id="customer-quality-max-removal" type="number" min="0" max="20" step="0.01" name="max_removal_percentage" value="{{ data_get($settings, 'max_removal_percentage', 20) }}" class="form-control">
                            </div>
                            <div class="col-md-6 col-xl-3">
                                <label class="form-label" for="customer-quality-auto-exclusion">{{ translate('Auto Exclude Internal/Test') }}</label>
                                <label class="toggle-switch toggle-switch-sm d-block mt-2" for="customer-quality-auto-exclusion"><input type="checkbox" name="auto_exclusions[enabled]" value="1" class="toggle-switch-input" id="customer-quality-auto-exclusion" {{ data_get($settings, 'auto_exclusions.enabled', true) ? 'checked' : '' }}><span class="toggle-switch-label"><span class="toggle-switch-indicator"></span></span></label>
                            </div>
                            <div class="col-md-6 col-xl-3">
                                <label class="form-label" for="customer-quality-admin-staff-match">{{ translate('Match Admin/Staff Tables') }}</label>
                                <label class="toggle-switch toggle-switch-sm d-block mt-2" for="customer-quality-admin-staff-match"><input type="checkbox" name="auto_exclusions[match_admin_staff_tables]" value="1" class="toggle-switch-input" id="customer-quality-admin-staff-match" {{ data_get($settings, 'auto_exclusions.match_admin_staff_tables', true) ? 'checked' : '' }}><span class="toggle-switch-label"><span class="toggle-switch-indicator"></span></span></label>
                            </div>
                        </div>
                    </fieldset>

                    <fieldset class="border rounded p-3 mb-3">
                        <legend class="h5 w-auto px-2 mb-0">{{ translate('Quality Thresholds') }}</legend>
                        <div class="row g-3">
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-min-orders">{{ translate('Min Delivered Orders') }}</label><input id="customer-quality-min-orders" type="number" min="0" name="min_delivered_orders" value="{{ data_get($settings, 'min_delivered_orders') }}" class="form-control"></div>
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-min-receive">{{ translate('Min Receive Rate') }}</label><input id="customer-quality-min-receive" type="number" min="0" max="100" step="0.01" name="min_receive_rate" value="{{ data_get($settings, 'min_receive_rate') }}" class="form-control"></div>
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-max-return">{{ translate('Max Return Rate') }}</label><input id="customer-quality-max-return" type="number" min="0" max="100" step="0.01" name="max_return_rate" value="{{ data_get($settings, 'max_return_rate') }}" class="form-control"></div>
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-max-cancel">{{ translate('Max Cancel Rate') }}</label><input id="customer-quality-max-cancel" type="number" min="0" max="100" step="0.01" name="max_cancel_rate" value="{{ data_get($settings, 'max_cancel_rate', 30) }}" class="form-control"></div>
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-min-amount">{{ translate('Min Delivered Amount') }}</label><input id="customer-quality-min-amount" type="number" min="0.01" step="0.01" name="min_delivered_amount" value="{{ data_get($settings, 'min_delivered_amount', 3000) }}" class="form-control"></div>
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-min-aov">{{ translate('Min AOV') }}</label><input id="customer-quality-min-aov" type="number" min="0.01" step="0.01" name="min_average_order_value" value="{{ data_get($settings, 'min_average_order_value', 800) }}" class="form-control"></div>
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-dry-run-expiry">{{ translate('Dry Run Expiry Minutes') }}</label><input id="customer-quality-dry-run-expiry" type="number" min="5" max="1440" name="dry_run_expires_minutes" value="{{ data_get($settings, 'dry_run_expires_minutes') }}" class="form-control"></div>
                        </div>
                    </fieldset>

                    <fieldset class="border rounded p-3 mb-3">
                        <legend class="h5 w-auto px-2 mb-0">{{ translate('Audience Configuration') }}</legend>
                        <div class="row g-3">
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-country">{{ translate('Country') }}</label><input id="customer-quality-country" type="text" maxlength="2" name="country_code" value="{{ data_get($settings, 'country_code', 'BD') }}" class="form-control text-uppercase"></div>
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-lookalike-country">{{ translate('Lookalike Country') }}</label><input id="customer-quality-lookalike-country" type="text" maxlength="2" name="lookalike[country]" value="{{ data_get($settings, 'lookalike.country', 'BD') }}" class="form-control text-uppercase"></div>
                            <div class="col-md-6 col-xl-3"><label class="form-label" for="customer-quality-lookalike-ratio">{{ translate('Lookalike Ratio') }}</label><input id="customer-quality-lookalike-ratio" type="number" min="0.01" max="0.2" step="0.01" name="lookalike[ratio]" value="{{ data_get($settings, 'lookalike.ratio', 0.01) }}" class="form-control"></div>
                            <div class="col-md-6"><label class="form-label" for="customer-quality-high-audience-id">{{ translate('High Quality Meta Audience ID') }}</label><input id="customer-quality-high-audience-id" type="text" name="audiences[{{ $highAudienceKey }}][meta_audience_id]" value="{{ data_get($settings, 'audiences.' . $highAudienceKey . '.meta_audience_id') }}" class="form-control"></div>
                            <div class="col-md-6"><label class="form-label" for="customer-quality-lookalike-id">{{ translate('Bangladesh 1% Lookalike ID') }}</label><input id="customer-quality-lookalike-id" type="text" name="audiences[{{ $highAudienceKey }}][lookalike_audience_id]" value="{{ data_get($settings, 'audiences.' . $highAudienceKey . '.lookalike_audience_id') }}" class="form-control"></div>
                            <div class="col-md-6"><label class="form-label" for="customer-quality-risk-audience-id">{{ translate('Risk Meta Audience ID') }}</label><input id="customer-quality-risk-audience-id" type="text" name="audiences[{{ $riskAudienceKey }}][meta_audience_id]" value="{{ data_get($settings, 'audiences.' . $riskAudienceKey . '.meta_audience_id') }}" class="form-control"></div>
                        </div>
                    </fieldset>

                    <fieldset class="border rounded p-3 mb-3">
                        <legend class="h5 w-auto px-2 mb-0">{{ translate('Status and Exclusion Rules') }}</legend>
                        <p class="text-muted">{{ translate('Comma, newline and bulleted lists are accepted. Status values must not overlap between groups.') }}</p>
                        <div class="row g-3">
                            <div class="col-lg-4"><label class="form-label" for="customer-quality-delivered-statuses">{{ translate('Delivered Status Mapping') }}</label><textarea id="customer-quality-delivered-statuses" name="status_mappings[delivered]" rows="3" class="form-control">{{ implode(', ', (array) data_get($statusMappings, 'delivered', [])) }}</textarea></div>
                            <div class="col-lg-4"><label class="form-label" for="customer-quality-returned-statuses">{{ translate('Returned Status Mapping') }}</label><textarea id="customer-quality-returned-statuses" name="status_mappings[returned]" rows="3" class="form-control">{{ implode(', ', (array) data_get($statusMappings, 'returned', [])) }}</textarea></div>
                            <div class="col-lg-4"><label class="form-label" for="customer-quality-cancelled-statuses">{{ translate('Cancelled Status Mapping') }}</label><textarea id="customer-quality-cancelled-statuses" name="status_mappings[cancelled]" rows="3" class="form-control">{{ implode(', ', (array) data_get($statusMappings, 'cancelled', [])) }}</textarea></div>
                            <div class="col-lg-4"><label class="form-label" for="customer-quality-internal-keywords">{{ translate('Internal/Test Keywords') }}</label><textarea id="customer-quality-internal-keywords" name="auto_exclusions[keywords]" rows="3" class="form-control">{{ implode(', ', (array) data_get($settings, 'auto_exclusions.keywords', [])) }}</textarea><small>{{ translate('Exact token/boundary matching only') }}</small></div>
                            <div class="col-lg-4"><label class="form-label" for="customer-quality-internal-emails">{{ translate('Internal/Test Emails') }}</label><textarea id="customer-quality-internal-emails" name="auto_exclusions[emails]" rows="3" class="form-control">{{ implode(', ', (array) data_get($settings, 'auto_exclusions.emails', [])) }}</textarea></div>
                            <div class="col-lg-4"><label class="form-label" for="customer-quality-internal-phones">{{ translate('Internal/Test Phones') }}</label><textarea id="customer-quality-internal-phones" name="auto_exclusions[phones]" rows="3" class="form-control">{{ implode(', ', (array) data_get($settings, 'auto_exclusions.phones', [])) }}</textarea></div>
                        </div>
                    </fieldset>

                    <button type="submit" class="btn btn--primary"><i class="tio-save" aria-hidden="true"></i> {{ translate('Save Settings') }}</button>
                </form>

                <div class="row g-3">
                    @foreach([$highAudienceKey, $riskAudienceKey] as $audienceKey)
                        <div class="col-lg-6">
                            <div class="border rounded p-3 h-100">
                                <h5 class="mb-1">{{ $audienceNames[$audienceKey] }}</h5>
                                <div class="mb-3 text-muted fs-12">
                                    {{ translate('Eligible') }}: {{ $audienceCounts[$audienceKey] ?? 0 }}
                                    <span class="mx-1">|</span>
                                    {{ translate('Meta Status') }}:
                                    <strong class="text-capitalize">{{ str_replace('_', ' ', data_get($audienceStatuses, $audienceKey . '.state', 'not checked')) }}</strong>
                                    <span class="mx-1">|</span> {{ translate('Add') }}: {{ data_get($audienceSummaries, $audienceKey . '.add_count', 0) }}
                                    <span class="mx-1">|</span> {{ translate('Remove') }}: {{ data_get($audienceSummaries, $audienceKey . '.remove_count', 0) }}
                                    <span class="mx-1">|</span> {{ translate('Skipped') }}: {{ data_get($audienceSummaries, $audienceKey . '.skipped_count', 0) }}
                                    <div class="mt-1">ID: <code>{{ data_get($settings, 'audiences.' . $audienceKey . '.meta_audience_id', 'not configured') }}</code> | {{ translate('Approx. Size') }}: {{ data_get($audienceStatuses, $audienceKey . '.approximate_count_lower_bound', 'n/a') }}–{{ data_get($audienceStatuses, $audienceKey . '.approximate_count_upper_bound', 'n/a') }} | {{ translate('Last Check') }}: {{ data_get($audienceStatuses, $audienceKey . '.checked_at', 'never') }}</div>
                                    <div>{{ translate('Last Successful Sync') }}: {{ data_get($settings, 'audiences.' . $audienceKey . '.sync_result.last_successful_sync_at', 'never') }} | {{ translate('Last Add') }}: {{ data_get($settings, 'audiences.' . $audienceKey . '.sync_result.last_add_count', 0) }} | {{ translate('Last Remove') }}: {{ data_get($settings, 'audiences.' . $audienceKey . '.sync_result.last_remove_count', 0) }} | {{ translate('Failed') }}: {{ data_get($settings, 'audiences.' . $audienceKey . '.sync_result.last_failed_count', 0) }}</div>
                                </div>
                                <div class="d-flex flex-wrap align-items-center">
                                    <a href="{{ route('admin.customer-quality.index', array_merge(request()->query(), ['preview_audience' => $audienceKey])) }}" class="btn btn-outline-info btn-sm mr-2 mb-2">
                                        <i class="tio-visible-outlined"></i>
                                        {{ translate('Sync Preview') }}
                                    </a>
                                    <form action="{{ route('admin.customer-quality.sync-all') }}" method="post" class="mr-2 mb-2">@csrf<input type="hidden" name="audience_key" value="{{ $audienceKey }}"><input type="hidden" name="mode" value="dry_run"><button type="submit" class="btn btn-outline-info btn-sm">{{ translate('Dry Run') }}</button></form>
                                    <form action="{{ route('admin.customer-quality.sync-all') }}" method="post" class="mr-2 mb-2" onsubmit="return confirm('Upload one customer to Meta and immediately remove that same test customer?');">@csrf<input type="hidden" name="audience_key" value="{{ $audienceKey }}"><input type="hidden" name="mode" value="test_upload"><input type="hidden" name="confirm_test_upload" value="1"><button type="submit" class="btn btn-outline-warning btn-sm" {{ data_get($audienceSummaries, $audienceKey . '.dry_run_ready', false) ? '' : 'disabled' }}>{{ translate('Test Upload') }}</button></form>
                                    <form action="{{ route('admin.customer-quality.sync-all') }}" method="post" class="mb-2" onsubmit="return confirm('WARNING: Confirm LIVE Meta sync for {{ addslashes($audienceNames[$audienceKey]) }} (ID: {{ data_get($settings, 'audiences.' . $audienceKey . '.meta_audience_id', 'missing') }}, Eligible: {{ $audienceCounts[$audienceKey] ?? 0 }}, Add: {{ data_get($audienceSummaries, $audienceKey . '.add_count', 0) }}, Remove: {{ data_get($audienceSummaries, $audienceKey . '.remove_count', 0) }}, Skipped: {{ data_get($audienceSummaries, $audienceKey . '.skipped_count', 0) }}, Expires: {{ data_get($audienceSummaries, $audienceKey . '.dry_run_expires_at', 'not ready') }}, Checksum: {{ data_get($audienceSummaries, $audienceKey . '.checksum', 'missing') }}).');">@csrf<input type="hidden" name="audience_key" value="{{ $audienceKey }}"><input type="hidden" name="mode" value="live"><input type="hidden" name="confirm_live_sync" value="1"><button type="submit" class="btn btn-danger btn-sm" {{ data_get($audienceSummaries, $audienceKey . '.live_ready', false) && $metaWriteAllowed ? '' : 'disabled' }}>{{ translate('Confirm Live') }}</button></form>
                                </div>
                                <div class="d-flex flex-wrap align-items-center mt-2">
                                    <form action="{{ route('admin.customer-quality.audience-status') }}" method="post" class="mr-2 mb-2">
                                        @csrf
                                        <input type="hidden" name="audience_key" value="{{ $audienceKey }}">
                                        <button type="submit" class="btn btn-outline-secondary btn-sm">
                                            <i class="tio-refresh"></i>
                                            {{ translate('Refresh Meta Status') }}
                                        </button>
                                    </form>
                                    @if($audienceKey === $highAudienceKey)<span class="badge badge-soft-secondary mb-2">{{ translate('Lookalike create/update disabled until a validated ID is configured') }}</span>@endif
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>

        @if($preview)
            <div class="card mb-3">
                <div class="card-header border-0">
                    <h4 class="card-title">{{ translate('Sync Preview') }}: {{ $preview['audience_name'] }}</h4>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-3">
                        <div class="col-sm-6 col-lg-2"><strong>{{ translate('Candidates') }}:</strong> {{ $preview['candidate_count'] }}</div>
                        <div class="col-sm-6 col-lg-2"><strong>{{ translate('Eligible') }}:</strong> {{ $preview['eligible_count'] }}</div>
                        <div class="col-sm-6 col-lg-2"><strong>{{ translate('Add') }}:</strong> {{ $preview['add_count'] }}</div>
                        <div class="col-sm-6 col-lg-2"><strong>{{ translate('Remove') }}:</strong> {{ $preview['remove_count'] }}</div>
                        <div class="col-sm-6 col-lg-2"><strong>{{ translate('Proposed Remove') }}:</strong> {{ $preview['proposed_remove_count'] }} ({{ number_format($preview['removal_percentage'], 2) }}%)</div>
                        <div class="col-sm-6 col-lg-2"><strong>{{ translate('Removal Suppressed') }}:</strong> {{ $preview['suppressed_remove_count'] }}</div>
                        <div class="col-sm-6 col-lg-2"><strong>{{ translate('Skipped') }}:</strong> {{ $preview['skipped_count'] }}</div>
                        <div class="col-sm-6 col-lg-2"><strong>{{ translate('Expires') }}:</strong> {{ $preview['expires_at']->toDateTimeString() }}</div>
                    </div>
                    @if(!$preview['removal_enabled'] && $preview['suppressed_remove_count'] > 0)<div class="alert alert-warning">{{ translate('Automatic audience removal is OFF. Proposed removals are shown for audit only and will not be sent.') }}</div>@endif
                    <div class="mb-2"><strong>{{ translate('Scope Hash') }}:</strong> <code>{{ $preview['scope_hash'] }}</code></div>
                    <div class="mb-3"><strong>{{ translate('Checksum') }}:</strong> <code>{{ $preview['checksum'] }}</code></div>

                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <h5>{{ translate('Add Preview') }}</h5>
                            <div class="table-responsive">
                                <table class="table table-sm table-borderless table-nowrap mb-0">
                                    <thead class="thead-light">
                                    <tr>
                                        <th>{{ translate('Full Mobile Number') }}</th>
                                        <th>{{ translate('Phone Hash') }}</th>
                                        <th>{{ translate('Value') }}</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    @forelse($preview['add_rows'] as $row)
                                        <tr>
                                            <td>{{ $row->formatted_phone ?? $row->normalized_phone ?? $row->phone ?? '' }}</td>
                                            <td><code>{{ substr($row->phone_hash ?? '', 0, 16) }}...</code></td>
                                            <td>{{ number_format((float) ($row->lookalike_value ?? 0), 2) }}</td>
                                        </tr>
                                    @empty
                                        <tr><td colspan="3" class="text-center">{{ translate('No add rows') }}</td></tr>
                                    @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h5>{{ translate('Remove Preview') }}</h5>
                            <div class="table-responsive">
                                <table class="table table-sm table-borderless table-nowrap mb-0">
                                    <thead class="thead-light">
                                    <tr>
                                        <th>{{ translate('Full Mobile Number') }}</th>
                                        <th>{{ translate('Metric Key') }}</th>
                                        <th>{{ translate('Phone Hash') }}</th>
                                        <th>{{ translate('Value') }}</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    @forelse($preview['remove_rows'] as $row)
                                        <tr>
                                            <td>{{ $row->formatted_phone ?? '' }}</td>
                                            <td>{{ $row->metric_key ?? '' }}</td>
                                            <td><code>{{ substr($row->phone_hash ?? '', 0, 16) }}...</code></td>
                                            <td>{{ number_format((float) ($row->lookalike_value ?? 0), 2) }}</td>
                                        </tr>
                                    @empty
                                        <tr><td colspan="4" class="text-center">{{ translate('No remove rows') }}</td></tr>
                                    @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    @if($preview['skipped_count'] > 0)
                        <div class="mb-3">
                            <h5>{{ translate('Invalid / Excluded Customers') }}</h5>
                            <div class="mb-2">
                                @foreach($preview['skipped_reasons'] as $reason => $count)
                                    <span class="badge badge-soft-warning mr-1">
                                        {{ translate(ucwords(str_replace('_', ' ', $reason))) }}: {{ $count }}
                                    </span>
                                @endforeach
                            </div>
                            <div class="table-responsive">
                                <table class="table table-sm table-borderless table-nowrap mb-0">
                                    <thead class="thead-light">
                                    <tr>
                                        <th>{{ translate('Customer') }}</th>
                                        <th>{{ translate('Full Mobile Number') }}</th>
                                        <th>{{ translate('Reason') }}</th>
                                        <th>{{ translate('Details') }}</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    @foreach($preview['skipped_rows'] as $row)
                                        <tr>
                                            <td>{{ $row['customer_name'] }}</td>
                                            <td>{{ $row['phone'] }}</td>
                                            <td>{{ translate(ucwords(str_replace('_', ' ', $row['reason']))) }}</td>
                                            <td>{{ $row['detail'] }}</td>
                                        </tr>
                                    @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    @endif

                    <div class="table-responsive">
                        <table class="table table-borderless table-thead-bordered table-nowrap mb-0">
                            <thead class="thead-light">
                            <tr>
                                <th>{{ translate('Customer') }}</th>
                                <th>{{ translate('Full Mobile Number') }}</th>
                                <th>{{ translate('Email Hash') }}</th>
                                <th>{{ translate('External ID Hash') }}</th>
                                <th>{{ translate('Country') }}</th>
                                <th class="text-right">{{ translate('Delivered Value') }}</th>
                                <th class="text-center">{{ translate('Quality Score') }}</th>
                                <th class="text-right">{{ translate('Lookalike Value') }}</th>
                                <th>{{ translate('Status') }}</th>
                            </tr>
                            </thead>
                            <tbody>
                            @forelse($preview['rows'] as $row)
                                <tr>
                                    <td>{{ $row->customer_name }}</td>
                                    <td>{{ $row->formatted_phone }}</td>
                                    <td><code>{{ substr($row->email_hash, 0, 16) }}...</code></td>
                                    <td><code>{{ substr($row->external_id_hash, 0, 16) }}...</code></td>
                                    <td>{{ $row->country_code }}</td>
                                    <td class="text-right">{{ Helpers::format_currency($row->delivered_amount) }}</td>
                                    <td class="text-center">{{ number_format($row->quality_score, 2) }}</td>
                                    <td class="text-right">{{ number_format($row->lookalike_value, 2) }}</td>
                                    <td>
                                        <span class="badge {{ $statusClasses[$row->customer_quality_status] ?? 'badge-soft-secondary' }}">
                                            {{ translate($row->customer_quality_label) }}
                                        </span>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="9" class="text-center py-4">{{ translate('No eligible customer found') }}</td>
                                </tr>
                            @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        @endif

        <form id="customer-quality-selected-form" action="{{ route('admin.customer-quality.sync-selected') }}" method="post">
            @csrf
            <input type="hidden" name="audience_key" id="selected-audience-key" value="{{ $highAudienceKey }}">

            <div class="card mb-3">
                <div class="card-header border-0 d-flex flex-wrap align-items-center justify-content-between">
                    <h4 class="card-title mb-2">{{ translate('Customers') }}</h4>
                    <div class="d-flex flex-wrap align-items-center mb-2">
                        <span class="badge badge-soft-info">{{ translate('Use the checksum-bound audience controls above for Dry Run, Test Upload and Confirm Live') }}</span>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-borderless table-thead-bordered table-nowrap table-align-middle mb-0">
                        <thead class="thead-light">
                        <tr>
                            <th>
                                <label class="sr-only" for="quality-check-all">{{ translate('Select all customers on this page') }}</label>
                                <input type="checkbox" id="quality-check-all">
                            </th>
                            <th>{{ translate('Customer Name') }}</th>
                            <th>{{ translate('Full Mobile Number') }}</th>
                            <th class="text-center">{{ translate('Total Orders') }}</th>
                            <th class="text-center">{{ translate('Delivered Orders') }}</th>
                            <th class="text-center">{{ translate('Returned Orders') }}</th>
                            <th class="text-center">{{ translate('Cancelled Orders') }}</th>
                            <th class="text-right">{{ translate('Delivered Amount') }}</th>
                            <th class="text-right">{{ translate('AOV') }}</th>
                            <th class="text-center" title="Delivered / (Delivered + Returned). Cancelled orders are excluded.">{{ translate('Delivery Receive Rate') }}</th>
                            <th class="text-center">{{ translate('Return Rate') }}</th>
                            <th class="text-center">{{ translate('Cancel Rate') }}</th>
                            <th class="text-center">{{ translate('Quality Score') }}</th>
                            <th>{{ translate('Customer Quality Status') }}</th>
                            <th>{{ translate('Action') }}</th>
                        </tr>
                        </thead>
                        <tbody>
                        @forelse($customers as $customer)
                            @php($qualityCheckboxId = 'quality-row-' . md5($customer->metric_key))
                            <tr>
                                <td>
                                    <label class="sr-only" for="{{ $qualityCheckboxId }}">{{ translate('Select customer') }} {{ $customer->customer_name }}</label>
                                    <input id="{{ $qualityCheckboxId }}" type="checkbox" name="customer_keys[]" value="{{ $customer->metric_key }}" class="quality-row-check">
                                </td>
                                <td>
                                    @if($customer->user_id)
                                        <a href="{{ route('admin.customer.view', [$customer->user_id]) }}" class="text-dark">
                                            {{ $customer->customer_name }}
                                        </a>
                                    @else
                                        {{ $customer->customer_name }}
                                        <span class="badge badge-soft-info ml-1">{{ translate('Guest') }}</span>
                                    @endif
                                </td>
                                <td>{{ $customer->formatted_phone }} @if($customer->phone_validation_reason)<small class="d-block text-danger">{{ $customer->phone_validation_reason }}</small>@endif</td>
                                <td class="text-center">{{ $customer->total_orders }}</td>
                                <td class="text-center">{{ $customer->delivered_orders }}</td>
                                <td class="text-center">{{ $customer->returned_orders }}</td>
                                <td class="text-center">{{ $customer->cancelled_orders }}</td>
                                <td class="text-right">{{ Helpers::format_currency($customer->delivered_amount) }}</td>
                                <td class="text-right">{{ Helpers::format_currency($customer->average_order_value) }}</td>
                                <td class="text-center">{{ number_format($customer->receive_rate, 2) }}%</td>
                                <td class="text-center">{{ number_format($customer->return_rate, 2) }}%</td>
                                <td class="text-center">{{ number_format($customer->cancel_rate, 2) }}%</td>
                                <td class="text-center">{{ number_format($customer->quality_score, 2) }}</td>
                                <td>
                                    <span class="badge {{ $statusClasses[$customer->customer_quality_status] ?? 'badge-soft-secondary' }}">
                                        {{ translate($customer->customer_quality_label) }}
                                    </span>
                                    @if($customer->is_high_return)<span class="badge badge-soft-danger ml-1">{{ translate('High Return') }}</span>@endif
                                    @if($customer->is_high_cancel)<span class="badge badge-soft-warning ml-1">{{ translate('High Cancel') }}</span>@endif
                                    @if($customer->is_blacklisted)<span class="badge badge-soft-dark ml-1">{{ translate('Manual Blacklist') }}</span>@endif
                                    @if(blank($customer->normalized_phone))
                                        <span class="badge badge-soft-warning ml-1">{{ translate('Invalid Phone') }}</span>
                                    @endif
                                    @if($customer->is_meta_excluded)
                                        <span class="badge badge-soft-warning ml-1">
                                            {{ translate('Meta Excluded') }}: {{ translate(ucwords(str_replace('_', ' ', $customer->meta_exclusion_category))) }}
                                        </span>
                                    @endif
                                    @if($customer->classification_reasons)<small class="d-block mt-1 text-muted">{{ implode(', ', $customer->classification_reasons) }}</small>@else<small class="d-block mt-1 text-success">{{ translate('Passed all requirements') }}</small>@endif
                                    @if($customer->is_internal)<small class="d-block text-warning">{{ data_get($customer->internal_exclusion_evidence, 'source') }} / {{ data_get($customer->internal_exclusion_evidence, 'table') }} / {{ data_get($customer->internal_exclusion_evidence, 'field') }}: {{ data_get($customer->internal_exclusion_evidence, 'value') }} ({{ $customer->internal_exclusion_reason }})</small>@endif
                                </td>
                                <td>
                                    @if($customer->user_id)
                                        <button type="submit" form="customer-quality-flag-form" formaction="{{ route('admin.customer-quality.flag', [$customer->user_id]) }}" name="flag_action" value="blacklist" class="btn btn-outline-dark btn-xs mb-1">
                                            {{ translate('Blacklist') }}
                                        </button>
                                        <button type="submit" form="customer-quality-flag-form" formaction="{{ route('admin.customer-quality.flag', [$customer->user_id]) }}" name="flag_action" value="fake" class="btn btn-outline-danger btn-xs mb-1">
                                            {{ translate('Fake') }}
                                        </button>
                                        @if($customer->is_blacklisted || $customer->is_fake)
                                            <button type="submit" form="customer-quality-flag-form" formaction="{{ route('admin.customer-quality.flag', [$customer->user_id]) }}" name="flag_action" value="clear" class="btn btn-outline-secondary btn-xs mb-1">
                                                {{ translate('Clear') }}
                                            </button>
                                        @endif
                                    @endif
                                    @if($customer->is_meta_excluded)
                                        <button type="submit" form="customer-quality-include-form" name="metric_key" value="{{ $customer->metric_key }}" class="btn btn-outline-success btn-xs mb-1">
                                            {{ translate('Include in Meta') }}
                                        </button>
                                    @else
                                        <button type="button" class="btn btn-outline-warning btn-xs mb-1 meta-exclusion-button" data-metric-key="{{ $customer->metric_key }}" data-customer-name="{{ $customer->customer_name }}">
                                            {{ translate('Exclude from Meta') }}
                                        </button>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="15" class="text-center py-4">{{ translate('No cached customer metric found') }}</td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
                @if($customers->hasPages())
                    <div class="card-footer customer-quality-pagination">
                        {!! $customers->links() !!}
                    </div>
                @endif
            </div>
        </form>

        <form id="customer-quality-flag-form" method="post">
            @csrf
        </form>

        <form id="customer-quality-include-form" action="{{ route('admin.customer-quality.exclusion') }}" method="post">
            @csrf
            <input type="hidden" name="exclude_action" value="include">
        </form>

        <div class="modal fade" id="customer-quality-exclusion-modal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <form action="{{ route('admin.customer-quality.exclusion') }}" method="post">
                        @csrf
                        <input type="hidden" name="exclude_action" value="exclude">
                        <input type="hidden" name="metric_key" id="meta-exclusion-metric-key">
                        <div class="modal-header">
                            <h5 class="modal-title">{{ translate('Exclude from Meta Audience') }}</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3 font-weight-bold" id="meta-exclusion-customer-name"></div>
                            <div class="form-group">
                                <label class="form-label" for="customer-quality-exclusion-category">{{ translate('Category') }}</label>
                                <select id="customer-quality-exclusion-category" name="category" class="form-control" required>
                                    <option value="admin">{{ translate('Admin') }}</option>
                                    <option value="staff">{{ translate('Staff') }}</option>
                                    <option value="test">{{ translate('Test Customer') }}</option>
                                    <option value="own_store">{{ translate('Own Store') }}</option>
                                    <option value="internal" selected>{{ translate('Internal Customer') }}</option>
                                    <option value="other">{{ translate('Other') }}</option>
                                </select>
                            </div>
                            <div class="form-group mb-0">
                                <label class="form-label" for="customer-quality-exclusion-reason">{{ translate('Reason') }}</label>
                                <input id="customer-quality-exclusion-reason" type="text" name="reason" maxlength="191" class="form-control">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">{{ translate('Cancel') }}</button>
                            <button type="submit" class="btn btn-warning">{{ translate('Exclude') }}</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header border-0">
                <h4 class="card-title">{{ translate('Sync Logs') }}</h4>
            </div>
            <div class="table-responsive">
                <table class="table table-borderless table-thead-bordered table-nowrap mb-0">
                    <thead class="thead-light">
                    <tr>
                        <th>{{ translate('Date') }}</th>
                        <th>{{ translate('Audience') }}</th>
                        <th>{{ translate('Mode') }}</th>
                        <th>{{ translate('Status') }}</th>
                        <th class="text-center">{{ translate('Eligible') }}</th>
                        <th class="text-center">{{ translate('Add') }}</th>
                        <th class="text-center">{{ translate('Remove') }}</th>
                        <th class="text-center">{{ translate('Skipped') }}</th>
                        <th>{{ translate('Checksum') }}</th>
                        <th>{{ translate('Expires') }}</th>
                        <th>{{ translate('Meta Result') }}</th>
                        <th>{{ translate('Error') }}</th>
                    </tr>
                    </thead>
                    <tbody>
                    @forelse($syncLogs as $log)
                        <tr>
                            <td>{{ $log->created_at }}</td>
                            <td>{{ $log->audience_name }}</td>
                            <td class="text-capitalize">{{ str_replace('_', ' ', $log->mode) }}</td>
                            <td class="text-capitalize">{{ str_replace('_', ' ', $log->status) }}</td>
                            <td class="text-center">{{ $log->eligible_count }}</td>
                            <td class="text-center">{{ $log->add_count }}</td>
                            <td class="text-center">{{ $log->remove_count }}</td>
                            <td class="text-center">{{ $log->skipped_count }}</td>
                            <td><code>{{ $log->checksum ? substr($log->checksum, 0, 16) . '...' : '' }}</code></td>
                            <td>{{ $log->expires_at?->toDateTimeString() }}</td>
                            <td style="min-width: 180px; white-space: normal;">
                                @if(data_get($log->meta_response, 'add_acceptance'))
                                    <small class="d-block">Test: {{ data_get($log->meta_response, 'add_acceptance.received_count', 0) }} received / {{ data_get($log->meta_response, 'add_acceptance.invalid_count', 0) }} invalid</small>
                                @endif
                                @if(data_get($log->meta_response, 'cleanup_acceptance'))
                                    <small class="d-block">Cleanup: {{ data_get($log->meta_response, 'cleanup_acceptance.received_count', 0) }} received / {{ data_get($log->meta_response, 'cleanup_acceptance.invalid_count', 0) }} invalid</small>
                                @endif
                                @if(data_get($log->meta_response, 'acceptance.add'))
                                    <small class="d-block">Add: {{ data_get($log->meta_response, 'acceptance.add.received_count', 0) }} received / {{ data_get($log->meta_response, 'acceptance.add.invalid_count', 0) }} invalid</small>
                                @endif
                                @if(data_get($log->meta_response, 'acceptance.remove'))
                                    <small class="d-block">Remove: {{ data_get($log->meta_response, 'acceptance.remove.received_count', 0) }} received / {{ data_get($log->meta_response, 'acceptance.remove.invalid_count', 0) }} invalid</small>
                                @endif
                            </td>
                            <td style="min-width: 260px; white-space: normal;">
                                <div>{{ $log->error_message }}</div>
                                @if($log->meta_http_status || $log->meta_error_code || $log->meta_error_subcode || $log->meta_trace_id)
                                    <small class="text-muted">
                                        HTTP {{ $log->meta_http_status ?? 'n/a' }} |
                                        Code {{ $log->meta_error_code ?? 'n/a' }} |
                                        Subcode {{ $log->meta_error_subcode ?? 'n/a' }} |
                                        Trace {{ $log->meta_trace_id ?? 'n/a' }}
                                    </small>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="12" class="text-center py-4">{{ translate('No sync log found') }}</td>
                        </tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection

@push('script_2')
    <script>
        "use strict";

        $('#quality-check-all').on('change', function () {
            $('.quality-row-check').prop('checked', this.checked);
        });

        $('.selected-sync-button').on('click', function () {
            $('#selected-audience-key').val($(this).data('audience-key'));
        });

        $('.meta-exclusion-button').on('click', function () {
            $('#meta-exclusion-metric-key').val($(this).data('metric-key'));
            $('#meta-exclusion-customer-name').text($(this).data('customer-name'));
            $('#customer-quality-exclusion-modal').modal('show');
        });
    </script>
@endpush
