<?php

namespace MtcPharmacy\Subscriptions\Console\Commands;

use Illuminate\Console\Command;
use MtcPharmacy\Subscriptions\Classes\Subscription;
use MtcPharmacy\Subscriptions\Classes\SubscriptionLog;

/**
 * Show detailed information about a subscription
 *
 * Usage:
 *     php artisan subscriptions:show 1
 *     php artisan subscriptions:show 1 --logs
 *     php artisan subscriptions:show 1 --orders
 */
class ShowSubscriptionCommand extends Command
{
    protected $signature = 'subscriptions:show
                            {id : The subscription ID}
                            {--logs : Show subscription logs}
                            {--orders : Show related orders}
                            {--all : Show everything}';

    protected $description = 'Display detailed information about a subscription for debugging';

    public function handle()
    {
        $subscriptionId = $this->argument('id');
        $subscription = Subscription::with(['member', 'items.shop_item', 'items.shop_item_size', 'orders'])
            ->find($subscriptionId);

        if (!$subscription) {
            $this->error("Subscription with ID {$subscriptionId} not found.");
            return 1;
        }

        $showLogs = $this->option('logs') || $this->option('all');
        $showOrders = $this->option('orders') || $this->option('all');

        // Main subscription info
        $this->info("📦 Subscription #{$subscription->id}");
        $this->newLine();

        $this->table(
            ['Property', 'Value'],
            [
                ['ID', $subscription->id],
                ['Member', "{$subscription->member->full_name} (ID: {$subscription->member_id})"],
                ['Email', $subscription->member->email],
                ['Status', $this->colorizeStatus($subscription->status)],
                ['Interval', "{$subscription->interval_multiplier} {$subscription->interval}"],
                ['Price per Issue', '£' . number_format($subscription->price_per_issue, 2)],
                ['Can be Paused', $subscription->can_be_paused ? 'Yes' : 'No'],
                ['Max Issues', $subscription->max_number_of_issues ?? 'Unlimited'],
                ['Issues Created', $subscription->orders->count()],
                ['Next Issue Date', $subscription->next_issue_date ?? 'Not set'],
                ['Expiry Date', $subscription->expiry_date ?? 'Not set'],
                ['Previous Payment ID', $subscription->previous_payment_id ?? 'None'],
                ['Assessment Updated', $subscription->is_assessment_updated ? 'Yes' : 'No'],
                ['Created', $subscription->created_at->format('Y-m-d H:i:s')],
                ['Updated', $subscription->updated_at->format('Y-m-d H:i:s')],
            ]
        );

        // Items
        $this->newLine();
        $this->info('📋 Subscription Items:');
        $itemsData = $subscription->items->map(function ($item) {
            return [
                'ID' => $item->id,
                'Item' => $item->getDisplayName(),
                'Shop Item ID' => $item->shop_item_id,
                'Size ID' => $item->shop_item_size_id ?? 'N/A',
                'Assessment ID' => $item->assessment_id ?? 'N/A',
            ];
        })->toArray();
        $this->table(['ID', 'Item', 'Shop Item ID', 'Size ID', 'Assessment ID'], $itemsData);

        // Orders
        if ($showOrders) {
            $this->newLine();
            $this->info('🛒 Related Orders:');
            if ($subscription->orders->isEmpty()) {
                $this->warn('  No orders yet.');
            } else {
                $ordersData = $subscription->orders->map(function ($order) {
                    return [
                        'ID' => $order->id,
                        'Date' => $order->date,
                        'Total' => '£' . number_format($order->cost_total, 2),
                        'Paid' => $order->paid ? '✓ Yes' : '✗ No',
                        'Status' => $order->getOrderStatusTitle(),
                    ];
                })->toArray();
                $this->table(['ID', 'Date', 'Total', 'Paid', 'Status'], $ordersData);
            }
        }

        // Logs
        if ($showLogs) {
            $this->newLine();
            $this->info('📝 Recent Activity (Last 10 logs):');
            $logs = SubscriptionLog::where('subscription_id', $subscription->id)
                ->orderBy('created_at', 'desc')
                ->limit(10)
                ->get();

            if ($logs->isEmpty()) {
                $this->warn('  No activity logs yet.');
            } else {
                $logsData = $logs->map(function ($log) {
                    return [
                        'Date' => $log->created_at->format('Y-m-d H:i:s'),
                        'Action' => $log->action_type,
                        'Description' => \Illuminate\Support\Str::limit($log->action_description, 50),
                        'Source' => $log->source,
                    ];
                })->toArray();
                $this->table(['Date', 'Action', 'Description', 'Source'], $logsData);
            }
        }

        // Helpful commands
        $this->newLine();
        $this->info('💡 Helpful Commands:');
        $this->line("  View logs:      php artisan subscriptions:show {$subscription->id} --logs");
        $this->line("  View orders:    php artisan subscriptions:show {$subscription->id} --orders");
        $this->line("  View all:       php artisan subscriptions:show {$subscription->id} --all");
        $this->line("  Generate order: php artisan subscriptions:generate_orders --force --subscription-id={$subscription->id}");
        $this->line("  Edit in admin:  /admin/subscriptions/edit/{$subscription->id}");

        return 0;
    }

    private function colorizeStatus($status)
    {
        $colors = [
            'active' => 'green',
            'pending' => 'yellow',
            'paused' => 'yellow',
            'cancelled' => 'red',
            'expired' => 'red',
            'payment-failed' => 'red',
            'completed' => 'blue',
        ];

        $color = $colors[$status] ?? 'white';
        return "<fg={$color}>{$status}</>";
    }
}
