<style>
    body {
        background-color: #333333;
        color: white;
    }
</style>
<?php
// Simple Script to create a MySQL View.

define("INITIALIZATION_FILE_NAME", "../xml/settings.xml");

// Retrieve Application Settings

$applicationSettings = simplexml_load_file(INITIALIZATION_FILE_NAME);

if (empty($applicationSettings)) {
    echo "Unable to load Application Settings." . PHP_EOL;
    exit();
}

// Connect to the Database.

if ($applicationSettings->Environment == 'Production') {
    $host = 'localhost';
} else {
    $host = '192.168.1.190';
}


$database = (string) $applicationSettings->DatabaseName;
$user = (string) $applicationSettings->DatabaseUser;
$password = (string) $applicationSettings->DatabasePassword;

try {
    $connection = new PDO("mysql:host={$host};dbname={$database}", $user, $password);
} catch (PDOException | Exception $e) {
    echo "Unable to connect to the database. <br/>";
    echo "Error is: {$e->getMessage()}";
    exit();
}

// Retrieve the View Names.

$views = array();

$directory = ".";

if (is_dir($directory)) {

    if ($handle = opendir($directory)) {

        while (false !== ($filename = readdir($handle))) {

            if ($filename != "." && $filename != ".." && !is_dir("{$directory}/{$filename}")) {

                if (substr($filename, 0, 5) !== "view_") {
                    continue;
                }

                $views[] = $filename;
            }
        }

        closedir($handle);
    }
}

if (count($views) === 0) {
    echo "No views found. Views not created.";
    exit();
}

// Create the Views

$created = 0;
$not_created = 0;

foreach ($views as $view) {

    if ((include "{$view}") != true) {
        echo "{$view} not found. View not created <br/>.";
        continue;
    }

    $view = str_replace(".php", "", $view);

    $connection->exec("drop view if exists {$view}");
    $connection->exec($SQL);

    if ($connection->errorCode() != 0) {
        $not_created++;
        echo "Error creating view {$view}: <br/>";
        echo "<pre>";
        print_r($connection->errorInfo());
        echo "<br/>";
    } else {
        $created++;
        echo "{$view} was created. <br/>";
    }
}

echo "<br/> {$created} Views were created. {$not_created} were not created due to errors.";
?>