<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\Payment\Http;

use App\Models\Setting;
use Illuminate\Http\Request;
use Plugins\Neatstudio\Payment\Models\Payment;
use Plugins\Neatstudio\Payment\Services\PaymentManager;

class PaymentController
{
    public function __construct(private PaymentManager $manager)
    {
    }

    /**
     * 发起支付：创建订单并跳转。
     */
    public function checkout(Request $request, Payment $payment)
    {
        if ($payment->user_id !== auth()->id()) {
            abort(403);
        }

        $url = $this->manager->pay($payment);

        return redirect()->away($url);
    }

    /**
     * 沙箱模拟支付页。
     */
    public function sandbox(string $orderNo)
    {
        $payment = Payment::where('order_no', $orderNo)->firstOrFail();

        return theme_view('payments.sandbox', compact('payment'));
    }

    /**
     * 沙箱确认支付。
     */
    public function sandboxConfirm(Request $request, string $orderNo)
    {
        $payment = Payment::where('order_no', $orderNo)->firstOrFail();

        $this->manager->simulatePay($payment);

        return redirect()->route('pay.result', $payment->order_no);
    }

    /**
     * 支付结果页（沙箱 / 回跳共用）。
     */
    public function result(string $orderNo)
    {
        $payment = Payment::where('order_no', $orderNo)->firstOrFail();

        return theme_view('payments.result', compact('payment'));
    }

    /**
     * 异步回调（支付宝/微信 notify）。
     */
    public function notify(Request $request, string $channel)
    {
        $result = $this->manager->handleNotify($channel, $request->all());

        return response($result);
    }

    /**
     * 同步回跳。
     */
    public function return(Request $request, string $channel)
    {
        $orderNo = $request->input('out_trade_no');

        if (! $orderNo) {
            return redirect()->route('home');
        }

        return redirect()->route('pay.result', $orderNo);
    }
}
