<?php

namespace WPD\Domain;

use WPD\Security\Redactor;
use WPD\WordPress\ConfigParser;
use WPD\WordPress\PathGuard;

final class ScanContext
{
    private $root;
    private $guard;
    private $config;
    private $manualDatabase;
    private $redactor;

    public function __construct($root, PathGuard $guard, ConfigParser $parser, array $manualDatabase = array())
    {
        $this->root = rtrim((string) $root, '/\\');
        $this->guard = $guard;
        $this->config = $parser->parse($this->root);
        $this->manualDatabase = $manualDatabase;

        $secrets = array();
        foreach (array('DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST') as $key) {
            if (!empty($this->config['values'][$key])) {
                $secrets[] = $this->config['values'][$key];
            }
        }
        foreach ($manualDatabase as $value) {
            $secrets[] = $value;
        }
        $this->redactor = new Redactor($secrets, $this->root);
    }

    public function root()
    {
        return $this->root;
    }

    public function guard()
    {
        return $this->guard;
    }

    public function config()
    {
        return $this->config;
    }

    public function databaseCredentials()
    {
        if (!empty($this->manualDatabase['name']) && !empty($this->manualDatabase['user']) && isset($this->manualDatabase['password']) && !empty($this->manualDatabase['host'])) {
            return array(
                'name' => (string) $this->manualDatabase['name'],
                'user' => (string) $this->manualDatabase['user'],
                'password' => (string) $this->manualDatabase['password'],
                'host' => (string) $this->manualDatabase['host'],
                'prefix' => !empty($this->manualDatabase['prefix']) ? (string) $this->manualDatabase['prefix'] : (string) $this->config['table_prefix'],
                'source' => 'manual',
            );
        }

        if ($this->config['complete']) {
            return array(
                'name' => (string) $this->config['values']['DB_NAME'],
                'user' => (string) $this->config['values']['DB_USER'],
                'password' => (string) $this->config['values']['DB_PASSWORD'],
                'host' => (string) $this->config['values']['DB_HOST'],
                'prefix' => (string) $this->config['table_prefix'],
                'source' => 'wp-config.php',
            );
        }
        return null;
    }

    public function redactor()
    {
        return $this->redactor;
    }

    public function wordpressVersion()
    {
        $file = $this->guard->safeFile($this->root . '/wp-includes/version.php');
        if ($file === null || !is_readable($file)) {
            return null;
        }
        $source = @file_get_contents($file, false, null, 0, 131072);
        if (is_string($source) && preg_match('/\$wp_version\s*=\s*([\'\"])([^\'\"]+)\1\s*;/', $source, $match)) {
            return $match[2];
        }
        return null;
    }
}

