<?php
/**
 * Copyright (c) 2017 Serhii Borodai <clarifying@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 *
 */

$alerts = [];
set_error_handler(function (int $errno , string $errstr, string $errfile, int $errline, array $errcontext ) use (&$alerts) {
    ob_start();
?>
    <div class="alert alert-danger">
        <ul>
            <li>
                Error # :<?= $errno ?>
            </li>
            <li>
                Message : <?= $errstr ?>
            </li>
            <li>
                File : <?= $errfile ?>
            </li>
            <li>
                Line : <?= $errline ?>
            </li>
            <li>
                Context : <?= print_r($errcontext, true) ?>
            </li>
        </ul>
    </div>
<?php
    $alerts[] = ob_get_contents();
    ob_end_clean();
    return true;
});

chdir(dirname(__DIR__));

error_reporting(E_ALL);

require 'vendor/autoload.php';
/** @var \Interop\Container\ContainerInterface $container */
$container = require 'config/container.php';

$extensions = [
    'mbstring',
    'gettext',
    'intl',
    'mysqli',
    'pdo_mysql',
    'zip-enabled' => function () {
        return class_exists('ZipArchive');
    }
];

//echo '<pre>';
/**
 * @return string
 */
function migrationStatus() {
    $phinx = new \Phinx\Wrapper\TextWrapper(new Phinx\Console\PhinxApplication(), ['configuration' => 'config/phinx.php', 'parser' => 'php']);
    $output = call_user_func([$phinx, 'getStatus'], null, null);
    return $output;
}

/**
 * @param \Interop\Container\ContainerInterface $container
 * @return array
 */
function checkDb(\Interop\Container\ContainerInterface $container) {
    $result = [];

    /** @var \Zend\Db\Adapter\Adapter $db */
    $db = $container->get(Zend\Db\Adapter\Adapter::class);

    $result = [
        'dbname' => $db->getCurrentSchema(),
        'platform' => $db->getDriver()->getDatabasePlatformName(),
    ];


    return $result;
}

/**
 * @param $extensions
 * @return array
 */
function checkExtensions($extensions) {
    $result = [];
    foreach ($extensions as $key => $extension) {
        if (is_object($extension)) {
            $result[$key] = $extension();
        } else {
            $result[$extension] = extension_loaded($extension);
        }
    }
    return $result;
}

/**
 * @param $dir
 * @return array
 */
function checkDir($dir) {
    touch($dir . '/test.file');
    $result = file_exists($dir . '/test.file');
    $resultDelete = unlink($dir . '/test.file');
    return [
        'create' => $result,
        'delete' => $resultDelete
    ];
}

/**
 * @return array
 */
function checkZip() {
    $zip = new ZipArchive();
    $zipName = 'data/testarc.zip';
    $resultCreateZip = $zip->open($zipName, ZipArchive::CREATE);
    $resultAddFirstFile = $zip->addFromString('manual.html', 'just a test string');
    $resultAddSecondFile = $zip->addFromString('counter.js', 'just a test string');
    $resultCloseZip = $zip->close();
    $fp =  file_get_contents($zipName);
    $resultReadZip = false;
    if ($fp) {
        $resultReadZip = true;
    }
    $resultDeleteZip = unlink($zipName);

    return [
        'create' => $resultCreateZip,
        'delete' => $resultDeleteZip,
        'close' => $resultCloseZip,
        'add-first' => $resultAddFirstFile,
        'add-second' => $resultAddSecondFile,
        'read' => $resultReadZip,

    ];
}

$extensionsTest = checkExtensions($extensions);

$accessDataDir = checkDir('data');
$accessCounterDir = checkDir('data/counter');
$accessTmpDir = checkDir('/tmp');
$accessLocaleDir = checkDir('data/locale');
$accessLocaleEnDir = checkDir('data/locale/en');

if ($extensionsTest['zip-enabled'] && $accessDataDir['create']) {
    $zipTest = checkZip();
} else {
    $zipTest = [
        'create' => null,
        'delete' => null,
        'close' => null,
        'add-first' => null,
        'add-second' => null,
        'read' => null,
    ];
}


$dbStatus = checkDb($container);
$migrationStatus = migrationStatus();

?>
<html>
<head>
    <title>AddCPM install status</title>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
    <script type="text/javascript" src="/js/jquery.min.js"></script>
    <script type="text/javascript" src="/js/bootstrap.min.js"></script>
