<?php

// 检查是否已存在此函数,避免重复定义
if (!function_exists('getDomain')) {
    /**
     * 获取当前请求的完整域名(包括协议)
     *
     * @return string
     */
    function getDomain() {
        return request()->getSchemeAndHttpHost();
    }
}

if (!function_exists('getHost')) {
    /**
     * 获取当前请求的主机名
     *
     * @return string
     */
    function getHost() {
        return request()->getHost();
    }
}

if (!function_exists('getDistId')) {

    function getDistId() {
        return app('dist')->id;
    }
}

if (!function_exists('formatDirectory')) {
    /**
     * 格式化目录名
     *
     * @param string $directory 目录名
     * @return string
     */
    function formatDirectory($directory) {
        // 如果目录名为空,返回空字符串
        if (empty($directory)) {
            return '';
        }

        // 移除前面的斜杠
        $directory = ltrim($directory, '/');

        // 确保最后添加一个斜杠
        $directory = rtrim($directory, '/') . '/';

        return $directory;
    }
}

if (!function_exists('formatAndCreateAbsoluteDirectory')) {
    /**
     * 格式化绝对路径,移除文件部分并创建目录
     *
     * @param string $path 完整的路径(可能包含文件)
     * @param int $permissions 新建目录的权限(默认为 0755)
     * @return string 格式化后的绝对路径
     */
    function formatAndCreateAbsoluteDirectory($path, $permissions = 0755) {
        // 如果路径为空,返回空字符串
        if (empty($path)) {
            return '';
        }

        // 确保路径是绝对路径(以 / 开头)
//        if ($path[0] !== '/') {
//            throw new Exception("The path must be an absolute path starting with '/'. Provided: {$path}");
//        }

        // 检查是否包含文件部分
        if (preg_match('/\/[^\/]+\.[^\/]+$/', $path)) {
            // 如果路径中包含文件名,则移除
            $path = dirname($path);
        }

        // 确保路径以斜杠结尾
        $path = rtrim($path, '/') . '/';

        // 检查目录是否存在,如果不存在则创建
        if (!is_dir($path)) {
            if (!mkdir($path, $permissions, true)) { // true 表示递归创建中间目录
                throw new Exception("Failed to create directory: {$path}");
            }
        }

        return $path;
    }
}

if (!function_exists('generateOrderNumber')) {
    /**
     * 生成唯一订单号
     *
     * @param string $prefix 订单号前缀(可选,默认为 'ORD')
     * @return string
     */
    function generateOrderNumber($prefix = 'ORD') {
        // 获取当前日期和时间
        $date = date('YmdHis'); // 年月日时分秒

        // 生成一个随机的两位数
        $randomNumber = mt_rand(10, 99);

        // 拼接前缀、日期时间和随机数
        $orderNumber = $prefix . $date . $randomNumber;

        return $orderNumber;
    }
}