<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\PaymentAttempt;
use App\Services\AnalyticsTracker;
use App\Services\MockPaymentGatewayService;
use Illuminate\Http\Request;
use RuntimeException;

class MockPaymentController extends Controller
{
    public function show(Request $request, Order $order, MockPaymentGatewayService $gateway, AnalyticsTracker $analytics)
    {
        abort_unless(! $order->user_id || $request->user()?->id === $order->user_id || $request->user()?->isAdmin(), 403);

        try {
            $attempt = $gateway->initiate($order);
        } catch (RuntimeException $exception) {
            return redirect()->route('orders.show', $order)->withErrors(['payment' => $exception->getMessage()]);
        }

        $analytics->track($request, 'payment_started', 'order', $order->id, [
            'gateway' => 'mock_gateway',
            'attempt_id' => $attempt->id,
            'amount_minor' => $attempt->amount_minor,
        ]);

        return view('payments.mock', [
            'order' => $order->load('items'),
            'attempt' => $attempt,
        ]);
    }

    public function confirm(Request $request, PaymentAttempt $paymentAttempt, MockPaymentGatewayService $gateway, AnalyticsTracker $analytics)
    {
        abort_unless(! $paymentAttempt->order->user_id || $request->user()?->id === $paymentAttempt->order->user_id || $request->user()?->isAdmin(), 403);

        try {
            $order = $gateway->confirm($paymentAttempt);
        } catch (RuntimeException $exception) {
            return back()->withErrors(['payment' => $exception->getMessage()]);
        }

        $analytics->track($request, 'payment_completed', 'order', $order->id, [
            'gateway' => $paymentAttempt->gateway,
            'attempt_id' => $paymentAttempt->id,
        ]);

        return redirect()->route('orders.show', $order)->with('status', 'تم تأكيد الدفع التجريبي.');
    }

    public function fail(Request $request, PaymentAttempt $paymentAttempt, MockPaymentGatewayService $gateway, AnalyticsTracker $analytics)
    {
        abort_unless(! $paymentAttempt->order->user_id || $request->user()?->id === $paymentAttempt->order->user_id || $request->user()?->isAdmin(), 403);

        try {
            $order = $gateway->fail($paymentAttempt);
        } catch (RuntimeException $exception) {
            return back()->withErrors(['payment' => $exception->getMessage()]);
        }

        $analytics->track($request, 'payment_failed', 'order', $order->id, [
            'gateway' => $paymentAttempt->gateway,
            'attempt_id' => $paymentAttempt->id,
        ]);

        return redirect()->route('orders.show', $order)->withErrors(['payment' => 'تم رفض الدفع التجريبي.']);
    }
}