</head>
<body>
<div class="row">
    <div class="panel panel-primary">
        <div class="panel-heading">
            Check install
        </div>
        <div class="panel-body">
            <table class="table">
                <tr>
                    <td>Access <strong>data</strong> directory</td>
                    <td class="<?= $accessDataDir['create'] ? 'text-primary' : 'text-danger' ?>">
                        Create file: <?= $accessDataDir['create'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $accessDataDir['delete'] ? 'text-primary' : 'text-danger' ?>">
                        Delete file: <?= $accessDataDir['delete'] ? 'true' : 'false' ?>
                    </td>
                </tr>
                <tr>
                    <td>Access <strong>data/counter</strong> directory</td>
                    <td class="<?= $accessCounterDir['create'] ? 'text-primary' : 'text-danger' ?>">
                        Create file: <?= $accessCounterDir['create'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $accessCounterDir['delete'] ? 'text-primary' : 'text-danger' ?>">
                        Delete file: <?= $accessCounterDir['delete'] ? 'true' : 'false' ?>
                    </td>
                </tr>
                <tr>
                    <td>Access <strong>data/locale</strong> directory</td>
                    <td class="<?= $accessLocaleDir['create'] ? 'text-primary' : 'text-danger' ?>">
                        Create file: <?= $accessLocaleDir['create'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $accessLocaleDir['delete'] ? 'text-primary' : 'text-danger' ?>">
                        Delete file: <?= $accessLocaleDir['delete'] ? 'true' : 'false' ?>
                    </td>
                </tr>
                <tr>
                    <td>Access <strong>data/locale/en</strong> directory</td>
                    <td class="<?= $accessLocaleEnDir['create'] ? 'text-primary' : 'text-danger' ?>">
                        Create file: <?= $accessLocaleEnDir['create'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $accessLocaleEnDir['delete'] ? 'text-primary' : 'text-danger' ?>">
                        Delete file: <?= $accessLocaleEnDir['delete'] ? 'true' : 'false' ?>
                    </td>
                </tr>
                <tr>
                    <td>Access <strong>/tmp/</strong> directory</td>
                    <td class="<?= $accessTmpDir['create'] ? 'text-primary' : 'text-danger' ?>">
                        Create file: <?= $accessTmpDir['create'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $accessTmpDir['delete'] ? 'text-primary' : 'text-danger' ?>">
                        Delete file: <?= $accessTmpDir['delete'] ? 'true' : 'false' ?>
                    </td>
                </tr>
                <tr>
                    <td>Create <strong>ZIP archive</strong></td>
                    <td class="<?= $zipTest['create'] ? 'text-primary' : 'text-danger' ?>">
                        Create zip: <?= $zipTest['create'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $zipTest['add-first'] && $zipTest['add-second'] ? 'text-primary' : 'text-danger' ?>">
                        Add file: <?= $zipTest['add-first'] && $zipTest['add-second'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $zipTest['close'] ? 'text-primary' : 'text-danger' ?>">
                        Close zip: <?= $zipTest['close'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $zipTest['read'] ? 'text-primary' : 'text-danger' ?>">
                        Read zip: <?= $zipTest['read'] ? 'true' : 'false' ?>
                    </td>
                    <td class="<?= $zipTest['delete'] ? 'text-primary' : 'text-danger' ?>">
                        Delete zip: <?= $zipTest['delete'] ? 'true' : 'false' ?>
                    </td>
                </tr>
                <tr>
                    <td>
                        Database
                    </td>
                    <?php foreach ($dbStatus as $name => $value) { ?>
                        <td><?= $name ?> : <?= $value ?></td>
                    <?php } ?>
                </tr>
                <tr class="text-info">
                    <td> Migration status </td>
                    <td colspan="10"><pre><?= $migrationStatus ?></pre></td>
                </tr>
                <tr>
                    <td rowspan="<?= count($extensionsTest) + 1 ?>">
                        Extensions & options
                    </td>
                </tr>
                <?php foreach ($extensionsTest as $name => $status) { ?>
                    <tr>
                        <td class="<?= $status ? 'text-primary' : 'text-danger'?>">
                            <?= $name ?>: <?= $status ? 'true' : 'false' ?>
                        </td>
                    </tr>
                <?php }?>
            </table>
        </div>
    </div>
</div>
<div class="row">
    <div class="panel panel-info">
        <div class="panel-heading">
            <div class="panel-title">Errors list</div>
        </div>
        <div class="panel-body">
            <?php foreach ($alerts as $alert) {
                echo $alert;
            }
            ?>
        </div>
    </div>

</div>

</body>
</html>
