<?php
namespace App\Services;

class UserFun
{
    public static function success($code = 200, $message = 'ok') {
        return response()->json([
            'code' => $code,
            'message' => $message,
        ]);
    }

    public static function error($code = 500,$message = 'error') {
        return response()->json([
            'code' => $code,
            'message' => $message,
        ]);
    }


    public static function Json2Arr($data, $prefix = '') {
        // 如果傳進來的是字串，就 decode 一次
        if (is_string($data)) {
            $arr = json_decode($data, true);
            if (!is_array($arr)) {
                return []; // 無效 JSON，回傳空陣列或你可自訂錯誤處理
            }
        } elseif (is_array($data)) {
            $arr = $data;
        } else {
            return []; // 不是 JSON 字串也不是陣列，回傳空
        }
        $result = [];
        foreach ($arr as $key => $value) {
            $fullKey = $prefix === '' ? $key : "{$prefix}_{$key}";
            if (is_array($value)) {
                $result += self::Json2Arr($value, $fullKey);
            } else {
                $result[$fullKey] = $value;
            }
        }
        return $result;
    }

    public static function CurlGet(string $url): array
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);             // 设定请求网址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // 回传结果而不是直接输出

        $response = curl_exec($ch); // 执行请求
        $err = curl_error($ch);     // 错误信息
        curl_close($ch);            // 关闭连接

        if ($err) {
            return ['ok' => false, 'error' => $err];
        }

        return json_decode($response, true);
    }

    public static function CurlPost(string $url, array $data = []): array
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);                    // 設定請求網址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        // 回傳內容不直接輸出
        curl_setopt($ch, CURLOPT_POST, true);                  // 啟用 POST
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // POST的資料

        $response = curl_exec($ch);
        $error = curl_error($ch);
        $errno = curl_errno($ch);
        curl_close($ch);

        return [
            'ok'     => $errno === 0,
            'error'  => $error,
            'code'   => $errno,
            'body'   => $response,
        ];
    }
}
