<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Payment;
use App\Models\Setting;
use App\Models\TrackingUpdate;
use App\Support\NotificationManager;
use App\Support\PaymentGatewayManager;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    public function show(Request $request, Order $order)
    {
        abort_unless($order->user_id === $request->user()->id || $request->user()->isAdmin(), 403);

        $order->load(['payments', 'items.document']);
        $payment = $order->payments()->latest()->firstOrFail();

        return view('payments.show', [
            'order' => $order,
            'payment' => $payment,
            'gatewayEnabled' => (bool) Setting::getValue('payment_gateway_enabled', true),
            'demoMode' => (bool) Setting::getValue('payment_demo_mode', true),
            'methods' => PaymentGatewayManager::availableMethods(),
            'provider' => $payment->provider,
        ]);
    }

    public function pay(Request $request, Order $order)
    {
        abort_unless($order->user_id === $request->user()->id || $request->user()->isAdmin(), 403);

        $validated = $request->validate([
            'payment_method' => ['required', 'in:upi,card,netbanking'],
        ]);

        $payment = $order->payments()->latest()->firstOrFail();
        $provider = $payment->provider ?: PaymentGatewayManager::activeProvider();
        $providerOrderId = $payment->provider_order_id ?: PaymentGatewayManager::createProviderOrderId($payment);

        $payment->update([
            'provider' => $provider,
            'provider_order_id' => $providerOrderId,
            'payload' => array_merge($payment->payload ?? [], [
                'method' => $validated['payment_method'],
                'provider_order_id' => $providerOrderId,
            ]),
        ]);

        $order->update([
            'payment_provider' => $provider,
            'payment_method' => $validated['payment_method'],
        ]);

        if ((bool) Setting::getValue('payment_demo_mode', true)) {
            $providerPaymentId = strtoupper(substr($provider, 0, 3)) . '-PAY-' . str_pad((string) $payment->id, 6, '0', STR_PAD_LEFT);
            $payload = $providerOrderId . '|' . $providerPaymentId;
            $signature = PaymentGatewayManager::sign($payload, (string) PaymentGatewayManager::secretFor($provider));

            $payment->update([
                'provider_payment_id' => $providerPaymentId,
                'provider_signature' => $signature,
                'status' => 'paid',
                'paid_at' => now(),
            ]);

            $order->update([
                'payment_status' => 'paid',
            ]);

            TrackingUpdate::query()->create([
                'order_id' => $order->id,
                'status' => 'approved',
                'title' => 'Payment confirmed',
                'description' => 'Payment was confirmed in demo mode and the order is now ready for admin approval.',
                'location' => $order->address?->city,
                'created_by' => $request->user()->id,
            ]);

            NotificationManager::paymentReceived($order->fresh('user'));

            return redirect()->route('orders.show', $order)->with('status', 'Payment completed successfully in demo mode.');
        }

        return redirect()->route('payments.show', $order)->with('status', 'Provider order created. Connect the live gateway callback to complete the payment.');
    }

    public function webhook(Request $request, string $provider)
    {
        $payment = Payment::query()->where('provider_order_id', $request->input('provider_order_id'))->firstOrFail();
        $signature = (string) $request->input('signature');
        $providerPaymentId = (string) $request->input('provider_payment_id');
        $payload = $payment->provider_order_id . '|' . $providerPaymentId;

        abort_unless(PaymentGatewayManager::verify($payload, $signature, (string) PaymentGatewayManager::secretFor($provider)), 403);

        $payment->update([
            'provider_payment_id' => $providerPaymentId,
            'provider_signature' => $signature,
            'status' => $request->input('status', 'paid'),
            'paid_at' => now(),
            'payload' => array_merge($payment->payload ?? [], $request->all()),
        ]);

        $order = $payment->order;
        $order->update([
            'payment_status' => 'paid',
        ]);

        TrackingUpdate::query()->create([
            'order_id' => $order->id,
            'status' => 'approved',
            'title' => 'Payment confirmed by webhook',
            'description' => 'Webhook verified successfully for the order payment.',
            'location' => $order->address?->city,
        ]);

        NotificationManager::paymentReceived($order->fresh('user'));

        return response()->json(['ok' => true]);
    }
}
