@php $isConnected = $integration && $integration->isConnected(); $tabs = [ 'overview' => 'Overview', 'orders' => 'Orders', 'products' => 'Products', 'offers' => 'Send Offer', 'customers' => 'Customers', 'events' => 'Automations', 'analytics' => 'Analytics', 'invoices' => 'Invoices', 'logs' => 'Activity', 'settings' => 'Settings', ]; $activeTab = array_key_exists($activeTab ?? 'overview', $tabs) ? $activeTab : 'overview'; $currency = $currency ?? ($integration?->shop_currency ?? 'USD'); // Only dashboardData() supplies $eventsByType, and the controller merges // that in ONLY when the store is connected. This @php block runs on EVERY // render, including the not-connected screen, so the $testable filter // below blew up with "Undefined variable $eventsByType" and 500'd the // whole page. The `?? []` inside that closure could never save it: a // `use (...)` clause is bound when the closure is CREATED, so the // undefined read happens first. Default it here instead. $eventsByType = $eventsByType ?? collect(); // Automation labels + the list the merchant can test right now (active + // a template chosen). Computed here — not inside the Automations tab — // because the Send-test-order modal renders outside that tab and must // work on every tab. $autoNames = [ 'orders/create' => 'Order confirmation', 'orders/paid' => 'Payment received', 'orders/fulfilled' => 'Shipped / Out for delivery', 'order/delivered' => 'Delivered', 'orders/cancelled' => 'Order cancelled', 'refunds/create' => 'Refund issued', 'orders/updated' => 'Order updated', 'checkouts/create' => 'Abandoned cart · step 1', 'cart/step2' => 'Abandoned cart · step 2', 'cart/step3' => 'Abandoned cart · step 3', 'cod/confirm' => 'COD order confirmation', 'cod/prepaid' => 'COD → Prepaid offer', 'stock/back' => 'Back-in-stock alert', 'customers/create' => 'Welcome new customer', 'customers/update' => 'Customer updated', 'products/update' => 'Product updated', ]; $testable = collect(array_keys($autoNames)) ->filter(function ($t) use ($eventsByType) { $e = ($eventsByType ?? [])[$t] ?? null; return $e && $e->is_active && $e->template_id; }) ->values(); @endphp @if (!$isConnected) {{-- ════════════════════════════════════════════════════════════ NOT CONNECTED — match the /connect page chrome: sidebar (logo + setup steps + help) + main (title + form + FAQ). ════════════════════════════════════════════════════════════ --}}
{{ __('Integrations') }} / {{ __('Shopify') }}

{{ __('Connect') }} {{ __('Shopify') }}

{{ __('Connect your Shopify store so order, fulfilment, refund, and cart events automatically trigger WhatsApp messages — and the dashboard shows live order/product/customer counts.') }}

@if (session('error'))
{{ session('error') }}
@endif @if (isset($errors) && $errors->any())
@foreach ($errors->all() as $e)
{{ $e }}
@endforeach
@endif {{-- ── Use your own Shopify app (self-serve BYO — owner only) ── The workspace owner pastes their OWN Shopify app's API key + secret and connects through their own app: no admin config or approval. Members don't see the keys. --}} @if (!empty($shopifyIsOwner) && !empty($shopifyManualAllowed))
{{ __('Your Shopify app') }}
{{ !empty($shopifyOwnApp) ? __('Connecting through your own Shopify app') : __('Connect with your own Shopify app') }}
{{ !empty($shopifyOwnApp) ? __('keys saved') : __('not set') }}
@if (!$appEnabled)

{{ __('Create a Shopify app in your Partner dashboard and paste its API key + secret here, then enter your store domain below. No approval needed — you use your own app.') }}

