<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Create System Tables</title>
        <style>
            body {
                background-color: #333;
                color: white;
                font-family: sans-serif;
                padding: 1em;
            }
            .log {
                margin-bottom: 1em;
            }
        </style>
    </head>
    <body>

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

        // Load Application Settings
        $applicationSettings = simplexml_load_file(INITIALIZATION_FILE_NAME);

        if (empty($applicationSettings)) {
            echo "<div class='log'>❌ Unable to load Application Settings.</div>";
            exit();
        }

        // Database Connection
        $host = (string) $applicationSettings->DatabaseServer;
        $database = (string) $applicationSettings->DatabaseName;
        $user = (string) $applicationSettings->DatabaseUser;
        $password = (string) $applicationSettings->DatabasePassword;

        try {
            $connection = new PDO("mysql:host={$host};dbname={$database}", $user, $password);
            $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            // Disable foreign key checks temporarily
            $connection->exec("SET FOREIGN_KEY_CHECKS = 0");
        } catch (PDOException | Exception $e) {
            echo "<div class='log'>❌ Unable to connect to the database.<br/>Error: {$e->getMessage()}</div>";
            exit();
        }

        // Get all table definition files
        $tableFiles = array_diff(scandir("."), ['.', '..', '_createSystemTable.php', '_createTable.php']);

        foreach ($tableFiles as $tableFile) {
            $tableName = basename($tableFile, ".php");
            echo "<div class='log'>Processing <strong>{$tableName}</strong>...</div>";

            try {
                $connection->exec("DROP VIEW IF EXISTS `view_{$tableName}`");
            } catch (PDOException $e) {
                echo "<div class='log'>⚠️ Error dropping view view_{$tableName}: {$e->getMessage()}</div>";
            }

            try {
                $connection->exec("DROP TABLE IF EXISTS `{$tableName}`");
            } catch (PDOException $e) {
                echo "<div class='log'>⚠️ Error dropping table {$tableName}: {$e->getMessage()}</div>";
            }

            $SQL = null;

            if (!include $tableFile) {
                echo "<div class='log'>❌ Failed to include {$tableFile}. Skipping.</div>";
                continue;
            }

            runSQL($SQL, $connection, $tableName);

            switch ($tableFile) {
                case 'popovers.php':
                    $sqlQueries = [
                        // (same array from before)
                        "INSERT INTO popovers (popover_name, popover_title, popover_placeholder, popover_text, popover_created, popover_creator) 
                    VALUES ('find_user', 'Find User', 'Find User...', '<p>Find by Name, Email, or Role</p>', CURDATE(), 'Init Script')",
                        "INSERT INTO popovers (popover_name, popover_title, popover_placeholder, popover_text, popover_created, popover_creator) 
                    VALUES ('find_report', 'Find Report', 'Find Report...', '<p>Find by Name or Description</p>', CURDATE(), 'Init Script')",
                        "INSERT INTO popovers (popover_name, popover_title, popover_placeholder, popover_text, popover_created, popover_creator) 
                    VALUES ('select_report', 'Select Report', 'Find Report...', '<p>Find by Name, Email, or Role</p>', CURDATE(), 'Init Script')",
                        "INSERT INTO popovers (popover_name, popover_title, popover_placeholder, popover_text, popover_created, popover_creator) 
                    VALUES ('find_popover', 'Find Popover', 'Find Popover...', '<p>Find by Name, Title or Placeholder</p>', CURDATE(), 'Init Script')",
                        "INSERT INTO popovers (popover_name, popover_title, popover_placeholder, popover_text, popover_created, popover_creator) 
                    VALUES ('find_journal', 'Find Journal', 'Find Journal...', '<p>Find by Name, Email, or Role</p>', CURDATE(), 'Init Script')",
                        "INSERT INTO popovers (popover_name, popover_title, popover_placeholder, popover_text, popover_created, popover_creator) 
                    VALUES ('find_status', 'Find Status', 'Find Status...', '<p>Find by Name</p>', CURDATE(), 'Init Script')",
                        "INSERT INTO popovers (popover_name, popover_title, popover_placeholder, popover_text, popover_created, popover_creator) 
                    VALUES ('find_dropdowntype', 'Find Dropdown Types', 'Find Dropdown Types...', '<p>Search for dropdown types</p>', CURDATE(), 'Init Script')"
                    ];

                    foreach ($sqlQueries as $sql) {
                        runSQL($sql, $connection, "popovers data");
                    }
                    break;

                case 'users.php':
                    $password = password_hash("349Jamot@", PASSWORD_DEFAULT);
                    $sql = "INSERT INTO users (user_id, user_name, user_email, user_password, user_role, user_change_password, user_active, user_creator, user_created) 
                    VALUES ('jric11', 'James Richie', 'james.richie@onesourceits.com', '{$password}', 'Administrator', 0, 1, 'Init Script', CURDATE())";
                    runSQL($sql, $connection, "initial admin user");
                    break;

                default:
                    // Nothing extra
                    break;
            }
        }

        echo "<div class='log'><strong>✅ System Tables Created.</strong></div>";

        /**
         * Executes a SQL query and handles error output
         */
        function runSQL($SQL, $connection, $context = 'query') {
            try {
                $connection->exec($SQL);
            } catch (PDOException $e) {
                echo "<div class='log'>❌ Error running {$context}: {$e->getMessage()}</div>";
                exit();
            }
        }
        ?>

    </body>
</html>
