<style>
    body {
        background-color: #333333;
        color: white;
        font-family: sans-serif;
        padding: 1em;
    }

    .success {
        color: #8fd19e;
    }

    .error {
        color: #ff9999;
    }
</style>

<?php
define("INITIALIZATION_FILE_NAME", "../xml/settings.xml");

// Load Application Settings

$applicationSettings = simplexml_load_file(INITIALIZATION_FILE_NAME);

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

// Connect to Database

$host = ((string) $applicationSettings->Environment === "Production") ? "localhost" : "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};charset=utf8mb4",
            $user,
            $password,
            [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]
    );
} catch (PDOException | Exception $e) {
    echo "Unable to connect to the database.";
    exit();
}

// Get View Files

$views = glob("view_*.php");

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

sort($views);

// Create Views

$created = 0;
$not_created = 0;

foreach ($views as $viewFile) {

    $viewName = basename($viewFile, ".php");

    if (!preg_match('/^view_[a-zA-Z0-9_]+$/', $viewName)) {
        echo "<div class='error'>Invalid view file skipped: " . htmlspecialchars($viewFile, ENT_QUOTES, "UTF-8") . "</div>";
        $not_created++;
        continue;
    }

    $SQL = null;

    include $viewFile;

    if (empty($SQL)) {
        echo "<div class='error'>No SQL found in {$viewFile}. View not created.</div>";
        $not_created++;
        continue;
    }

    try {
        $connection->exec("DROP VIEW IF EXISTS `{$viewName}`");
        $connection->exec($SQL);

        $created++;

        echo "<div class='success'>" . htmlspecialchars($viewName, ENT_QUOTES, "UTF-8") . " was created.</div>";
    } catch (PDOException | Exception $e) {

        $not_created++;

        echo "<div class='error'>Error creating " . htmlspecialchars($viewName, ENT_QUOTES, "UTF-8") . ".</div>";
    }
}

echo "<br/>";
echo htmlspecialchars("{$created} views were created. {$not_created} were not created due to errors.", ENT_QUOTES, "UTF-8");
?>