<?php
namespace App\Controllers;

use Core\Payment\GatewayFactory;
use Core\Payment\OrderService;

/** 支付网关异步通知（无需登录） */
class PayController extends Controller
{
    public function notify($channel)
    {
        if ($channel === 'alipay') {
            $gw = GatewayFactory::make('alipay');
            $no = $gw->verifyNotify($_POST);
            if ($no) {
                OrderService::markPaid($no, $_POST['trade_no'] ?? '', 'alipay');
                echo 'success';
            } else {
                echo 'fail';
            }
        } elseif ($channel === 'wechat') {
            $xml = file_get_contents('php://input');
            $data = $this->xmlToArray($xml);
            $gw = GatewayFactory::make('wechat');
            $no = $gw->verifyNotify($data);
            if ($no) {
                OrderService::markPaid($no, $data['transaction_id'] ?? '', 'wechat');
                echo '<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>';
            } else {
                echo '<xml><return_code><![CDATA[FAIL]]></return_code></xml>';
            }
        } else {
            echo 'invalid';
        }
        exit;
    }

    private function xmlToArray($xml)
    {
        $r = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        return $r ? json_decode(json_encode($r), true) : [];
    }
}
