@extends('layouts.admin.app')

@section('title', translate('Meta Ads Delivered Performance'))

@section('content')
    @php
        $money = fn ($value) => \App\CentralLogics\Helpers::format_currency((float) $value);
        $roas = fn ($value) => $value === null ? translate('N/A') : number_format((float) $value, 2) . 'x';
        $safetyRows = collect($safety_audit?->rows ?? [])
            ->sortBy(fn ($row) => data_get($row, 'risk_excluded') ? 1 : 0)
            ->take(100);
    @endphp

    <div class="content container-fluid">
        <div class="page-header d-flex flex-wrap justify-content-between align-items-center">
            <h1 class="page-header-title mb-2">
                <span class="page-header-icon"><i class="tio-chart-line-up"></i></span>
                <span>{{ translate('Meta Ads Delivered Performance') }}</span>
            </h1>
            <div class="d-flex flex-wrap">
                <form action="{{ route('admin.report.meta-ads-performance.safety-audit') }}"
                      method="post" class="mb-2 mr-2">
                    @csrf
                    <button type="submit" class="btn btn-outline-secondary">
                        <i class="tio-shield"></i>
                        {{ translate('Audit Targeting') }}
                    </button>
                </form>
                <form action="{{ route('admin.report.meta-ads-performance.sync') }}" method="post" class="mb-2">
                    @csrf
                    <input type="hidden" name="from" value="{{ $filters['from'] }}">
                    <input type="hidden" name="to" value="{{ $filters['to'] }}">
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="tio-sync"></i>
                        {{ translate('Queue Meta Sync') }}
                    </button>
                </form>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-body">
                <form action="{{ route('admin.report.meta-ads-performance') }}" method="get">
                    <div class="row g-3 align-items-end">
                        <div class="col-md-4">
                            <label class="form-label">{{ translate('From') }}</label>
                            <input type="date" name="from" value="{{ $filters['from'] }}" class="form-control" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">{{ translate('To') }}</label>
                            <input type="date" name="to" value="{{ $filters['to'] }}" class="form-control" required>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn--primary btn-block">
                                <i class="tio-filter-list"></i>
                                {{ translate('Filter') }}
                            </button>
                        </div>
                        <div class="col-md-2">
                            <a href="{{ route('admin.report.meta-ads-performance') }}" class="btn btn--reset btn-block">
                                {{ translate('Reset') }}
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        @if($last_sync)
            <div class="alert {{ $last_sync->status === 'failed' ? 'alert-soft-danger' : 'alert-soft-info' }} mb-3">
                <strong>{{ translate('Last Meta Sync') }}:</strong>
                {{ ucfirst(str_replace('_', ' ', $last_sync->status)) }}
                <span class="mx-1">|</span>
                {{ $last_sync->date_from?->format('Y-m-d') }} - {{ $last_sync->date_to?->format('Y-m-d') }}
                <span class="mx-1">|</span>
                {{ translate('Ad rows') }}: {{ $last_sync->base_rows }}
                <span class="mx-1">|</span>
                {{ translate('Product rows') }}: {{ $last_sync->product_rows }}
                @if($last_sync->error_message)
                    <div class="mt-1 text-break">{{ $last_sync->error_message }}</div>
                @endif
            </div>
        @endif

        <div class="card mb-3">
            <div class="card-header border-0">
                <div>
                    <h4 class="card-title mb-1">{{ translate('Audience Exclusion Compliance') }}</h4>
                    <p class="text-muted mb-0">
                        {{ translate('Read-only audit. It does not edit the winning campaign or any Meta ad set.') }}
                    </p>
                </div>
            </div>
            @if(!$safety_audit)
                <div class="card-body text-center text-muted">
                    {{ translate('No targeting audit has been run yet') }}
                </div>
            @elseif($safety_audit->status === 'failed')
                <div class="card-body">
                    <div class="alert alert-soft-danger mb-0">
                        <strong>{{ translate('Targeting audit failed') }}</strong>
                        <div class="text-break">{{ $safety_audit->error_message }}</div>
                        @if($safety_audit->meta_error_code)
                            <div class="fs-12 mt-1">
                                {{ translate('Code') }}: {{ $safety_audit->meta_error_code }}
                                <span class="mx-1">|</span>
                                {{ translate('Subcode') }}: {{ $safety_audit->meta_error_subcode ?: translate('N/A') }}
                                <span class="mx-1">|</span>
                                {{ translate('Trace') }}: {{ $safety_audit->meta_trace_id ?: translate('N/A') }}
                            </div>
                        @endif
                    </div>
                </div>
            @else
                <div class="card-body border-bottom">
                    <div class="row g-3">
                        <div class="col-sm-6 col-xl-3">
                            <div class="text-muted">{{ translate('Ad Sets Audited') }}</div>
                            <strong>{{ $safety_audit->total_adsets }}</strong>
                        </div>
                        <div class="col-sm-6 col-xl-3">
                            <div class="text-muted">{{ translate('Risk Exclusion OK') }}</div>
                            <strong class="text-success">{{ $safety_audit->risk_compliant_count }}</strong>
                        </div>
                        <div class="col-sm-6 col-xl-3">
                            <div class="text-muted">{{ translate('Risk Exclusion Missing') }}</div>
                            <strong class="text-danger">{{ $safety_audit->risk_missing_count }}</strong>
                        </div>
                        <div class="col-sm-6 col-xl-3">
                            <div class="text-muted">{{ translate('Purchaser Exclusion Present') }}</div>
                            <strong>{{ $safety_audit->purchaser_excluded_count }}</strong>
                        </div>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-borderless table-thead-bordered table-nowrap card-table">
                        <thead class="thead-light">
                        <tr>
                            <th>{{ translate('Campaign') }}</th>
                            <th>{{ translate('Ad Set') }}</th>
                            <th>{{ translate('Delivery') }}</th>
                            <th>{{ translate('Risk Audience') }}</th>
                            <th>{{ translate('180-day Purchaser') }}</th>
                        </tr>
                        </thead>
                        <tbody>
                        @forelse($safetyRows as $row)
                            <tr>
                                <td>
                                    <strong>{{ data_get($row, 'campaign_name') }}</strong>
                                    <div class="text-muted fs-12">{{ data_get($row, 'campaign_id') }}</div>
                                </td>
                                <td>
                                    {{ data_get($row, 'adset_name') }}
                                    <div class="text-muted fs-12">{{ data_get($row, 'adset_id') }}</div>
                                </td>
                                <td>{{ data_get($row, 'adset_status') ?: translate('Unknown') }}</td>
                                <td>
                                    @if(data_get($row, 'risk_excluded'))
                                        <span class="badge badge-soft-success">{{ translate('Excluded') }}</span>
                                    @else
                                        <span class="badge badge-soft-danger">{{ translate('Missing') }}</span>
                                    @endif
                                </td>
                                <td>
                                    @if(data_get($row, 'purchaser_excluded'))
                                        <span class="badge badge-soft-success">{{ translate('Excluded') }}</span>
                                    @else
                                        <span class="badge badge-soft-warning">{{ translate('Not excluded') }}</span>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center py-4">
                                    {{ translate('No Meta ad sets returned by the audit') }}
                                </td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            @endif
        </div>

        <div class="row g-3 mb-3">
            <div class="col-sm-6 col-xl-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="text-muted">{{ translate('Meta Spend') }}</div>
                        <h3 class="mb-0">{{ $money($summary['spend']) }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xl-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="text-muted">{{ translate('Purchase ROAS') }}</div>
                        <h3 class="mb-0">{{ $roas($summary['purchase_roas']) }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xl-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="text-muted">{{ translate('Delivered Revenue') }}</div>
                        <h3 class="mb-0">{{ $money($summary['delivered_revenue']) }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xl-3">
                <div class="card h-100 border border-success">
                    <div class="card-body">
                        <div class="text-muted">{{ translate('Delivered ROAS') }}</div>
                        <h3 class="mb-0 text-success">{{ $roas($summary['delivered_roas']) }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xl-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="text-muted">{{ translate('Cost per Delivered Order') }}</div>
                        <h3 class="mb-0">
                            {{ $summary['cost_per_delivered_order'] === null ? translate('N/A') : $money($summary['cost_per_delivered_order']) }}
                        </h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xl-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="text-muted">{{ translate('Return-adjusted ROAS') }}</div>
                        <h3 class="mb-0">{{ $roas($summary['return_adjusted_roas']) }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xl-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="text-muted">{{ translate('Profit ROAS') }}</div>
                        <h3 class="mb-0">{{ $roas($summary['profit_roas']) }}</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xl-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="text-muted">{{ translate('Delivered / Returned') }}</div>
                        <h3 class="mb-0">{{ $summary['delivered_orders'] }} / {{ $summary['returned_orders'] }}</h3>
                        <div class="text-muted fs-12">{{ number_format($summary['return_rate'], 2) }}%</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="alert alert-soft-secondary mb-3">
            {{ translate('Attributed Orders') }}:
            <strong>{{ $attribution_coverage['attributed_orders'] }}</strong>
            / {{ $attribution_coverage['total_orders'] }}
            <span class="mx-1">|</span>
            {{ translate('Products missing purchase cost') }}:
            <strong>{{ $missing_purchase_cost_items }}</strong>
        </div>

        <div class="card mb-3">
            <div class="card-header border-0">
                <div>
                    <h4 class="card-title mb-1">{{ translate('Catalog Product Rules') }}</h4>
                    <p class="text-muted mb-0">
                        {{ translate('Rules update feed labels for new product sets. They do not remove products from the feed or edit the current winning ad.') }}
                    </p>
                </div>
            </div>
            <div class="card-body">
                <form action="{{ route('admin.report.meta-ads-performance.rules.update') }}" method="post">
                    @csrf
                    <div class="row g-3 align-items-end">
                        <div class="col-sm-6 col-xl-2">
                            <label class="form-label d-block">{{ translate('Auto Exclude') }}</label>
                            <label class="switcher">
                                <input type="checkbox" name="auto_exclude_enabled" value="1"
                                       class="switcher_input" @checked($rule_settings->auto_exclude_enabled)>
                                <span class="switcher_control"></span>
                            </label>
                        </div>
                        <div class="col-sm-6 col-xl-2">
                            <label class="form-label d-block">{{ translate('Auto Restore') }}</label>
                            <label class="switcher">
                                <input type="checkbox" name="auto_restore_enabled" value="1"
                                       class="switcher_input" @checked($rule_settings->auto_restore_enabled)>
                                <span class="switcher_control"></span>
                            </label>
                        </div>
                        <div class="col-sm-6 col-xl-2">
                            <label class="form-label">{{ translate('Min Final Orders') }}</label>
                            <input type="number" name="minimum_final_orders" min="1" max="1000"
                                   value="{{ $rule_settings->minimum_final_orders }}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 col-xl-2">
                            <label class="form-label">{{ translate('Max Return Rate') }} (%)</label>
                            <input type="number" name="maximum_return_rate" min="0" max="100" step="0.01"
                                   value="{{ $rule_settings->maximum_return_rate }}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 col-xl-2">
                            <label class="form-label">{{ translate('Min Profit') }}</label>
                            <input type="number" name="minimum_profit" step="0.01"
                                   value="{{ $rule_settings->minimum_profit }}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 col-xl-2">
                            <label class="form-label">{{ translate('High Profit Min') }}</label>
                            <input type="number" name="high_profit_minimum_profit" step="0.01"
                                   value="{{ $rule_settings->high_profit_minimum_profit }}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 col-xl-2">
                            <label class="form-label">{{ translate('High Profit ROAS') }}</label>
                            <input type="number" name="high_profit_minimum_roas" min="0" step="0.01"
                                   value="{{ $rule_settings->high_profit_minimum_roas }}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 col-xl-2">
                            <button type="submit" class="btn btn--primary btn-block">
                                <i class="tio-save"></i>
                                {{ translate('Save Rules') }}
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        @include('admin-views.report.partials._meta-entity-performance-table', [
            'entityRows' => $campaign_rows,
            'entityTitle' => 'Campaign Performance',
            'entityLabel' => 'Campaign',
            'entityNameKey' => 'campaign_name',
            'entityIdKey' => 'campaign_id',
            'emptyMessage' => 'No Meta campaign insight data found',
        ])

        @include('admin-views.report.partials._meta-entity-performance-table', [
            'entityRows' => $adset_rows,
            'entityTitle' => 'Ad Set Performance',
            'entityLabel' => 'Ad Set',
            'entityNameKey' => 'adset_name',
            'entityIdKey' => 'adset_id',
            'emptyMessage' => 'No Meta ad set insight data found',
        ])

        @include('admin-views.report.partials._meta-entity-performance-table', [
            'entityRows' => $ad_rows,
            'entityTitle' => 'Ad Performance',
            'entityLabel' => 'Ad',
            'entityNameKey' => 'ad_name',
            'entityIdKey' => 'ad_id',
            'emptyMessage' => 'No Meta ad insight data found',
        ])

        <div class="card">
            <div class="card-header border-0">
                <h4 class="card-title">{{ translate('Product-wise Ad Performance') }}</h4>
            </div>
            <div class="table-responsive">
                <table class="table table-borderless table-thead-bordered table-nowrap card-table">
                    <thead class="thead-light">
                    <tr>
                        <th>{{ translate('Product') }}</th>
                        <th class="text-right">{{ translate('Spend') }}</th>
                        <th class="text-right">{{ translate('Clicks') }}</th>
                        <th class="text-right">{{ translate('Add to Cart') }}</th>
                        <th class="text-right">{{ translate('Purchase') }}</th>
                        <th class="text-right">{{ translate('Purchase ROAS') }}</th>
                        <th class="text-right">{{ translate('Delivered Orders') }}</th>
                        <th class="text-right">{{ translate('Cost / Delivered') }}</th>
                        <th class="text-right">{{ translate('Delivered Revenue') }}</th>
                        <th class="text-right">{{ translate('Delivered ROAS') }}</th>
                        <th class="text-right">{{ translate('Return Rate') }}</th>
                        <th class="text-right">{{ translate('Profit') }}</th>
                        <th class="text-right">{{ translate('Profit ROAS') }}</th>
                        <th>{{ translate('Ad Priority') }}</th>
                        <th>{{ translate('Catalog Status') }}</th>
                        <th>{{ translate('Action') }}</th>
                    </tr>
                    </thead>
                    <tbody>
                    @forelse($product_rows as $row)
                        @php($controlForm = 'meta-product-control-' . md5((string) $row['product_id']))
                        <tr>
                            <td>
                                <strong>{{ $row['product_name'] }}</strong>
                                <div class="text-muted fs-12">#{{ $row['product_id'] }}</div>
                            </td>
                            <td class="text-right">{{ $money($row['spend']) }}</td>
                            <td class="text-right">{{ number_format($row['clicks']) }}</td>
                            <td class="text-right">{{ number_format($row['add_to_cart'], 0) }}</td>
                            <td class="text-right">{{ number_format($row['purchases'], 0) }}</td>
                            <td class="text-right">{{ $roas($row['purchase_roas']) }}</td>
                            <td class="text-right">{{ $row['delivered_orders'] }}</td>
                            <td class="text-right">
                                {{ $row['cost_per_delivered_order'] === null
                                    ? translate('N/A')
                                    : $money($row['cost_per_delivered_order']) }}
                            </td>
                            <td class="text-right">{{ $money($row['delivered_revenue']) }}</td>
                            <td class="text-right font-weight-bold text-success">{{ $roas($row['delivered_roas']) }}</td>
                            <td class="text-right">{{ number_format($row['return_rate'], 2) }}%</td>
                            <td class="text-right">{{ $money($row['profit']) }}</td>
                            <td class="text-right">{{ $roas($row['profit_roas']) }}</td>
                            <td>
                                <select name="priority" class="form-control min-w-120"
                                        form="{{ $controlForm }}" @disabled(!$row['item_exists'])>
                                    <option value="high" @selected($row['meta_ad_priority'] === 'high')>
                                        {{ translate('High') }}
                                    </option>
                                    <option value="medium" @selected($row['meta_ad_priority'] === 'medium')>
                                        {{ translate('Medium') }}
                                    </option>
                                    <option value="low" @selected($row['meta_ad_priority'] === 'low')>
                                        {{ translate('Low') }}
                                    </option>
                                </select>
                            </td>
                            <td>
                                @if($row['meta_ads_excluded'])
                                    <span class="badge badge-soft-danger">
                                        {{ translate('Excluded') }}
                                        @if($row['meta_ads_exclusion_mode'])
                                            ({{ ucfirst($row['meta_ads_exclusion_mode']) }})
                                        @endif
                                    </span>
                                    @if($row['meta_ads_exclusion_reason'])
                                        <div class="text-muted fs-12 text-wrap mt-1" style="max-width: 220px">
                                            {{ $row['meta_ads_exclusion_reason'] }}
                                        </div>
                                    @endif
                                @elseif($row['meta_ads_high_profit'])
                                    <span class="badge badge-soft-success">{{ translate('High Profit') }}</span>
                                @elseif($row['meta_ad_priority'] === 'high')
                                    <span class="badge badge-soft-info">{{ translate('Best Seller') }}</span>
                                @else
                                    <span class="badge badge-soft-secondary">{{ translate('Standard') }}</span>
                                @endif
                            </td>
                            <td>
                                @if($row['item_exists'])
                                    <form id="{{ $controlForm }}"
                                          action="{{ route('admin.report.meta-ads-performance.products.update', ['item' => $row['product_id']]) }}"
                                          method="post" class="d-flex align-items-center">
                                        @csrf
                                        <label class="switcher mr-2 mb-0" title="{{ translate('Exclude from new Meta product sets') }}">
                                            <input type="checkbox" name="excluded" value="1"
                                                   class="switcher_input" @checked($row['meta_ads_excluded'])>
                                            <span class="switcher_control"></span>
                                        </label>
                                        <input type="text" name="exclusion_reason" maxlength="255"
                                               value="{{ $row['meta_ads_exclusion_reason'] }}"
                                               class="form-control mr-2 min-w-160"
                                               placeholder="{{ translate('Exclusion reason') }}">
                                        <button type="submit" class="btn btn-sm btn-outline-primary"
                                                title="{{ translate('Save product controls') }}">
                                            <i class="tio-save"></i>
                                        </button>
                                    </form>
                                @else
                                    <span class="text-muted">{{ translate('Catalog-only item') }}</span>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="16" class="text-center py-4">{{ translate('No product-level Meta insight data found') }}</td></tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection
