<?php

namespace App\Http\Controllers;

use App\Models\Campaign;
use App\Models\CampaignEvent;
use App\Models\ContactList;
use App\Models\SmtpConfig;
use App\Models\Tag;
use App\Models\Contact;
use App\Services\AutomationEngine;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AutomationController extends Controller
{
    public function index(Request $request): Response
    {
        $query = Campaign::query()
            ->where('type', 'automation')
            ->orderByDesc('updated_at')
            ->orderByDesc('id');

        if ($search = $request->input('search')) {
            $query->where('title', 'like', "%{$search}%");
        }

        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }

        $automations = $query->paginate(20)->withQueryString();

        return Inertia::render('Automation/Index', [
            'automations' => $automations->through(function ($a) {
                $nodes = $a->settings['nodes'] ?? [];
                $trigger = $a->settings['trigger'] ?? [];
                
                // Fetch dynamic trigger type
                $triggersList = $trigger['triggers'] ?? [];
                if (!empty($triggersList)) {
                    $triggerTypes = collect($triggersList)->map(fn($t) => $t['type'] ?? 'Unknown')->unique()->toArray();
                    $triggerType = implode(', ', $triggerTypes);
                } else {
                    $triggerType = $trigger['type'] ?? 'Unknown';
                }

                // Count enrolled contacts
                $enrolled = CampaignEvent::where('campaign_id', $a->id)
                    ->where('event_type', 'enrolled')
                    ->count();

                // Count completed contacts
                $completed = CampaignEvent::where('campaign_id', $a->id)
                    ->where('event_type', 'completed')
                    ->count();

                // Count active contacts
                $active = max(0, $enrolled - $completed);

                return [
                    'id'          => $a->id,
                    'title'       => $a->title,
                    'status'      => $a->status,
                    'trigger'     => $triggerType,
                    'nodes_count' => count($nodes),
                    'enrolled'    => $enrolled,
                    'active'      => $active,
                    'completed'   => $completed,
                    'created_at'  => $a->created_at->format('M d, Y'),
                    'updated_at'  => $a->updated_at->format('M d, Y'),
                ];
            }),
            'filters' => $request->only(['search', 'status']),
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'    => 'required|string|max:192',
            'template' => 'nullable|string|max:64',
        ]);

        $template = $data['template'] ?? null;
        $settings = $this->buildTemplateSettings($data['title'], $template);

        $automation = Campaign::create([
            'title'      => $data['title'],
            'type'       => 'automation',
            'status'     => 'draft',
            'created_by' => auth()->id(),
            'settings'   => $settings,
        ]);

        return redirect()->route('automation.edit', $automation)
            ->with('success', 'Automation created.');
    }

    public function edit(Campaign $automation): Response
    {
        abort_unless($automation->type === 'automation', 404);

        $lists = ContactList::orderBy('title')->get(['id', 'title']);
        $tags  = Tag::orderBy('title')->get(['id', 'title']);
        $defaultSmtp = SmtpConfig::where('is_default', true)->first();

        $campaigns = Campaign::where('type', 'campaign')
            ->orderByDesc('updated_at')
            ->get(['id', 'title', 'email_subject', 'email_pre_header', 'email_body', 'design_template', 'settings']);

        $smtpConfigs = SmtpConfig::orderBy('name')
            ->get(['id', 'name', 'from_name', 'from_email', 'is_default']);

        $nodeEvents = \App\Models\CampaignEvent::where('campaign_id', $automation->id)
            ->whereNotNull('node_id')
            ->with(['contact' => fn($q) => $q->withoutGlobalScopes()->select(['id', 'email', 'first_name', 'last_name'])])
            ->orderByDesc('id')
            ->get()
            ->map(fn($e) => [
                'id'          => $e->id,
                'node_id'     => $e->node_id,
                'event_type'  => $e->event_type,
                'reason'      => $e->reason,
                'contact'     => $e->contact ? [
                    'id'    => $e->contact->id,
                    'email' => $e->contact->email,
                    'name'  => trim($e->contact->first_name . ' ' . $e->contact->last_name),
                ] : null,
                'created_at'  => $e->created_at->toISOString(),
            ]);

        $webhooks = \App\Models\Webhook::withoutGlobalScopes()
            ->where(function ($q) {
                if (auth()->check()) {
                    $q->where('user_id', auth()->id())->orWhereNull('user_id');
                }
            })
            ->with(['lists:id,title,color', 'tags:id,title,color'])
            ->withCount('logs')
            ->latest()
            ->get()
            ->map(fn($w) => [
                'id'                   => $w->id,
                'name'                 => $w->name,
                'receive_url'          => $w->receiveUrl(),
                'has_secret'           => !empty($w->getRawOriginal('secret')),
                'default_status'       => $w->default_status,
                'duplicate_handling'   => $w->duplicate_handling,
                'success_redirect_url' => $w->success_redirect_url,
                'is_active'            => $w->is_active,
                'total_received'       => $w->total_received,
                'logs_count'           => $w->logs_count,
                'last_triggered_at'    => $w->last_triggered_at?->toISOString(),
                'lists'                => $w->lists,
                'tags'                 => $w->tags,
            ]);

        return Inertia::render('Automation/Create', [
            'automation' => [
                'id'       => $automation->id,
                'title'    => $automation->title,
                'status'   => $automation->status,
                'settings' => $automation->settings ?? $this->buildTemplateSettings($automation->title, null),
                'node_events' => $nodeEvents,
            ],
            'lists'         => $lists,
            'tags'          => $tags,
            'webhooks'      => $webhooks,
            'campaigns'     => $campaigns,
            'smtpConfigs'   => $smtpConfigs,
            'defaultSender' => $defaultSmtp ? [
                'profile'    => $defaultSmtp->name,
                'from_name'  => $defaultSmtp->from_name,
                'from_email' => $defaultSmtp->from_email,
            ] : null,
        ]);
    }

    public function update(Request $request, Campaign $automation): JsonResponse
    {
        abort_unless($automation->type === 'automation', 404);

        $data = $request->validate([
            'title'    => 'sometimes|string|max:192',
            'status'   => 'sometimes|string|in:draft,active,paused',
            'settings' => 'sometimes|array',
        ]);

        if (isset($data['title'])) {
            $automation->title = $data['title'];
        }

        if (isset($data['status'])) {
            $automation->status = $data['status'];
        }

        if (isset($data['settings'])) {
            $automation->settings = $data['settings'];
        }

        $automation->save();

        return response()->json([
            'success' => true,
            'automation' => [
                'id'       => $automation->id,
                'title'    => $automation->title,
                'status'   => $automation->status,
                'settings' => $automation->settings,
            ],
        ]);
    }

    public function destroy(Campaign $automation)
    {
        abort_unless($automation->type === 'automation', 404);
        $automation->delete();

        return redirect()->route('automation.index')
            ->with('success', 'Automation deleted.');
    }

    public function bulkDestroy(Request $request): JsonResponse
    {
        $ids = $request->validate([
            'ids'   => 'required|array',
            'ids.*' => 'integer',
        ])['ids'];

        Campaign::where('type', 'automation')
            ->whereIn('id', $ids)
            ->delete();

        return response()->json(['success' => true]);
    }

    public function testWebhook(Request $request): JsonResponse
    {
        $url = $request->input('url');
        $method = strtoupper($request->input('method', 'POST'));
        $payloadType = $request->input('payload_type', 'json');
        $payloadMode = $request->input('payload_mode', 'merged');
        $headersData = $request->input('headers', []);
        $paramsData = $request->input('params', []);

        if (empty($url)) {
            return response()->json(['success' => false, 'message' => 'URL is required.'], 422);
        }

        $headers = [];
        foreach ($headersData as $h) {
            if (!empty($h['key'])) {
                $headers[$h['key']] = $h['value'] ?? '';
            }
        }

        $customParams = [];
        foreach ($paramsData as $p) {
            if (!empty($p['key'])) {
                $customParams[$p['key']] = $p['value'] ?? '';
            }
        }

        $contactData = [
            'id' => 999999,
            'email' => 'test@example.com',
            'first_name' => 'John',
            'last_name' => 'Doe',
            'phone' => '+15551234567',
            'status' => 'subscribed',
            'contact_type' => 'lead',
            'total_points' => 100,
            'life_time_value' => 500.00,
            'timezone' => 'UTC',
        ];

        $payload = ($payloadMode === 'custom') ? $customParams : array_merge($contactData, $customParams);

        try {
            $client = \Illuminate\Support\Facades\Http::withHeaders($headers)->timeout(8);

            if ($method === 'GET') {
                $response = $client->get($url, $payload);
            } elseif ($method === 'PUT') {
                $response = ($payloadType === 'form') ? $client->asForm()->put($url, $payload) : $client->put($url, $payload);
            } else {
                $response = ($payloadType === 'form') ? $client->asForm()->post($url, $payload) : $client->post($url, $payload);
            }

            return response()->json([
                'success' => $response->successful(),
                'status' => $response->status(),
                'body' => mb_strimwidth($response->body(), 0, 1000, '...'),
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    // ── Template builders ──

    private function buildTemplateSettings(string $title, ?string $template): array
    {
        $base = [
            'trigger' => [
                'type'    => 'new_user_signup',
                'list_id' => null,
                'tag_id'  => null,
            ],
            'description'          => '',
            'subscription_status'  => 'subscribed',
            'run_on_unsubscribed'  => false,
            'exist_contact_action' => 'update',
            'nodes' => [],
            'edges' => [],
        ];

        $triggerId = $this->uid();

        $base['nodes'][] = [
            'id'     => $triggerId,
            'type'   => 'trigger',
            'title'  => $title,
            'sub'    => 'New User Sign Up',
            'config' => [],
        ];

        if ($template === 'inactive') {
            return $this->buildInactiveTemplate($base, $triggerId);
        }

        if ($template === 'reengagement') {
            return $this->buildReengagementTemplate($base, $triggerId);
        }

        // ── New templates ──────────────────────────────────────────────
        $newBuilders = [
            'welcome_new'        => 'buildWelcomeNewTemplate',
            'onboarding'         => 'buildOnboardingTemplate',
            'email_click_followup' => 'buildEmailClickFollowupTemplate',
            'upsell'             => 'buildUpsellTemplate',
            'recommend'          => 'buildRecommendTemplate',
            'feedback'           => 'buildFeedbackTemplate',
            'winback'            => 'buildWinbackTemplate',
            'cart_abandon'       => 'buildCartAbandonTemplate',
            'lead_nurture'       => 'buildLeadNurtureTemplate',
            'tag_nurture'        => 'buildTagNurtureTemplate',
            'birthday'           => 'buildBirthdayTemplate',
            'anniversary'        => 'buildAnniversaryTemplate',
        ];

        if ($template && isset($newBuilders[$template])) {
            $method = $newBuilders[$template];
            return $this->$method($base, $triggerId);
        }

        // Default: just trigger node
        return $base;
    }

    private function buildInactiveTemplate(array $base, string $triggerId): array
    {
        $condId  = $this->uid();
        $emailId = $this->uid();
        $waitId  = $this->uid();
        $email2  = $this->uid();
        $wait2   = $this->uid();
        $email3  = $this->uid();
        $tagId   = $this->uid();
        $endId   = $this->uid();

        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $condId, 'type' => 'condition', 'title' => 'Check Last Purchase Date', 'sub' => 'Matching 1 condition sets', 'config' => ['conditions' => [['field' => 'Last Purchase Date', 'operator' => 'is before', 'value' => 90, 'unit' => 'days ago']]]],
            ['id' => $emailId, 'type' => 'email', 'title' => 'Inactivity Reminder + New Arrivals', 'sub' => 'We Miss You! Come See What\'s New!', 'config' => ['subject' => 'We Miss You! Come See What\'s New!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $waitId, 'type' => 'wait', 'title' => 'Wait X Days/Hours', 'sub' => 'Wait 2 days', 'config' => ['value' => 2, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $email2, 'type' => 'email', 'title' => 'Reminder + Offer', 'sub' => 'There\'s So Much to Discover: 10% Off!', 'config' => ['subject' => 'There\'s So Much to Discover: 10% Off!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $wait2, 'type' => 'wait', 'title' => 'Wait X Days/Hours', 'sub' => 'Wait 2 days', 'config' => ['value' => 2, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $email3, 'type' => 'email', 'title' => 'FOMO', 'sub' => 'Last Chance! Your 10% Off is About to Expire', 'config' => ['subject' => 'Last Chance! Your 10% Off is About to Expire', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $tagId, 'type' => 'remove_tag', 'title' => 'Remove "Inactive Customer" Tag', 'sub' => 'Remove this contact from the selected Tags', 'config' => ['tag_ids' => []]],
            ['id' => $endId, 'type' => 'end', 'title' => 'End This Funnel Here', 'sub' => 'No further action will run once a contact hit this point', 'config' => []],
        ]);

        $base['edges'] = [
            ['source' => $triggerId, 'target' => $condId],
            ['source' => $condId, 'target' => $emailId, 'branch' => 'yes'],
            ['source' => $emailId, 'target' => $waitId],
            ['source' => $waitId, 'target' => $email2],
            ['source' => $email2, 'target' => $wait2],
            ['source' => $wait2, 'target' => $email3],
            ['source' => $condId, 'target' => $tagId, 'branch' => 'no'],
            ['source' => $tagId, 'target' => $endId],
        ];

        $base['trigger']['type'] = 'new_user_signup';
        $base['description'] = 'Recover your idle customers with a 3 step re-engagement sequence';

        return $base;
    }

    private function buildReengagementTemplate(array $base, string $triggerId): array
    {
        $emailId = $this->uid();
        $waitId  = $this->uid();
        $email2  = $this->uid();

        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $emailId, 'type' => 'email', 'title' => 'Re-engagement Email', 'sub' => 'We miss you!', 'config' => ['subject' => 'We miss you!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $waitId, 'type' => 'wait', 'title' => 'Wait X Days/Hours', 'sub' => 'Wait 3 days', 'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $email2, 'type' => 'email', 'title' => 'Final Reminder', 'sub' => 'Last chance to stay connected', 'config' => ['subject' => 'Last chance to stay connected', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);

        $base['edges'] = [
            ['source' => $triggerId, 'target' => $emailId],
            ['source' => $emailId, 'target' => $waitId],
            ['source' => $waitId, 'target' => $email2],
        ];

        $base['trigger']['type'] = 'tag_applied';
        $base['description'] = 'Easily keep your contacts engaged and identify inactive contacts like a pro!';

        return $base;
    }

    private function uid(): string
    {
        return 'n_' . bin2hex(random_bytes(6));
    }

    // ── New template builders ──────────────────────────────────────────

    /** welcome_new: Welcome New Subscribers */
    private function buildWelcomeNewTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $w1 = $this->uid(); $e2 = $this->uid(); $w2 = $this->uid(); $e3 = $this->uid();
        $base['trigger']['type'] = 'subscribes_to_list';
        $base['description'] = 'Automatically send a series of welcome emails to new subscribers.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1, 'type' => 'email', 'title' => 'Welcome Email', 'sub' => 'Welcome to the community!', 'config' => ['subject' => 'Welcome to the community!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w1, 'type' => 'wait', 'title' => 'Wait 2 Days', 'sub' => 'Wait 2 days', 'config' => ['value' => 2, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e2, 'type' => 'email', 'title' => 'Getting Started Guide', 'sub' => 'Here\'s how to get started', 'config' => ['subject' => 'Here\'s how to get started', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2, 'type' => 'wait', 'title' => 'Wait 3 Days', 'sub' => 'Wait 3 days', 'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e3, 'type' => 'email', 'title' => 'Social Proof Email', 'sub' => 'See what others are saying', 'config' => ['subject' => 'See what others are saying', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $w1],
            ['source' => $w1, 'target' => $e2],
            ['source' => $e2, 'target' => $w2],
            ['source' => $w2, 'target' => $e3],
        ];
        return $base;
    }

    /** onboarding: New User Onboarding */
    private function buildOnboardingTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $w1 = $this->uid(); $cond = $this->uid(); $e2 = $this->uid(); $w2 = $this->uid(); $e3 = $this->uid();
        $base['trigger']['type'] = 'new_user_signup';
        $base['description'] = 'A structured onboarding sequence that helps new users understand your product value.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1,   'type' => 'email',     'title' => 'Welcome & Account Setup', 'sub' => 'Let\'s set up your account', 'config' => ['subject' => 'Let\'s set up your account', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w1,   'type' => 'wait',      'title' => 'Wait 1 Day',              'sub' => 'Wait 1 day',               'config' => ['value' => 1, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $cond, 'type' => 'condition', 'title' => 'Has Completed Profile?',  'sub' => 'Matching 1 condition',     'config' => ['conditions' => [['field' => 'profile_complete', 'operator' => 'equals', 'value' => 'yes']]]],
            ['id' => $e2,   'type' => 'email',     'title' => 'Feature Highlight Email', 'sub' => 'Discover key features',   'config' => ['subject' => 'Discover key features', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2,   'type' => 'wait',      'title' => 'Wait 3 Days',             'sub' => 'Wait 3 days',              'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e3,   'type' => 'email',     'title' => 'Tips & Tricks Email',     'sub' => 'Pro tips to get more out of the product', 'config' => ['subject' => 'Pro tips for you', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $w1],
            ['source' => $w1, 'target' => $cond],
            ['source' => $cond, 'target' => $e2, 'branch' => 'yes'],
            ['source' => $cond, 'target' => $e2, 'branch' => 'no'],
            ['source' => $e2, 'target' => $w2],
            ['source' => $w2, 'target' => $e3],
        ];
        return $base;
    }

    /** email_click_followup: Email Click Follow-Up */
    private function buildEmailClickFollowupTemplate(array $base, string $triggerId): array
    {
        $tag = $this->uid(); $w1 = $this->uid(); $e1 = $this->uid(); $w2 = $this->uid(); $e2 = $this->uid();
        $base['trigger']['type'] = 'email_clicked';
        $base['description'] = 'When a contact clicks a link in your email, automatically follow up with targeted content.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $tag, 'type' => 'add_tag',  'title' => 'Apply Interest Tag',        'sub' => 'Tag contact based on link clicked', 'config' => ['tag_ids' => []]],
            ['id' => $w1,  'type' => 'wait',     'title' => 'Wait 1 Day',                'sub' => 'Wait 1 day',                       'config' => ['value' => 1, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e1,  'type' => 'email',    'title' => 'Related Follow-up Content', 'sub' => 'More about what you clicked',      'config' => ['subject' => 'More about what you clicked', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2,  'type' => 'wait',     'title' => 'Wait 2 Days',               'sub' => 'Wait 2 days',                      'config' => ['value' => 2, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e2,  'type' => 'email',    'title' => 'Conversion Offer Email',    'sub' => 'Special offer just for you',       'config' => ['subject' => 'Special offer just for you', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $tag],
            ['source' => $tag, 'target' => $w1],
            ['source' => $w1, 'target' => $e1],
            ['source' => $e1, 'target' => $w2],
            ['source' => $w2, 'target' => $e2],
        ];
        return $base;
    }

    /** upsell: Post-Purchase Upsell */
    private function buildUpsellTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $w1 = $this->uid(); $e2 = $this->uid(); $w2 = $this->uid(); $e3 = $this->uid();
        $base['trigger']['type'] = 'new_user_signup';
        $base['description'] = 'Send cross-sell and upsell emails right after a customer makes a purchase.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1, 'type' => 'email', 'title' => 'Order Confirmation & Thank You', 'sub' => 'Thank you for your order!',           'config' => ['subject' => 'Thank you for your order!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w1, 'type' => 'wait',  'title' => 'Wait 2 Days',                   'sub' => 'Wait 2 days',                         'config' => ['value' => 2, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e2, 'type' => 'email', 'title' => 'Product Recommendations',        'sub' => 'Customers also bought...',             'config' => ['subject' => 'You might also like these', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2, 'type' => 'wait',  'title' => 'Wait 3 Days',                   'sub' => 'Wait 3 days',                         'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e3, 'type' => 'email', 'title' => 'Exclusive Next Order Discount',  'sub' => '10% off your next purchase',           'config' => ['subject' => '10% off your next purchase — just for you', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $w1],
            ['source' => $w1, 'target' => $e2],
            ['source' => $e2, 'target' => $w2],
            ['source' => $w2, 'target' => $e3],
        ];
        return $base;
    }

    /** recommend: Product Recommendation */
    private function buildRecommendTemplate(array $base, string $triggerId): array
    {
        $w1 = $this->uid(); $e1 = $this->uid(); $w2 = $this->uid(); $cond = $this->uid(); $e2 = $this->uid();
        $base['trigger']['type'] = 'new_user_signup';
        $base['description'] = 'Boost revenue by recommending products right after a purchase.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $w1,   'type' => 'wait',      'title' => 'Wait 3 Days',                   'sub' => 'Wait 3 days',                      'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e1,   'type' => 'email',     'title' => 'Customers Also Bought Email',   'sub' => 'Based on your recent purchase',     'config' => ['subject' => 'Customers who bought this also love...', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2,   'type' => 'wait',      'title' => 'Wait 5 Days',                   'sub' => 'Wait 5 days',                      'config' => ['value' => 5, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $cond, 'type' => 'condition', 'title' => 'Clicked Recommendation?',       'sub' => 'Matching 1 condition',             'config' => ['conditions' => [['field' => 'email_clicked', 'operator' => 'equals', 'value' => 'yes']]]],
            ['id' => $e2,   'type' => 'email',     'title' => 'Limited-Time Offer Email',      'sub' => 'Offer expires soon — act fast!',   'config' => ['subject' => 'Limited-time offer on that product you liked', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $w1],
            ['source' => $w1, 'target' => $e1],
            ['source' => $e1, 'target' => $w2],
            ['source' => $w2, 'target' => $cond],
            ['source' => $cond, 'target' => $e2, 'branch' => 'yes'],
        ];
        return $base;
    }

    /** feedback: Post-Purchase Feedback */
    private function buildFeedbackTemplate(array $base, string $triggerId): array
    {
        $w1 = $this->uid(); $e1 = $this->uid(); $w2 = $this->uid(); $cond = $this->uid(); $e2 = $this->uid();
        $base['trigger']['type'] = 'new_user_signup';
        $base['description'] = 'Automatically request reviews and feedback after a customer makes a purchase.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $w1,   'type' => 'wait',      'title' => 'Wait 7 Days',              'sub' => 'Wait 7 days',                    'config' => ['value' => 7, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e1,   'type' => 'email',     'title' => 'Feedback Request Email',   'sub' => 'How was your experience?',      'config' => ['subject' => 'How was your experience? Share your feedback', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2,   'type' => 'wait',      'title' => 'Wait 3 Days',              'sub' => 'Wait 3 days',                    'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $cond, 'type' => 'condition', 'title' => 'Submitted Review?',        'sub' => 'Matching 1 condition',           'config' => ['conditions' => [['field' => 'review_submitted', 'operator' => 'equals', 'value' => 'yes']]]],
            ['id' => $e2,   'type' => 'email',     'title' => 'Thank You Coupon Email',   'sub' => 'Thank you! Here\'s your reward', 'config' => ['subject' => 'Thank you for your review — here\'s a reward!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $w1],
            ['source' => $w1, 'target' => $e1],
            ['source' => $e1, 'target' => $w2],
            ['source' => $w2, 'target' => $cond],
            ['source' => $cond, 'target' => $e2, 'branch' => 'yes'],
        ];
        return $base;
    }

    /** winback: Customer Win-Back */
    private function buildWinbackTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $w1 = $this->uid(); $e2 = $this->uid(); $w2 = $this->uid(); $cond = $this->uid(); $e3 = $this->uid();
        $base['trigger']['type'] = 'tag_applied';
        $base['description'] = 'Identify customers who have not purchased in 90+ days and send a targeted win-back sequence.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1,   'type' => 'email',     'title' => 'We Miss You Email',     'sub' => 'It\'s been a while!',               'config' => ['subject' => 'We miss you — come back!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w1,   'type' => 'wait',      'title' => 'Wait 5 Days',           'sub' => 'Wait 5 days',                       'config' => ['value' => 5, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e2,   'type' => 'email',     'title' => 'Exclusive 20% Off',     'sub' => '20% off coupon inside',             'config' => ['subject' => 'Here\'s 20% off — just for you', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2,   'type' => 'wait',      'title' => 'Wait 7 Days',           'sub' => 'Wait 7 days',                       'config' => ['value' => 7, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $cond, 'type' => 'condition', 'title' => 'Made a Purchase?',      'sub' => 'Matching 1 condition',              'config' => ['conditions' => [['field' => 'purchase_count', 'operator' => 'greater than', 'value' => 0]]]],
            ['id' => $e3,   'type' => 'email',     'title' => 'Final Win-Back Email',  'sub' => 'Last chance — offer expiring soon', 'config' => ['subject' => 'Last chance — your offer expires tonight', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $w1],
            ['source' => $w1, 'target' => $e2],
            ['source' => $e2, 'target' => $w2],
            ['source' => $w2, 'target' => $cond],
            ['source' => $cond, 'target' => $e3, 'branch' => 'no'],
        ];
        return $base;
    }

    /** cart_abandon: Cart Abandonment Recovery */
    private function buildCartAbandonTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $w1 = $this->uid(); $cond = $this->uid(); $e2 = $this->uid(); $w2 = $this->uid(); $e3 = $this->uid();
        $base['trigger']['type'] = 'new_user_signup';
        $base['description'] = 'Automatically follow up with customers who left items in their cart.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1,   'type' => 'email',     'title' => 'Cart Reminder Email',   'sub' => 'You left something behind!',       'config' => ['subject' => 'You left something in your cart!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w1,   'type' => 'wait',      'title' => 'Wait 12 Hours',         'sub' => 'Wait 12 hours',                    'config' => ['value' => 12, 'unit' => 'hours', 'send_time' => 'immediately']],
            ['id' => $cond, 'type' => 'condition', 'title' => 'Completed Purchase?',   'sub' => 'Matching 1 condition',             'config' => ['conditions' => [['field' => 'cart_abandoned', 'operator' => 'equals', 'value' => 'yes']]]],
            ['id' => $e2,   'type' => 'email',     'title' => 'Urgency Reminder',      'sub' => 'Items selling fast!',              'config' => ['subject' => 'Your items are selling fast — grab them now', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2,   'type' => 'wait',      'title' => 'Wait 1 Day',            'sub' => 'Wait 1 day',                       'config' => ['value' => 1, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e3,   'type' => 'email',     'title' => 'Final Offer with Discount', 'sub' => '10% off to complete your order', 'config' => ['subject' => '10% off to complete your order — limited time', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $w1],
            ['source' => $w1, 'target' => $cond],
            ['source' => $cond, 'target' => $e2, 'branch' => 'yes'],
            ['source' => $e2, 'target' => $w2],
            ['source' => $w2, 'target' => $e3],
        ];
        return $base;
    }

    /** lead_nurture: Lead Nurture Drip */
    private function buildLeadNurtureTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $w1 = $this->uid(); $e2 = $this->uid(); $w2 = $this->uid(); $e3 = $this->uid(); $w3 = $this->uid(); $e4 = $this->uid();
        $base['trigger']['type'] = 'contact_created';
        $base['description'] = 'A multi-step educational drip sequence designed to nurture leads from awareness to conversion.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1, 'type' => 'email', 'title' => 'Lead Magnet Delivery',      'sub' => 'Your free resource is here!',          'config' => ['subject' => 'Your free resource is here!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w1, 'type' => 'wait',  'title' => 'Wait 2 Days',               'sub' => 'Wait 2 days',                          'config' => ['value' => 2, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e2, 'type' => 'email', 'title' => 'Educational Content Email', 'sub' => 'Learn how to solve your problem',      'config' => ['subject' => 'How to solve [their main problem]', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2, 'type' => 'wait',  'title' => 'Wait 3 Days',               'sub' => 'Wait 3 days',                          'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e3, 'type' => 'email', 'title' => 'Case Study & Social Proof', 'sub' => 'See how others succeeded',             'config' => ['subject' => 'How [Customer] achieved [Result] with us', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w3, 'type' => 'wait',  'title' => 'Wait 3 Days',               'sub' => 'Wait 3 days',                          'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e4, 'type' => 'email', 'title' => 'Demo Offer / CTA Email',    'sub' => 'Ready to take the next step?',         'config' => ['subject' => 'Ready to get started? Book your free demo', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $w1],
            ['source' => $w1, 'target' => $e2],
            ['source' => $e2, 'target' => $w2],
            ['source' => $w2, 'target' => $e3],
            ['source' => $e3, 'target' => $w3],
            ['source' => $w3, 'target' => $e4],
        ];
        return $base;
    }

    /** tag_nurture: Tag-Based Lead Nurture */
    private function buildTagNurtureTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $w1 = $this->uid(); $e2 = $this->uid(); $w2 = $this->uid(); $e3 = $this->uid();
        $base['trigger']['type'] = 'tag_applied';
        $base['description'] = 'When a specific tag is applied to a contact, start a personalized nurture sequence.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1, 'type' => 'email', 'title' => 'Introductory Email',      'sub' => 'Welcome to this journey!',         'config' => ['subject' => 'Welcome — here\'s what\'s next for you', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w1, 'type' => 'wait',  'title' => 'Wait 2 Days',             'sub' => 'Wait 2 days',                      'config' => ['value' => 2, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e2, 'type' => 'email', 'title' => 'Deep-Dive Content Email', 'sub' => 'Going deeper on what matters',     'config' => ['subject' => 'A deep dive just for you', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w2, 'type' => 'wait',  'title' => 'Wait 4 Days',             'sub' => 'Wait 4 days',                      'config' => ['value' => 4, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e3, 'type' => 'email', 'title' => 'Personalized Offer Email', 'sub' => 'A special offer tailored for you', 'config' => ['subject' => 'A special offer tailored for you', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $w1],
            ['source' => $w1, 'target' => $e2],
            ['source' => $e2, 'target' => $w2],
            ['source' => $w2, 'target' => $e3],
        ];
        return $base;
    }

    /** birthday: Birthday Discount */
    private function buildBirthdayTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $w1 = $this->uid(); $e2 = $this->uid();
        $base['trigger']['type'] = 'birthday';
        $base['description'] = 'Delight your contacts on their special day with a personalized birthday greeting and an exclusive discount.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1, 'type' => 'email', 'title' => 'Birthday Greeting + Coupon', 'sub' => 'Happy Birthday! Here\'s a gift for you', 'config' => ['subject' => '🎂 Happy Birthday! Here\'s a gift from us', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $w1, 'type' => 'wait',  'title' => 'Wait 3 Days',                'sub' => 'Wait 3 days (if not redeemed)',         'config' => ['value' => 3, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e2, 'type' => 'email', 'title' => 'Reminder — Offer Expires',  'sub' => 'Your birthday offer is expiring soon',   'config' => ['subject' => 'Your birthday offer expires soon!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $w1],
            ['source' => $w1, 'target' => $e2],
        ];
        return $base;
    }

    /** anniversary: Customer Anniversary */
    private function buildAnniversaryTemplate(array $base, string $triggerId): array
    {
        $e1 = $this->uid(); $tag = $this->uid(); $w1 = $this->uid(); $e2 = $this->uid();
        $base['trigger']['type'] = 'contact_updated';
        $base['description'] = 'Recognize and celebrate the anniversary of a contact\'s relationship with your brand.';
        $base['nodes'] = array_merge($base['nodes'], [
            ['id' => $e1,  'type' => 'email',   'title' => 'Anniversary Email',           'sub' => 'Celebrating 1 year together!',    'config' => ['subject' => '🎉 Happy 1-Year Anniversary with us!', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
            ['id' => $tag, 'type' => 'add_tag', 'title' => 'Apply "Loyal Customer" Tag', 'sub' => 'Add Loyal Customer tag',          'config' => ['tag_ids' => []]],
            ['id' => $w1,  'type' => 'wait',    'title' => 'Wait 1 Day',                  'sub' => 'Wait 1 day',                      'config' => ['value' => 1, 'unit' => 'days', 'send_time' => 'immediately']],
            ['id' => $e2,  'type' => 'email',   'title' => 'Loyalty Reward Email',        'sub' => 'A special reward for your loyalty', 'config' => ['subject' => 'Your exclusive loyalty reward is here', 'template_id' => null, 'from_name' => '', 'from_email' => '']],
        ]);
        $base['edges'] = [
            ['source' => $triggerId, 'target' => $e1],
            ['source' => $e1, 'target' => $tag],
            ['source' => $tag, 'target' => $w1],
            ['source' => $w1, 'target' => $e2],
        ];
        return $base;
    }

    public function run(Campaign $automation)
    {
        $settings = $automation->settings;
        $trigger = $settings['trigger'] ?? [];
        $triggerType = $trigger['type'] ?? '';

        $query = Contact::query(); // TenantScope is applied automatically

        $triggerConfig = $settings['trigger'] ?? [];
        $logicalOperator = $triggerConfig['logical_operator'] ?? 'OR';
        $triggers = $triggerConfig['triggers'] ?? [];
        if (empty($triggers) && isset($triggerConfig['type'])) {
            $triggers = [$triggerConfig];
        }

        if (!empty($triggers)) {
            $query->where(function($q) use ($triggers, $logicalOperator) {
                foreach ($triggers as $idx => $t) {
                    $whereMethod = ($idx === 0 || $logicalOperator === 'AND') ? 'where' : 'orWhere';
                    $tType = $t['type'] ?? '';

                    if ($tType === 'subscribes_to_list') {
                        $listId = $t['list_id'] ?? null;
                        if ($listId !== null) {
                            $q->$whereMethod(function($sub) use ($listId) {
                                $sub->whereHas('lists', function($listsQuery) use ($listId) {
                                    $listsQuery->where('lists.id', (int)$listId);
                                });
                            });
                        }
                    } elseif ($tType === 'tag_applied') {
                        $tagId = $t['tag_id'] ?? null;
                        if ($tagId !== null) {
                            $q->$whereMethod(function($sub) use ($tagId) {
                                $sub->whereHas('tags', function($tagsQuery) use ($tagId) {
                                    $tagsQuery->where('tags.id', (int)$tagId);
                                });
                            });
                        }
                    } elseif ($tType === 'email_opened') {
                        $campaignId = $t['campaign_id'] ?? null;
                        if ($campaignId !== null) {
                            $q->$whereMethod(function($sub) use ($campaignId) {
                                $sub->whereHas('campaignEvents', function($ce) use ($campaignId) {
                                    $ce->where('campaign_id', $campaignId)->where('event_type', 'open');
                                });
                            });
                        }
                    } elseif ($tType === 'email_clicked') {
                        $campaignId = $t['campaign_id'] ?? null;
                        if ($campaignId !== null) {
                            $q->$whereMethod(function($sub) use ($campaignId) {
                                $sub->whereHas('campaignEvents', function($ce) use ($campaignId) {
                                    $ce->where('campaign_id', $campaignId)->where('event_type', 'click');
                                });
                            });
                        }
                    } elseif ($tType === 'unsubscribed') {
                        $q->$whereMethod('status', 'unsubscribed');
                    } elseif ($tType === 'incoming_webhook') {
                        $webhookId = $t['webhook_id'] ?? null;
                        $q->$whereMethod(function($sub) use ($webhookId) {
                            $sub->whereHas('webhookLogs', function($wlQuery) use ($webhookId) {
                                $wlQuery->where('status', 'success');
                                if ($webhookId && $webhookId !== 'all') {
                                    $wlQuery->where('webhook_id', (int)$webhookId);
                                }
                            });
                        });
                    } elseif ($tType === 'new_user_signup' || $tType === 'contact_created') {
                        if ($logicalOperator === 'OR') {
                            $q->orWhereRaw('1=1');
                        }
                    }
                }
            });
        }

        $contacts = $query->get();
        $enrolledCount = 0;

        foreach ($contacts as $contact) {
            $hasEnrolled = CampaignEvent::where('campaign_id', $automation->id)
                ->where('contact_id', $contact->id)
                ->where('event_type', 'enrolled')
                ->exists();

            if (!$hasEnrolled) {
                AutomationEngine::enroll($automation, $contact);
                $enrolledCount++;
            }
        }

        return back()->with('success', "Enrolled {$enrolledCount} contacts successfully.");
    }

    public function restart(Campaign $automation)
    {
        // Delete all execution events
        CampaignEvent::where('campaign_id', $automation->id)->delete();

        // Reset recipient count
        $automation->update([
            'recipients_count' => 0
        ]);

        return back()->with('success', "Automation metrics and logs reset successfully.");
    }

    public function report(Request $request, Campaign $automation): Response
    {
        abort_unless($automation->type === 'automation', 404);

        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        // Fetch automation overview stats with date filtering
        $enrolledCountQuery = CampaignEvent::where('campaign_id', $automation->id)->where('event_type', 'enrolled');
        $completedCountQuery = CampaignEvent::where('campaign_id', $automation->id)->where('event_type', 'completed');
        $errorCountQuery = CampaignEvent::where('campaign_id', $automation->id)->where('event_type', 'node_error');

        if ($startDate) {
            $enrolledCountQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
            $completedCountQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
            $errorCountQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
        }
        if ($endDate) {
            $enrolledCountQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
            $completedCountQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
            $errorCountQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
        }

        $enrolledCount = $enrolledCountQuery->count();
        $completedCount = $completedCountQuery->count();
        $errorCount = $errorCountQuery->count();

        // Step execution counts (unique contact count per step and state)
        $nodeStatsRawQuery = CampaignEvent::where('campaign_id', $automation->id)
            ->whereNotNull('node_id')
            ->selectRaw('node_id, event_type, count(distinct contact_id) as count');

        if ($startDate) {
            $nodeStatsRawQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
        }
        if ($endDate) {
            $nodeStatsRawQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
        }

        $nodeStatsRaw = $nodeStatsRawQuery->groupBy('node_id', 'event_type')->get();

        $nodeStats = [];
        foreach ($nodeStatsRaw as $stat) {
            $nId = $stat->node_id;
            if (!isset($nodeStats[$nId])) {
                $nodeStats[$nId] = [
                    'processing' => 0,
                    'success'    => 0,
                    'error'      => 0,
                ];
            }
            if ($stat->event_type === 'node_processing') {
                $nodeStats[$nId]['processing'] = $stat->count;
            } elseif (in_array($stat->event_type, ['node_success', 'enrolled', 'sent'])) {
                $nodeStats[$nId]['success'] = $stat->count;
            } elseif ($stat->event_type === 'node_error') {
                $nodeStats[$nId]['error'] = $stat->count;
            }
        }

        // Email Performance Metrics
        $emailsSentQuery = CampaignEvent::where('campaign_id', $automation->id)->where('event_type', 'sent');
        $opensCountQuery = CampaignEvent::where('campaign_id', $automation->id)->where('event_type', 'open');
        $clicksCountQuery = CampaignEvent::where('campaign_id', $automation->id)->where('event_type', 'click');
        $bouncesCountQuery = CampaignEvent::where('campaign_id', $automation->id)->where('event_type', 'bounced');

        if ($startDate) {
            $emailsSentQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
            $opensCountQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
            $clicksCountQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
            $bouncesCountQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
        }
        if ($endDate) {
            $emailsSentQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
            $opensCountQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
            $clicksCountQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
            $bouncesCountQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
        }

        $emailsSentCount = $emailsSentQuery->count();
        $uniqueOpensCount = $opensCountQuery->distinct('contact_id')->count();
        $uniqueClicksCount = $clicksCountQuery->distinct('contact_id')->count();
        $emailsBouncedCount = $bouncesCountQuery->count();

        // Fetch paginated enrolled contacts
        $enrolledContactIdsQuery = CampaignEvent::where('campaign_id', $automation->id)
            ->where('event_type', 'enrolled');

        if ($startDate) {
            $enrolledContactIdsQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
        }
        if ($endDate) {
            $enrolledContactIdsQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
        }

        $enrolledContactIds = $enrolledContactIdsQuery->pluck('contact_id');

        $contactsQuery = Contact::withoutGlobalScopes()
            ->whereIn('id', $enrolledContactIds);

        if ($contactSearch = $request->input('contact_search')) {
            $contactsQuery->where(function($q) use ($contactSearch) {
                $q->where('email', 'like', "%{$contactSearch}%")
                  ->orWhere('first_name', 'like', "%{$contactSearch}%")
                  ->orWhere('last_name', 'like', "%{$contactSearch}%");
            });
        }

        if ($contactStatus = $request->input('contact_status')) {
            if ($contactStatus === 'completed') {
                $completedIds = CampaignEvent::where('campaign_id', $automation->id)
                    ->where('event_type', 'completed')
                    ->pluck('contact_id');
                $contactsQuery->whereIn('id', $completedIds);
            } elseif ($contactStatus === 'failed') {
                $errorIds = CampaignEvent::where('campaign_id', $automation->id)
                    ->where('event_type', 'node_error')
                    ->pluck('contact_id');
                $contactsQuery->whereIn('id', $errorIds);
            } elseif ($contactStatus === 'active') {
                $completedIds = CampaignEvent::where('campaign_id', $automation->id)
                    ->where('event_type', 'completed')
                    ->pluck('contact_id');
                $errorIds = CampaignEvent::where('campaign_id', $automation->id)
                    ->where('event_type', 'node_error')
                    ->pluck('contact_id');
                $contactsQuery->whereNotIn('id', $completedIds)
                              ->whereNotIn('id', $errorIds);
            }
        }

        $enrolledContacts = $contactsQuery->orderByDesc('id')
            ->paginate(15, ['*'], 'contacts_page')
            ->withQueryString();

        $contactIdsOnPage = $enrolledContacts->pluck('id')->toArray();

        $completedStatuses = CampaignEvent::where('campaign_id', $automation->id)
            ->whereIn('contact_id', $contactIdsOnPage)
            ->where('event_type', 'completed')
            ->pluck('contact_id')
            ->toArray();

        $errorStatuses = CampaignEvent::where('campaign_id', $automation->id)
            ->whereIn('contact_id', $contactIdsOnPage)
            ->where('event_type', 'node_error')
            ->pluck('contact_id')
            ->toArray();

        $enrollEvents = CampaignEvent::where('campaign_id', $automation->id)
            ->whereIn('contact_id', $contactIdsOnPage)
            ->where('event_type', 'enrolled')
            ->get();

        $enrollDates = [];
        foreach ($enrollEvents as $ev) {
            $enrollDates[$ev->contact_id] = $ev->created_at;
        }

        $contactsPage = $enrolledContacts->through(function ($c) use ($completedStatuses, $errorStatuses, $enrollDates) {
            $status = 'active';
            if (in_array($c->id, $completedStatuses)) {
                $status = 'completed';
            } elseif (in_array($c->id, $errorStatuses)) {
                $status = 'failed';
            }
            
            $enrolledAt = isset($enrollDates[$c->id]) ? $enrollDates[$c->id]->toIso8601String() : null;

            return [
                'id'          => $c->id,
                'email'       => $c->email,
                'name'        => trim($c->first_name . ' ' . $c->last_name),
                'status'      => $status,
                'enrolled_at' => $enrolledAt,
            ];
        });

        // Activity log query
        $eventsQuery = CampaignEvent::where('campaign_id', $automation->id)
            ->with(['contact' => fn($q) => $q->withoutGlobalScopes()->select(['id', 'email', 'first_name', 'last_name'])])
            ->orderByDesc('id');

        if ($filterType = $request->input('event_type')) {
            $eventsQuery->where('event_type', $filterType);
        }

        if ($startDate) {
            $eventsQuery->where('created_at', '>=', \Carbon\Carbon::parse($startDate)->startOfDay());
        }
        if ($endDate) {
            $eventsQuery->where('created_at', '<=', \Carbon\Carbon::parse($endDate)->endOfDay());
        }

        $events = $eventsQuery->paginate(20, ['*'], 'events_page')->withQueryString();

        return Inertia::render('Automation/Report', [
            'automation' => [
                'id'                 => $automation->id,
                'title'              => $automation->title,
                'status'             => $automation->status,
                'settings'           => $automation->settings,
                'enrolled_count'     => $enrolledCount,
                'completed_count'    => $completedCount,
                'error_count'        => $errorCount,
                'emails_sent'        => $emailsSentCount,
                'unique_opens'       => $uniqueOpensCount,
                'unique_clicks'      => $uniqueClicksCount,
                'emails_failed'      => $automation->emails_failed ?? 0,
                'emails_bounced'     => $emailsBouncedCount,
                'unsubscribes_count' => $automation->unsubscribes_count ?? 0,
                'created_at'         => $automation->created_at->toIso8601String(),
                'updated_at'         => $automation->updated_at->toIso8601String(),
            ],
            'nodeStats' => $nodeStats,
            'contacts'  => $contactsPage,
            'events'    => $events->through(function ($e) {
                return [
                    'id'          => $e->id,
                    'contact'     => $e->contact ? [
                        'id'    => $e->contact->id,
                        'email' => $e->contact->email,
                        'name'  => trim($e->contact->first_name . ' ' . $e->contact->last_name),
                    ] : null,
                    'node_id'     => $e->node_id,
                    'event_type'  => $e->event_type,
                    'reason'      => $e->reason,
                    'created_at'  => $e->created_at->toIso8601String(),
                ];
            }),
            'filters' => $request->only(['event_type', 'contact_search', 'contact_status', 'start_date', 'end_date']),
        ]);
    }

    public function contactJourney(Campaign $automation, Contact $contact): JsonResponse
    {
        abort_unless($automation->type === 'automation', 404);

        $events = CampaignEvent::where('campaign_id', $automation->id)
            ->where('contact_id', $contact->id)
            ->orderBy('id', 'asc')
            ->get();

        $nodes = $automation->settings['nodes'] ?? [];
        $nodeMap = [];
        foreach ($nodes as $node) {
            $nodeMap[$node['id']] = $node;
        }

        $journey = $events->map(function ($e) use ($nodeMap) {
            $nodeType = 'Unknown';
            $nodeTitle = 'Automation Funnel';
            if ($e->node_id && isset($nodeMap[$e->node_id])) {
                $nodeType = $nodeMap[$e->node_id]['type'] ?? 'Unknown';
                $nodeTitle = $nodeMap[$e->node_id]['title'] ?? 'Funnel Step';
            } elseif ($e->event_type === 'completed') {
                $nodeType = 'end';
                $nodeTitle = 'Funnel Completed';
            }

            return [
                'id'          => $e->id,
                'event_type'  => $e->event_type,
                'node_type'   => $nodeType,
                'node_title'  => $nodeTitle,
                'reason'      => $e->reason,
                'created_at'  => $e->created_at->toIso8601String(),
            ];
        });

        return response()->json([
            'success' => true,
            'contact' => [
                'id'    => $contact->id,
                'email' => $contact->email,
                'name'  => trim($contact->first_name . ' ' . $contact->last_name),
            ],
            'journey' => $journey,
        ]);
    }
}
