<?php

namespace App\Http\Controllers\Api\Orders;

use App\Domains\Orders\Models\Order;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

class OrderShowController extends Controller
{
    public function __invoke(string $order): JsonResponse
    {
        $record = Order::query()
            ->with(['contact', 'assignee', 'items.product', 'quote', 'paymentRequests.provider'])
            ->where('tenant_id', request()->user()->tenant_id)
            ->findOrFail($order);

        return response()->json([
            'data' => [
                'id' => $record->id,
                'orderNumber' => $record->order_number,
                'customer' => $record->contact?->primary_name,
                'customerPhone' => $record->contact?->whatsapp_phone,
                'status' => $record->status,
                'paymentStatus' => $record->payment_status,
                'subtotal' => '$'.number_format((float) $record->subtotal, 2),
                'discountTotal' => '$'.number_format((float) $record->discount_total, 2),
                'shippingFee' => '$'.number_format((float) $record->shipping_fee, 2),
                'total' => '$'.number_format((float) $record->total, 2),
                'source' => $record->source_type ?? 'manual',
                'assignee' => $record->assignee?->full_name ?? 'Unassigned',
                'notes' => $record->notes,
                'shippingAddress' => $record->shipping_address_json,
                'quoteNumber' => $record->quote?->quote_number,
                'paymentRequests' => $record->paymentRequests->map(fn ($paymentRequest) => [
                    'id' => $paymentRequest->id,
                    'provider' => $paymentRequest->provider?->display_name ?? 'Unknown',
                    'status' => $paymentRequest->status,
                    'amount' => '$'.number_format((float) $paymentRequest->amount, 2),
                    'checkoutUrl' => $paymentRequest->checkout_url,
                    'externalReference' => $paymentRequest->external_reference,
                    'createdAt' => $paymentRequest->created_at?->format('M d, H:i'),
                ])->values()->all(),
                'paymentOptions' => $this->paymentOptions($record),
                'items' => $record->items->map(fn ($item) => [
                    'id' => $item->id,
                    'name' => $item->item_name,
                    'quantity' => $item->quantity,
                    'unitPrice' => '$'.number_format((float) $item->unit_price, 2),
                    'lineTotal' => '$'.number_format((float) $item->line_total, 2),
                ])->values()->all(),
            ],
        ]);
    }

    private function paymentOptions(Order $order): array
    {
        $provider = $order->tenant
            ?->paymentProviders()
            ->where('provider_key', 'whish')
            ->first();

        $credentials = is_array($provider?->credentials_json) ? $provider->credentials_json : [];
        $merchantId = trim((string) ($credentials['merchant_id'] ?? ''));
        $merchantSecret = trim((string) ($credentials['merchant_secret'] ?? ''));
        $manualWhishNumber = trim((string) ($credentials['manual_whish_number'] ?? ''));

        $canWhishApi = (bool) ($provider?->is_enabled) && $merchantId !== '' && $merchantSecret !== '';
        $canManualWhish = (bool) ($credentials['allow_manual_whish'] ?? false) && $manualWhishNumber !== '';
        $canCashOnDelivery = (bool) ($credentials['allow_cod'] ?? true);

        return [
            'canWhishApi' => $canWhishApi,
            'canManualWhish' => $canManualWhish,
            'canCashOnDelivery' => $canCashOnDelivery,
            'manualWhishNumber' => $manualWhishNumber !== '' ? $manualWhishNumber : null,
        ];
    }
}
