<?php

declare(strict_types=1);

namespace ShieldX\Support;

defined('ABSPATH') || exit;

final class WordPressPaths
{
    public static function root(): string
    {
        $root = '';

        if (function_exists('get_home_path')) {
            $root = (string) get_home_path();
        }

        if ($root === '' && defined('ABSPATH')) {
            $root = (string) ABSPATH;
        }

        return self::normalizeDirectory($root);
    }

    public static function contentDir(): string
    {
        if (defined('SHIELDX_CONTENT_DIR')) {
            return self::normalizeDirectory((string) SHIELDX_CONTENT_DIR);
        }

        $fromUploads = self::contentDirFromUploads();
        if ($fromUploads !== '') {
            return $fromUploads;
        }

        $pluginParent = self::pluginParentDir();
        return $pluginParent !== '' ? self::normalizeDirectory(dirname($pluginParent)) : '';
    }

    public static function pluginParentDir(): string
    {
        if (defined('SHIELDX_PLUGINS_DIR')) {
            return self::normalizeDirectory((string) SHIELDX_PLUGINS_DIR);
        }

        if (defined('SHIELDX_PLUGIN_FILE')) {
            $pluginFile = (string) SHIELDX_PLUGIN_FILE;
            if ($pluginFile !== '') {
                if (function_exists('plugin_dir_path')) {
                    return self::normalizeDirectory(dirname(plugin_dir_path($pluginFile)));
                }

                return self::normalizeDirectory(dirname(dirname($pluginFile)));
            }
        }

        if (defined('SHIELDX_PLUGIN_DIR')) {
            return self::normalizeDirectory(dirname(rtrim((string) SHIELDX_PLUGIN_DIR, '/\\')));
        }

        return '';
    }

    public static function adminIncludesPath(string $file): string
    {
        $file = trim(str_replace('\\', '/', $file));
        if ($file === '' || strpos($file, "\0") !== false || strpos($file, '..') !== false || strpos($file, '/') !== false) {
            return '';
        }

        $root = self::root();
        return $root !== '' ? $root . '/wp-admin/includes/' . $file : '';
    }

    public static function normalizeDirectory(string $path): string
    {
        $path = trim(str_replace('\\', '/', $path));

        return $path !== '' ? rtrim($path, '/') : '';
    }

    private static function contentDirFromUploads(): string
    {
        if (!function_exists('wp_upload_dir')) {
            return '';
        }

        $uploads = wp_upload_dir(null, false);
        if (!is_array($uploads) || empty($uploads['basedir']) || !is_scalar($uploads['basedir'])) {
            return '';
        }

        $baseDir = self::normalizeDirectory((string) $uploads['basedir']);
        $marker = '/uploads';
        $position = strpos($baseDir . '/', $marker . '/');

        return $position !== false ? self::normalizeDirectory(substr($baseDir, 0, (int) $position)) : '';
    }
}
