<?php

// ====================
// Migrate RDI Users
// ====================

class Migrate_Users {

    // Variables

    private $log = "";
    private $settings = "";
    private $olddb_connection = "";
    private $newdb_connection = "";

    // ==================
    // Class Constructor.
    // ==================

    public function __construct() {

        // Open the Log

        $this->log = fopen("../scripts/rdiusers.log", "w+");

        if ($this->log === false) {

            error_log("RDI Users : Unable to open log file");
            exit();
        }

        $this->log(str_repeat("*", 50));

        // Get Settings

        $this->settings = new SimpleXMLElement((file_exists("../xml/settings.xml") ? file_get_contents("../xml/settings.xml") : "<settings/>"));

        if ($this->settings->count() === 0) {

            error_log("RDI Users : Unable to initialize settings");
            exit();
        }

        // Open Database Connections

        $this->olddb_connection = $this->connect_olddb();
        $this->newdb_connection = $this->connect_newdb();
    }

    // ================================================
    // Return a Old DEC-DR Database Database Connection
    // ================================================

    public function connect_olddb() {

        try {

            $host = (string) $this->settings->OldDatabaseServer;
            $database = (string) $this->settings->OldDatabaseName;
            $user = (string) $this->settings->OldDatabaseUser;
            $password = (string) $this->settings->OldDatabasePassword;

            $connection = new PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);

            $connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException | Exception $e) {

            trigger_error($e->getMessage());
        }

        return $connection;
    }

    // ================================================
    // Return a New DEC-DR Database Database Connection
    // ================================================

    public function connect_newdb() {

        try {

            $host = (string) $this->settings->DatabaseServer;
            $database = (string) $this->settings->DatabaseName;
            $user = (string) $this->settings->DatabaseUser;
            $password = (string) $this->settings->DatabasePassword;

            $connection = new PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);

            $connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException | Exception $e) {

            trigger_error($e->getMessage());
        }

        return $connection;
    }

    // =============================
    // Log a message to the Log File
    // =============================

    private function log($message = "") {

        fwrite($this->log, date("Y-m-d H:i A") . " : " . "{$message} \n");
    }

    // ===================
    // Process Parcel Data
    // ===================

    public function process() {

        $this->log("Starting Migration of RDI Users");

        $this->migrateUsers();

        $this->log("RDI Users Migration Process Complete");
    }

    // ====================
    // Migrate RDI Users
    // ====================

    private function migrateUsers() {

        $this->log("Processing decweb Users");

        $users = $this->getUsers();

        $SQL = "INSERT INTO users (
                            user_id,
                            user_name,
                            user_email, 
                            user_password,
                            user_role,
                            user_change_password, 
                            user_active,
                            user_creator,
                            user_created )
                   VALUES (
                            :user_id,
                            :user_name,
                            :user_email, 
                            :user_password,
                            :user_role,
                            :user_change_password, 
                            :user_active,
                            :user_creator,
                            :user_created ) ";

        $statement = $this->newdb_connection->prepare($SQL);

        $counter = 0;

        foreach ($users as $user) {

            $user_id = $user['UserName'];
            $user_name = $user['UserName'];
            $user_email = $user['Email'];
            $user_password = $user['Password'];
            $user_role = "User";
            $user_change_password = 0;
            $user_active = 1;
            $user_creator = "Migrated";
            $user_created = date("Y-m-d H:i:s");

            $user_password = password_hash($user_password, PASSWORD_DEFAULT);

            $statement->bindValue(':user_id', $user_id);
            $statement->bindValue(':user_name', $user_name);
            $statement->bindValue(':user_email', $user_email);
            $statement->bindValue(':user_password', $user_password);
            $statement->bindValue(':user_role', $user_role);
            $statement->bindValue(':user_change_password', $user_change_password, PDO::PARAM_BOOL);
            $statement->bindValue(':user_active', $user_active, PDO::PARAM_BOOL);
            $statement->bindValue(':user_creator', $user_creator);
            $statement->bindValue(':user_created', $user_created);

            $statement->execute();

            $counter++;

            // Issue an update message every 10 records

            if (($counter % 10) == 0) {
                $this->log("Processed $counter records... ");
            }
        }
    }

    // =====================
    // Return a Users Object
    // =====================

    private function getUsers() {

        $SQL = "select * from Users_tbl";

        $users = $this->connect_olddb()->query($SQL)->fetchAll(PDO::FETCH_ASSOC);

        return $users;
    }
}

?>