<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\Hotspot\VoucherService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AzamCallbackController extends Controller
{
    public function handle(Request $request, VoucherService $vouchers)
    {
        $payload = $request->all();
        Log::info('AzamPay callback received', ['payload' => $payload]);

        // 1) Figure out reference / externalId
        $externalId =
            $request->input('externalReferenceId') ??
            $request->input('externalId') ??
            $request->input('reference') ??
            null;

        if (! $externalId) {
            Log::warning('AzamPay callback missing externalId', ['payload' => $payload]);
            return response()->json(['message' => 'No externalId'], 200);
        }

        /** @var Order|null $order */
        $order = Order::where('reference', $externalId)->first();
        if (! $order) {
            Log::warning('AzamPay callback: order not found', ['externalId' => $externalId]);
            return response()->json(['message' => 'Order not found'], 200);
        }

        // If already processed, just store callback & exit
        if (in_array($order->status, ['success', 'failed'], true)) {
            $meta = $order->meta ?? [];
            $meta['azam_callbacks'][] = $payload;
            $order->meta = $meta;
            $order->save();

            return response()->json(['message' => 'Already processed'], 200);
        }

        // 2) Determine success/fail
        $status     = $request->input('status') ?? $request->input('transactionStatus');
        $resultCode = $request->input('resultCode') ?? $request->input('messageCode');

        $isSuccess = false;

        if (is_string($status) && strcasecmp($status, 'SUCCESS') === 0) {
            $isSuccess = true;
        } elseif (in_array($resultCode, [0, '0'], true)) {
            $isSuccess = true;
        }

        // 3) Update order + generate voucher on success
        $meta = $order->meta ?? [];
        $meta['azam_last_callback'] = $payload;
        $order->meta = $meta;

        if ($isSuccess) {
            try {
                $code = $vouchers->generateForOrder($order);
                Log::info('Voucher generated from Azam callback', [
                    'order_id' => $order->id,
                    'code'     => $code,
                ]);
            } catch (\Throwable $e) {
                Log::error('Voucher generation failed in Azam callback', [
                    'order_id' => $order->id,
                    'error'    => $e->getMessage(),
                ]);
                $order->status = 'failed';
                $order->save();

                return response()->json(['message' => 'Voucher generation failed'], 200);
            }
        } else {
            $order->status = 'failed';
            $order->save();
        }

        return response()->json(['message' => 'Callback processed'], 200);
    }
}