@endif
@csrf
{{ __('In your Shopify app, add this exact Allowed redirection URL:') }}
{{ $shopifyRedirectUri }}
{{-- In-app step-by-step: where to get the keys. --}}
{{ __('Where do I get these keys?') }}
  1. {{ __('Open') }} partners.shopify.com → {{ __('Apps → Create app → Create app manually.') }}
  2. {{ __('In the app: Configuration → set the Allowed redirection URL to the URI shown above.') }}
  3. {{ __('Open API access / Overview → copy the Client ID (API key) and Client secret (API secret key).') }}
  4. {{ __('Paste them here and Save. To connect your own store, install the app on it once from the Partner dashboard (Test your app → select store).') }}
@if (!empty($shopifyOwnApp))
@csrf
@endif
@endif @if (!$appEnabled) {{-- No Shopify app yet (neither this workspace's own nor a platform one). --}}
{{ __("Add your Shopify app to start") }}

@if (!empty($shopifyManualAllowed) && !empty($shopifyIsOwner)) {{ __("Enter your Shopify app's API key and secret in the panel above, then the store-connect form will activate.") }} @elseif (!empty($shopifyManualAllowed)) {{ __('Ask the workspace owner to add the Shopify app keys on this page, then you can connect a store.') }} @else {{ __("Shopify isn't available for this workspace yet.") }} @endif

@else
{{ __('Step 2') }}

{{ __('Store domain') }}

@csrf
.myshopify.com

{{ __("Just the store handle — or paste the full URL, we'll normalise it.") }}

{{ __('Webhook URL · auto-configured after connect') }}
{{ url('/shopify/webhook/{webhook_secret}') }}
{{ __('Cancel') }}
@endif
@else {{-- ════════════════════════════════════════════════════════════ CONNECTED — original sidebar + main dashboard (preserved). ════════════════════════════════════════════════════════════ --}} @if (session('success'))
{{ session('success') }}
@endif @if (session('error'))
{{ session('error') }}
@endif {{-- Live-connection failure. Everything on this page is read straight from Shopify, so when Shopify refuses a call there are no numbers to show — say exactly what Shopify returned and how to fix it, rather than falling back to a stale snapshot that looks healthy. --}} @if (!empty($shopifyError))
{{ $shopifyError['title'] }} HTTP {{ $shopifyError['status'] }} · {{ $shopifyError['resource'] }}

{{ $shopifyError['cause'] }}

{{ __('How to fix it') }}
    @foreach ($shopifyError['fix'] as $i => $step)
  1. {{ $i + 1 }} {{ $step }}
  2. @endforeach

{{ __('Figures below read 0 because Shopify would not return them — this is not an empty store.') }}

@endif
{{ __('Integrations') }} / {{ __('Shopify') }} / {{ $tabs[$activeTab] }}

{{ $integration->store_name ?: $integration->store_url }} {{ strtolower($tabs[$activeTab]) }}

@switch($activeTab) @case('overview') Live snapshot of your store, synced from Shopify. @break @case('orders') Orders synced from Shopify. @break @case('products') Browse your synced catalogue — send any product or push an offer over WhatsApp. @break @case('offers') Pick products + a coupon, choose a customer segment, and broadcast the offer over WhatsApp. @break @case('customers') Customers synced from Shopify into your contacts. @break @case('events') Marketing automations — toggle one on, pick a template, and it fires on the matching store event. @break @case('analytics') Revenue, order trend and message performance for this store. @break @case('logs') Webhook delivery log for this store. @break @case('settings') Manage the connection — re-sync, view scopes, or disconnect. @break @endswitch

@switch($activeTab) @case('invoices') @include('user.invoices._panel', ['panelSource' => 'shopify']) @break @case('overview')
{{ __('Revenue (recent)') }}
{{ $currency }} {{ number_format($revenue30d, 2) }}
{{ __('across recent synced orders') }}
{{ __('Orders total') }}
{{ number_format($counts['orders'] ?? 0) }}
{{ __('from Shopify counts API') }}
{{ __('Products') }}
{{ number_format($counts['products'] ?? 0) }}
{{ __('live catalog size') }}
{{ __('Customers') }}
{{ number_format($counts['customers'] ?? 0) }}
{{ $activeEvents }} {{ __('active automations') }}

{{ __('Recent orders') }}

{{ __('View all →') }}
@forelse (collect($orders)->take(5) as $o) @php $cust = $o['customer'] ?? []; $name = trim( ($cust['first_name'] ?? '') . ' ' . ($cust['last_name'] ?? ''), ) ?: $o['email'] ?? '—'; @endphp
{{ $o['name'] ?? '#' . ($o['order_number'] ?? '?') }}
{{ $name }}
{{ $o['currency'] ?? $currency }} {{ number_format((float) ($o['total_price'] ?? 0), 2) }}
{{ ucfirst((string) ($o['financial_status'] ?? '—')) }}
@empty
{{ __('No orders fetched yet. Hit') }} {{ __('Sync now') }}.
@endforelse

{{ __('Recent webhook activity') }}

{{ __('View all →') }}
@forelse ($recentLogs->take(6) as $log) @php $statusCss = match ($log->status) { 'processed', 'sent' => 'bg-wa-green/15 text-wa-deep', 'failed' => 'bg-accent-coral/15 text-accent-coral', 'skipped' => 'bg-paper-100 text-ink-700', default => 'bg-accent-amber/15 text-[#8B5A14]', }; @endphp
{{ $log->event_type }}
{{ $log->created_at?->diffForHumans() }}
{{ $log->status }}
@empty
{{ __('No webhook events received yet.') }}
@endforelse
@break @case('orders')
@forelse ($orders as $o) @php $cust = $o['customer'] ?? []; $name = trim( ($cust['first_name'] ?? '') . ' ' . ($cust['last_name'] ?? ''), ) ?: $o['email'] ?? '—'; // Same source + normalization as ShopifyController::resolveRecipient $rawPhone = $cust['phone'] ?? ($o['phone'] ?? ($o['shipping_address']['phone'] ?? ($o['billing_address']['phone'] ?? null))); $phoneIso = $o['shipping_address']['country_code'] ?? ($o['billing_address']['country_code'] ?? ($cust['default_address']['country_code'] ?? null)); $phoneE164 = $rawPhone ? \App\Support\Woo\WooPhone::e164($rawPhone, $phoneIso) : null; @endphp @empty @endforelse
{{ __('Order') }} {{ __('Customer') }} {{ __('Phone') }} {{ __('Status') }} {{ __('Total') }} {{ __('Placed') }}
{{ $o['name'] ?? '#' . ($o['order_number'] ?? '?') }} {{ $name }} @if ($phoneE164) +{{ $phoneE164 }} @else — @endif {{ ucfirst((string) ($o['financial_status'] ?? '—')) }} {{ $o['currency'] ?? $currency }} {{ number_format((float) ($o['total_price'] ?? 0), 2) }} {{ \Carbon\Carbon::parse($o['created_at'] ?? null)->diffForHumans() }}
{{ __('No orders found.') }}
@break @case('products') @php $brands = collect($products)->pluck('vendor')->filter()->unique()->values()->take(8); // Reusable product-card renderer (closure) — storefront style. $card = function ($p) use ($currency) { $img = $p['image_url'] ?? null; $price = (float) ($p['price'] ?? 0); $cmp = $p['compare_price'] ?? null; $off = (int) ($p['discount_pct'] ?? 0); $json = e( json_encode([ 'id' => $p['id'], 'title' => $p['title'], 'price' => $price, 'image' => $img, 'url' => $p['product_url'] ?? '', ]), ); $title = e($p['title'] ?? '—'); $vendor = e($p['vendor'] ?? ''); $tAttr = e(strtolower($p['title'] ?? '')); $bAttr = e(strtolower($p['vendor'] ?? '')); $priceFmt = $currency . ' ' . number_format($price, 2); $imgHtml = $img ? '' : '
no image
'; $badge = $off > 0 ? 'SAVE ' . $off . '%' : ''; $cmpHtml = $cmp ? '' . $currency . ' ' . number_format((float) $cmp, 2) . '' : ''; return '
' . '
' . $imgHtml . $badge . '
' . '
' . '
' . $title . '
' . '
' . $vendor . '
' . '
' . $priceFmt . '' . $cmpHtml . '
' . '
' . '' . '' . '
'; }; @endphp {{-- Hero search --}}
{{-- Brand chips --}} @if ($brands->isNotEmpty())
@foreach ($brands as $b) @endforeach
@endif {{-- Special offers --}} @if (!empty($offers))

{{ __('Special offers') }}

{{ __('Send a catalog →') }}
@foreach ($offers as $p) {!! $card($p) !!} @endforeach
@endif {{-- New arrivals --}} @if (!empty($newArrivals))

{{ __('New arrivals') }}

@foreach ($newArrivals as $p) {!! $card($p) !!} @endforeach
@endif {{-- All products / popular --}}

{{ __('All products') }}

@forelse ($products as $p) {!! $card($p) !!} @empty
{{ __('No products yet. Connect a store or hit') }} {{ __('Sync now') }}.
@endforelse
@break @case('offers')
@csrf {{-- LEFT: product picker --}}

{{ __('Choose products') }}

0 {{ __('selected') }}
@if (empty($products))
{{ __('No products synced yet.') }}
@else
@foreach ($products as $p) @endforeach
@endif
{{-- RIGHT: offer settings --}}
{{-- Win-back lapsed customers (one-click, no schedule needed) --}}
@csrf

{{ __('Smart segment broadcast') }}

{{ __('Target customers from order history — recency (win-back), order count and total spend (VIPs). Skips opted-out contacts.') }}

@break @case('customers')
@forelse ($customers as $c) @empty @endforelse
{{ __('Name') }} {{ __('Email') }} {{ __('Phone') }} {{ __('Orders') }} {{ __('Spent') }}
{{ trim(($c['first_name'] ?? '') . ' ' . ($c['last_name'] ?? '')) ?: '—' }} {{ $c['email'] ?? '—' }} {{ $c['phone'] ?? '—' }} {{ number_format((int) ($c['orders_count'] ?? 0)) }} {{ $currency }} {{ number_format((float) ($c['total_spent'] ?? 0), 2) }}
{{ __('No customers fetched yet.') }}
@break @case('events') @php // Friendly automation metadata per Shopify webhook topic. The // app/uninstalled cleanup hook is intentionally not shown. $AUTO = [ 'orders/create' => [ 'Order confirmation', 'Thank the customer the moment they place an order.', 'C', ], 'orders/paid' => ['Payment received', 'Confirm once payment has cleared.', 'C'], 'orders/fulfilled' => [ 'Shipped / Out for delivery', 'Send a dispatch note — use {{ tracking_url }} for the live tracking link.', 'C', ], 'order/delivered' => [ 'Delivered', 'Confirm delivery (asks for a review if your template does). Fires when the courier marks it delivered.', 'C', ], 'orders/cancelled' => [ 'Order cancelled', 'Let the customer know an order was cancelled.', 'C', ], 'refunds/create' => ['Refund issued', 'Confirm a refund has been processed.', 'C'], 'orders/updated' => [ 'Order updated', 'Fire on any change to an existing order.', 'C', ], 'checkouts/create' => [ 'Abandoned cart · step 1', 'Fires right after a checkout is abandoned — include {{ checkout_url }} to bring them back.', 'R', ], 'cart/step2' => [ 'Abandoned cart · step 2', 'Scheduled follow-up (set the delay, e.g. 1 hour). Auto-cancels if they buy.', 'R', ], 'cart/step3' => [ 'Abandoned cart · step 3', 'Final nudge (e.g. 24 hours) — add a coupon in the template to close the sale.', 'R', ], 'cod/confirm' => [ 'COD order confirmation', 'Ask cash-on-delivery customers to confirm with a Yes/No reply — cuts fake orders & returns (RTO).', 'R', ], 'cod/prepaid' => [ 'COD → Prepaid offer', 'Nudge COD customers to pay online now (use {{ order_url }} + a discount in the template) — fewer returns, faster cash.', 'R', ], 'stock/back' => [ 'Back-in-stock alert', 'Customers who message about a sold-out item get notified automatically when it is restocked.', 'R', ], 'customers/create' => [ 'Welcome new customer', 'Greet a first-time customer warmly.', 'M', ], 'customers/update' => [ 'Customer updated', 'Fire when a customer profile changes.', 'M', ], 'products/update' => [ 'Product updated', 'Internal trigger on price / stock change.', 'M', ], ]; $groups = [ 'C' => [ 'Order lifecycle', 'Transactional updates — fire automatically on store events.', ], 'R' => ['Revenue recovery', 'Bring back lost sales.'], 'M' => ['Lifecycle marketing', 'Grow and retain customers.'], ]; $shown = collect(array_keys($AUTO)); @endphp

{{ __('Send yourself a dummy order to confirm a live automation actually reaches WhatsApp — it runs through the exact same path a real Shopify order does.') }}

@csrf @foreach ($groups as $gKey => $g) @php $topicsInGroup = $shown->filter(fn ($t) => $AUTO[$t][2] === $gKey); @endphp @if ($topicsInGroup->isNotEmpty())

{{ $g[0] }}

{{ $g[1] }}
@foreach ($topicsInGroup as $topic) @php $ev = $eventsByType[$topic] ?? null; $active = (bool) $ev?->is_active; $tplId = $ev?->template_id; $sendTo = $ev?->send_to ?? 'customer'; // Multiple admin numbers (new) fall back to the legacy single. $adminNums = (string) ($ev?->admin_numbers ?: $ev?->admin_number ?: ''); $adminDifferent = (bool) ($ev?->admin_template_id); $adminTplId = $ev?->admin_template_id; $showAdmin = in_array($sendTo, ['admin', 'both'], true); $delay = $ev?->delay_seconds ?? 0; $sentCount = (int) ($logsByEvent[$topic] ?? 0); [$name, $desc] = $AUTO[$topic]; @endphp
{{ $name }}
{{ $desc }} · {{ $topic }}
{{ $sentCount }} {{ __('fired') }}
{{ __('Template') }}
{{ __('Send to') }}
{{ __('Delay') }}
{{-- Admin notification — multiple numbers + an optional different message. Shown only when Send-to is Admin/Both. --}}
{{ __('Admin number(s)') }}
{{ __('The admin message is sent to every number listed. Use full international numbers.') }}
{{ __('Admin template') }}
@endforeach
@endif @endforeach
@break @case('analytics') @php $a = $analytics ?? ['revenue_total'=>0,'orders_total'=>0,'aov'=>0,'messages_sent'=>0,'offers_sent'=>0,'trend'=>[],'trend_max'=>1]; @endphp {{-- KPI strip --}}
{{ __('Revenue') }}
{{ $currency }} {{ number_format($a['revenue_total'], 0) }}
{{ __('Orders') }}
{{ number_format($a['orders_total']) }}
{{ __('Avg order') }}
{{ $currency }} {{ number_format($a['aov'], 0) }}
{{ __('Messages sent') }}
{{ number_format($a['messages_sent']) }}
{{ __('Offers sent') }}
{{ number_format($a['offers_sent']) }}
{{-- Impact / ROI — real attributable numbers --}}
{{ __('COD revenue protected') }}
{{ $currency }} {{ number_format($a['cod_protected'] ?? 0, 0) }}
{{ number_format($a['cod_confirmed'] ?? 0) }} {{ __('COD orders confirmed') }}
{{ __('RTO avoided') }}
{{ $currency }} {{ number_format($a['rto_avoided'] ?? 0, 0) }}
{{ number_format($a['cod_cancelled'] ?? 0) }} {{ __('fake/COD orders stopped') }}
{{ __('Recovery messages') }}
{{ number_format($a['recovery_sends'] ?? 0) }}
{{ __('cart / offer / win-back / stock') }}
{{ __('Avg order value') }}
{{ $currency }} {{ number_format($a['aov'] ?? 0, 0) }}
{{-- Revenue trend (dependency-free CSS bars) --}}

{{ __('Revenue · last 14 days') }}

@foreach ($a['trend'] as $t) @php $h = (int) max(3, round(($t['value'] / $a['trend_max']) * 100)); @endphp
{{ $t['label'] }}
@endforeach
{{-- Automation performance --}}

{{ __('Automation performance') }}

@forelse ($logsByEvent as $event => $n) @empty @endforelse
{{ __('Event') }} {{ __('Fired') }}
{{ $event }} {{ number_format($n) }}
{{ __('No automation activity yet.') }}
@break @case('logs')
@foreach (['processed' => 'Processed', 'sent' => 'Sent', 'skipped' => 'Skipped', 'failed' => 'Failed'] as $k => $label) @php $n = (int) ($logsByStatus[$k] ?? 0); @endphp
{{ $label }}
{{ number_format($n) }}
@endforeach
@forelse ($recentLogs as $log) @php $statusCss = match ($log->status) { 'processed', 'sent' => 'bg-wa-green/15 text-wa-deep', 'failed' => 'bg-accent-coral/15 text-accent-coral', 'skipped' => 'bg-paper-100 text-ink-700', default => 'bg-accent-amber/15 text-[#8B5A14]', }; @endphp @empty @endforelse
{{ __('Event') }} {{ __('Recipient') }} {{ __('Status') }} {{ __('When') }}
{{ $log->event_type }} {{ $log->recipient ?? '—' }} {{ $log->status }} {{ $log->created_at?->diffForHumans() }}
{{ __('No webhook events have arrived for this store yet.') }}
@break @case('settings')
{{ __('Store URL') }}
{{ $integration->store_url }}
{{ __('Connected at') }}
{{ $integration->connected_at?->format('M d, Y H:i') ?? '—' }}
{{ __('Last verified') }}
{{ $integration->last_verified_at?->diffForHumans() ?? '—' }}
{{ __('Scopes granted') }}
{{ $integration->scopes ?: '—' }}
{{ __('Webhook URL') }}
{{ url('/shopify/webhook/' . $integration->webhook_secret) }}
@php $webhookCount = is_array($integration->metadata['webhook_ids'] ?? null) ? count($integration->metadata['webhook_ids']) : 0; @endphp
{{ __('Registered webhooks') }}
{{ $webhookCount }} active subscription{{ $webhookCount === 1 ? '' : 's' }}
{{-- Chat widget on the storefront — inject the WaDesk widget onto the Shopify store so visitors chat (AI can reply) into the inbox, toggled here. Uses a Shopify ScriptTag under the hood. --}}

{{ __('Chat widget on your store') }}

{{ __('Show your :brand chat widget on your Shopify storefront. Visitors chat from any page, your AI can reply, and every conversation lands in the team inbox — same as your normal website widget.', ['brand' => (function_exists('brand_name') ? brand_name() : 'your')]) }}

{{ !empty($widgetEnabled) ? __('live on store') : __('off') }}
@error('widget')
{{ $message }}
@enderror @if (($chatWidgets ?? collect())->isEmpty())
{{ __('You have no active chat widget yet. Create one in') }} {{ __('Chat Widget') }}, {{ __('then come back and turn it on here.') }}
@else
@csrf
{{ __('Placed instantly — no theme editing.') }}

{{ __('If it says a permission is needed, Disconnect and reconnect the store once (a new scope is required to place the widget), then enable again.') }}

@endif
@break @endswitch
{{-- Send-test-order modal — fires a dummy order through the real automation path. --}} @endif