<?php

namespace App\Workflows\Examples;

use App\Models\Order;
use Spatie\Activitylog\Models\Activity;

/**
 * Example: Testing Workflow Activity Logging
 *
 * This example shows how to verify that workflow activities are being logged correctly.
 */
class ActivityLoggingExample
{
    public function demonstrateActivityLogging()
    {
        // Get an order with workflow
        $order = Order::with('workflowInstance')->first();

        if (! $order) {
            echo "No orders found.\n";

            return;
        }

        echo "Order: {$order->name}\n";
        echo "Workflow Status: {$order->getWorkflowStatusLabel()}\n\n";

        // Show all activities for this order
        $activities = $order->activities()->latest()->get();

        echo "=== Activity Log ===\n";
        foreach ($activities as $activity) {
            echo "Date: {$activity->created_at}\n";
            echo 'User: '.($activity->causer?->name ?? 'System')."\n";
            echo "Event: {$activity->event}\n";
            echo "Description: {$activity->description}\n";
            echo 'Properties: '.json_encode($activity->properties, JSON_PRETTY_PRINT)."\n";
            echo "---\n";
        }

        // Show workflow-specific activities only
        echo "\n=== Workflow Activities Only ===\n";
        $workflowActivities = $order->activities()
            ->where('event', 'LIKE', 'workflow_%')
            ->latest()
            ->get();

        foreach ($workflowActivities as $activity) {
            $props = $activity->properties;
            echo "📅 {$activity->created_at->format('Y-m-d H:i:s')}\n";
            echo '👤 '.($activity->causer?->name ?? 'System')."\n";
            echo "🔄 {$activity->description}\n";

            if ($activity->event === 'workflow_step_approved') {
                echo "   From: {$props['from_step']} → To: {$props['to_step']}\n";
                if (! empty($props['step_data'])) {
                    echo '   Data: '.json_encode($props['step_data'])."\n";
                }
            }

            if ($activity->event === 'workflow_step_rejected') {
                echo "   Reason: {$props['reason']}\n";
            }

            if (! empty($props['notes'])) {
                echo "   Notes: {$props['notes']}\n";
            }

            echo "\n";
        }
    }

    public function getWorkflowStatistics()
    {
        // Get workflow activity statistics
        $stats = Activity::where('event', 'LIKE', 'workflow_%')
            ->selectRaw('event, count(*) as count')
            ->groupBy('event')
            ->get();

        echo "=== Workflow Activity Statistics ===\n";
        foreach ($stats as $stat) {
            echo "{$stat->event}: {$stat->count}\n";
        }

        // Get most active users in workflows
        $activeUsers = Activity::where('event', 'LIKE', 'workflow_%')
            ->with('causer')
            ->selectRaw('causer_id, count(*) as activity_count')
            ->groupBy('causer_id')
            ->orderBy('activity_count', 'desc')
            ->limit(5)
            ->get();

        echo "\n=== Most Active Users in Workflows ===\n";
        foreach ($activeUsers as $userActivity) {
            $user = $userActivity->causer;
            echo ($user?->name ?? 'Unknown').": {$userActivity->activity_count} activities\n";
        }
    }

    public function getRecentWorkflowActivity()
    {
        // Get recent workflow activities across all models
        $recentActivities = Activity::where('event', 'LIKE', 'workflow_%')
            ->with(['subject', 'causer'])
            ->latest()
            ->limit(10)
            ->get();

        echo "=== Recent Workflow Activities (All Models) ===\n";
        foreach ($recentActivities as $activity) {
            $subjectName = $activity->subject?->name ?? "Unknown {$activity->subject_type}";
            $userName = $activity->causer?->name ?? 'System';

            echo "🕒 {$activity->created_at->diffForHumans()}\n";
            echo "📄 {$subjectName}\n";
            echo "👤 {$userName}\n";
            echo "🔄 {$activity->description}\n\n";
        }
    }
}

// Usage example in tinker or test:
/*
$example = new \App\Workflows\Examples\ActivityLoggingExample();
$example->demonstrateActivityLogging();
$example->getWorkflowStatistics();
$example->getRecentWorkflowActivity();
*/
