<?php
if (!defined('ABSPATH')) {
    exit;
}

final class DdvWpStorage
{
    public static function baseDir()
    {
        if (defined('DD_VERIFACTU_STORAGE_DIR') && trim((string) DD_VERIFACTU_STORAGE_DIR) !== '') {
            return rtrim((string) DD_VERIFACTU_STORAGE_DIR, '/\\');
        }
        $siteId = function_exists('get_current_blog_id') ? max(1, (int) get_current_blog_id()) : 1;
        return rtrim(WP_CONTENT_DIR, '/\\') . '/ddverifactu-private/site-' . $siteId;
    }

    public static function ensure()
    {
        $base = self::baseDir();
        foreach (array($base, $base . '/certs', $base . '/xml', $base . '/qr') as $dir) {
            if (!is_dir($dir) && !wp_mkdir_p($dir)) {
                throw new Exception('No se ha podido crear el almacen privado VeriFactu: ' . $dir);
            }
            @chmod($dir, 0750);
            self::protect($dir);
        }
        return true;
    }

    public static function path($subdir, $filename = '')
    {
        self::ensure();
        $subdir = trim(preg_replace('/[^A-Za-z0-9_-]/', '', (string) $subdir));
        $dir = self::baseDir() . ($subdir !== '' ? '/' . $subdir : '');
        if ($filename === '') {
            return $dir;
        }
        return $dir . '/' . basename((string) $filename);
    }

    private static function protect($dir)
    {
        $files = array(
            '.htaccess' => "Deny from all\n<IfModule mod_authz_core.c>\nRequire all denied\n</IfModule>\n",
            'index.php' => "<?php\nhttp_response_code(404);\nexit;\n",
            'web.config' => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration><system.webServer><security><authorization><remove users=\"*\" roles=\"\" verbs=\"\"/><add accessType=\"Deny\" users=\"*\"/></authorization></security></system.webServer></configuration>\n",
        );
        foreach ($files as $name => $contents) {
            $path = $dir . '/' . $name;
            if (!is_file($path)) {
                @file_put_contents($path, $contents, LOCK_EX);
            }
        }
    }
}
