<?php namespace Phpcmf\Controllers\Admin;
/**
 * https://www.besyun.com
 * BESCMS
 * 本文件是框架系统文件，二次开发时不可以修改本文件
 **/

class Payapi extends \Phpcmf\Common
{

    public function index() {

        $data = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'payapi')->get()->getRowArray();
        $data = dr_string2array($data['value']);

        if (IS_AJAX_POST) {
            $post = \Phpcmf\Service::L('input')->post('data');

            \Phpcmf\Service::M()->db->table('member_setting')->replace([
                'name' => 'payapi',
                'value' => dr_array2string($post)
            ]);
            \Phpcmf\Service::M('cache')->sync_cache('member'); // 自动更新缓存
            $this->_json(1, dr_lang('操作成功'));
        }

        $local = dr_dir_map(ROOTPATH.'api/pay/', 1);
        foreach ($local as $dir) {
            if ($dir != 'finecms' && is_file(ROOTPATH.'api/pay/'.$dir.'/config.php')) {
                $config = require ROOTPATH.'api/pay/'.$dir.'/config.php';
                if ($data[$dir]) {
                    $data[$dir]['config'] = $config;
                } else {
                    $data[$dir] = [
                        'config' => $config,
                    ];
                }
            }
        }

        \Phpcmf\Service::V()->assign([
            'data' => $data,
            'form' => dr_form_hidden(),
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu(
                [
                    '支付接口' => ['pay/payapi/index', 'fa fa-code'],
                    'help' => [387]
                ]
            ),
        ]);
        \Phpcmf\Service::V()->display('payapi.html');
    }

    /**
     * 检测微信退款 API 证书是否可用
     */
    public function check_cert() {

        $cert = trim((string)\Phpcmf\Service::L('input')->get('sslcert_path'));
        $key = trim((string)\Phpcmf\Service::L('input')->get('sslkey_path'));

        $default_cert = ROOTPATH.'api/pay/weixin/cert/apiclient_cert.pem';
        $default_key = ROOTPATH.'api/pay/weixin/cert/apiclient_key.pem';

        if ($cert === '') {
            $row = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'payapi')->get()->getRowArray();
            $payapi = dr_string2array($row['value']);
            if (!empty($payapi['weixin']['sslcert_path'])) {
                $cert = $payapi['weixin']['sslcert_path'];
            }
        }
        if ($key === '') {
            if (!isset($payapi)) {
                $row = \Phpcmf\Service::M()->db->table('member_setting')->where('name', 'payapi')->get()->getRowArray();
                $payapi = dr_string2array($row['value']);
            }
            if (!empty($payapi['weixin']['sslkey_path'])) {
                $key = $payapi['weixin']['sslkey_path'];
            }
        }

        if ($cert === '') {
            $cert = $default_cert;
        }
        if ($key === '') {
            $key = $default_key;
        }

        $errors = [];
        if (!is_file($cert)) {
            $errors[] = dr_lang('证书文件不存在').'：'.$cert;
        } elseif (!is_readable($cert)) {
            $errors[] = dr_lang('证书文件不可读').'：'.$cert;
        } else {
            $cert_body = (string)@file_get_contents($cert);
            if (strpos($cert_body, 'BEGIN CERTIFICATE') === false) {
                $errors[] = dr_lang('证书文件不是有效的 PEM 格式').'：'.$cert;
            } elseif (function_exists('openssl_x509_read')) {
                $x509 = @openssl_x509_read($cert_body);
                if (!$x509) {
                    $errors[] = dr_lang('证书文件无法被 OpenSSL 解析').'：'.$cert;
                }
            }
        }

        if (!is_file($key)) {
            $errors[] = dr_lang('密钥文件不存在').'：'.$key;
        } elseif (!is_readable($key)) {
            $errors[] = dr_lang('密钥文件不可读').'：'.$key;
        } else {
            $key_body = (string)@file_get_contents($key);
            if (strpos($key_body, 'PRIVATE KEY') === false) {
                $errors[] = dr_lang('密钥文件不是有效的 PEM 格式').'：'.$key;
            } elseif (function_exists('openssl_pkey_get_private')) {
                $pkey = @openssl_pkey_get_private($key_body);
                if (!$pkey) {
                    $errors[] = dr_lang('密钥文件无法被 OpenSSL 解析').'：'.$key;
                }
            }
        }

        if ($errors) {
            $this->_json(0, implode('<br>', $errors));
        }

        $this->_json(1, dr_lang('证书可用').'：'.$cert.' / '.$key);
    }

}
