<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

namespace Core\Lib;

class RefundService
{
    public static function ensureTable($db)
    {
        return true;
    }

    public static function statusMap()
    {
        return [
            0 => ['待审核', 'badge-warning'],
            1 => ['已同意', 'badge-primary'],
            2 => ['已拒绝', 'badge-danger'],
            3 => ['已人工退款', 'badge-success'],
        ];
    }

    public static function apply($db, $memberId, $orderId, $reason)
    {
        self::ensureTable($db);
        $memberId = intval($memberId);
        $orderId = intval($orderId);
        $reason = trim((string) $reason);

        if ($memberId <= 0 || $orderId <= 0) {
            return ['code' => 400, 'msg' => '参数错误'];
        }
        if ($reason === '') {
            return ['code' => 400, 'msg' => '请填写退款原因'];
        }

        $order = $db->fetch("SELECT * FROM {$db->table('order')} WHERE id = ? AND member_id = ?", [$orderId, $memberId]);
        if (!$order) {
            return ['code' => 404, 'msg' => '订单不存在'];
        }
        if (!in_array(intval($order['status']), [1, 2, 3], true)) {
            return ['code' => 400, 'msg' => '当前订单状态不能申请退款'];
        }

        $exists = $db->fetch("SELECT id, status FROM {$db->table('order_refund')} WHERE order_id = ? AND member_id = ? AND status IN (0,1,3) LIMIT 1", [$orderId, $memberId]);
        if ($exists) {
            return ['code' => 400, 'msg' => '该订单已有退款申请'];
        }

        $amount = isset($order['pay_price']) ? floatval($order['pay_price']) : floatval($order['total_amount'] ?? 0);
        $now = time();
        $db->insert('order_refund', [
            'order_id' => $orderId,
            'order_sn' => $order['order_sn'] ?? '',
            'member_id' => $memberId,
            'amount' => $amount,
            'reason' => $reason,
            'status' => 0,
            'create_time' => $now,
            'update_time' => $now,
        ]);

        if (function_exists('sendMemberMessage')) {
            try {
                \sendMemberMessage($memberId, '退款申请已提交', '订单 ' . ($order['order_sn'] ?? $orderId) . ' 的退款申请已提交，我们会尽快审核。');
            } catch (\Throwable $e) {
                error_log('Refund notification failed: ' . $e->getMessage());
            }
        }

        return ['code' => 200, 'msg' => '退款申请已提交'];
    }

    public static function updateStatus($db, $refundId, $status, $adminRemark = '')
    {
        self::ensureTable($db);
        $refundId = intval($refundId);
        $status = intval($status);
        $adminRemark = trim((string) $adminRemark);

        if ($refundId <= 0 || !in_array($status, [1, 2, 3], true)) {
            return ['code' => 400, 'msg' => '参数错误'];
        }

        $refund = $db->fetch("SELECT * FROM {$db->table('order_refund')} WHERE id = ?", [$refundId]);
        if (!$refund) {
            return ['code' => 404, 'msg' => '退款申请不存在'];
        }

        $now = time();
        $data = [
            'status' => $status,
            'admin_remark' => $adminRemark,
            'update_time' => $now,
        ];
        if ($status === 1 || $status === 2) {
            $data['audit_time'] = $now;
        }
        if ($status === 3) {
            $data['refund_time'] = $now;
        }

        $db->update('order_refund', $data, 'id = ?', [$refundId]);
        $notices = [
            1 => ['退款申请已通过', '退款申请已审核通过，请留意后续退款进度。'],
            2 => ['退款申请未通过', '退款申请未通过。'],
            3 => ['退款已完成', '退款已处理完成，请留意原支付账户到账情况。'],
        ];
        $notice = $notices[$status];
        $content = '订单 ' . ($refund['order_sn'] ?? $refund['order_id']) . '：' . $notice[1];
        if ($adminRemark !== '') { $content .= "\n备注：" . $adminRemark; }
        if (function_exists('sendMemberMessage')) {
            try {
                \sendMemberMessage(intval($refund['member_id']), $notice[0], $content);
            } catch (\Throwable $e) {
                error_log('Refund notification failed: ' . $e->getMessage());
            }
        }
        return ['code' => 200, 'msg' => '退款状态已更新'];
    }
}
