<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Financial\Enums\PaymentMethod;
use App\Domain\Financial\Enums\PaymentStatus;
use App\Domain\Financial\Models\Invoice;
use App\Domain\Financial\Models\Payment;
use App\Domain\Financial\Services\PaymobService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    public function initiate(Request $request, PaymobService $paymobService): JsonResponse
    {
        $request->validate([
            'invoice_uuid' => 'required|string',
        ]);

        if (!$paymobService->isConfigured()) {
            return response()->json([
                'error' => 'payment_not_configured',
                'message' => 'الدفع الإلكتروني غير مفعل حالياً',
            ], 503);
        }

        $user = $request->user();

        $invoice = Invoice::where('uuid', $request->invoice_uuid)
            ->whereIn('status', ['sent', 'partially_paid', 'overdue'])
            ->where('balance_due', '>', 0)
            ->first();

        if (!$invoice) {
            return response()->json([
                'error' => 'invoice_not_found',
                'message' => 'الفاتورة غير موجودة أو مدفوعة بالكامل',
            ], 404);
        }

        try {
            $result = $paymobService->createPaymentIntention($invoice, $user);

            // Create pending payment record
            Payment::create([
                'academy_id' => $invoice->academy_id,
                'branch_id' => $invoice->branch_id ?? null,
                'invoice_id' => $invoice->id,
                'reference' => 'PMB-' . $result['order_id'],
                'direction' => 'inbound',
                'method' => PaymentMethod::Online,
                'status' => PaymentStatus::Pending,
                'payer_type' => $invoice->billable_type,
                'payer_id' => $invoice->billable_id,
                'amount' => $invoice->balance_due,
                'currency' => 'EGP',
                'payment_date' => now()->toDateString(),
                'gateway_data' => [
                    'provider' => 'paymob',
                    'paymob_order_id' => $result['order_id'],
                    'payment_key' => substr($result['payment_key'], 0, 20) . '...',
                ],
                'created_by' => $user->id,
            ]);

            return response()->json([
                'payment_key' => $result['payment_key'],
                'iframe_url' => $result['iframe_url'],
                'order_id' => $result['order_id'],
                'amount' => $invoice->balance_due,
            ]);
        } catch (\Throwable $e) {
            Log::error('[Paymob] Payment initiation failed', [
                'invoice_uuid' => $invoice->uuid,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'error' => 'payment_failed',
                'message' => 'فشل في بدء عملية الدفع، يرجى المحاولة لاحقاً',
            ], 500);
        }
    }

    public function callback(Request $request, PaymobService $paymobService): JsonResponse
    {
        $data = $request->all();

        Log::info('[Paymob] Callback received', ['data' => $data]);

        // Extract transaction data from nested structure
        $transactionData = $data['obj'] ?? $data;

        if (!$paymobService->verifyCallback($transactionData)) {
            Log::warning('[Paymob] HMAC verification failed', $data);
            return response()->json(['status' => 'invalid_hmac'], 400);
        }

        $payment = $paymobService->processSuccessfulPayment($transactionData);

        if ($payment) {
            return response()->json(['status' => 'processed', 'payment_id' => $payment->id]);
        }

        return response()->json(['status' => 'ignored']);
    }
}
