<?php

namespace BtwInstaller;

use Illuminate\Support\Facades\Artisan;
use Symfony\Component\Translation\Loader\PhpFileLoader;
use Symfony\Component\Translation\Translator;

class BlueTwilightInstaller
{
    private $baseDirectory;
    private $licenseInfo;

    public function __construct()
    {
        $this->baseDirectory = dirname(__DIR__);

        // Display errors so installer never gets a WSOD!
        ini_set('display_errors', true);

        require $this->baseDirectory . '/vendor/autoload.php';
    }

    public function run()
    {
        $licenseFile = new \SplFileInfo(sprintf('%s/blue-twilight.lic', $this->baseDirectory));
        if (!$licenseFile->isReadable())
        {
            return $this->needLicense();
        }

        try
        {
            $this->licenseInfo = $this->verifyLicense();
        }
        catch (\Exception $ex)
        {
            unlink($licenseFile->getRealPath());
            return $this->needLicense();
        }

        $environmentFile = new \SplFileInfo(sprintf('%s/.env', $this->baseDirectory));
        if (!$environmentFile->isReadable())
        {
            return $this->needEnvironmentSetup();
        }
    }

    private function needEnvironmentSetup()
    {
        if ($_SERVER['REQUEST_METHOD'] != 'POST')
        {
            return $this->render('database-connection');
        }
        else
        {
            $rc = Artisan::call('migrate');
            $output = Artisan::output();

            var_dump($rc);
            var_dump($output);
        }
    }

    private function needLicense()
    {
        if ($_SERVER['REQUEST_METHOD'] != 'POST')
        {
            return $this->render('license');
        }
        else
        {
            move_uploaded_file($_FILES['license-file']['tmp_name'], sprintf('%s/blue-twilight.lic', $this->baseDirectory));
            header(sprintf('Location: %s', $_SERVER['REQUEST_URI']), true, 302);
            die();
        }
    }

    private function render($viewName)
    {
        $viewName = pathinfo($viewName, PATHINFO_BASENAME);
        $viewPath = sprintf('%s/resources/views/installer/%s.php', $this->baseDirectory, $viewName);

        $translator = new Translator('en');
        $translator->addLoader('file', new PhpFileLoader());
        $translator->addResource('file', sprintf('%s/resources/lang/en/installer.php', $this->baseDirectory), 'en');
        $licenseInfo = $this->licenseInfo;

        require $viewPath;
    }

    private function verifyLicense()
    {
        return (require $this->baseDirectory . '/verify-license.php');
    }
}

$installer = new BlueTwilightInstaller();
$installer->run();