<?php

// ======================
// Migrate Business Facts
// ======================

class Migrate_BusinessFacts {

    // Variables

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

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

    public function __construct() {

        // Open the Log

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

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

            error_log("Business Facts : 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("Business Facts : 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 Business Facts");

        $this->migrateBusinessFacts();

        $this->log("Business Facts Migration Process Complete");
    }

    // ====================
    // Migrate Business Facts
    // ====================

    private function migrateBusinessFacts() {

        $this->log("Processing Business Facts");

        $businessfacts = $this->getBusinessFacts();

        $SQL = "INSERT INTO businessfacts (
                            businessfact_legacy_id,
                            businessfact_company,
                            businessfact_address_one,
                            businessfact_address_two,
                            businessfact_city,
                            businessfact_state,
                            businessfact_zip,
                            businessfact_county,
                            businessfact_phone,
                            businessfact_fax,
                            businessfact_email_address,
                            businessfact_business_class,
                            businessfact_action,
                            businessfact_employee_count,
                            businessfact_inception,
                            businessfact_sic_code,
                            businessfact_contact_name,
                            businessfact_contact_title,
                            businessfact_license_date,
                            businessfact_home_based_business,
                            businessfact_year_established,
                            businessfact_entry_date,
                            businessfact_creator,
                            businessfact_created ) 
                            
                 VALUES (   :businessfact_legacy_id,
                            :businessfact_company,
                            :businessfact_address_one,
                            :businessfact_address_two,
                            :businessfact_city,
                            :businessfact_state,
                            :businessfact_zip,
                            :businessfact_county,
                            :businessfact_phone,
                            :businessfact_fax,
                            :businessfact_email_address,
                            :businessfact_business_class,
                            :businessfact_action,
                            :businessfact_employee_count,
                            :businessfact_inception,
                            :businessfact_sic_code,
                            :businessfact_contact_name,
                            :businessfact_contact_title,
                            :businessfact_license_date,
                            :businessfact_home_based_business,
                            :businessfact_year_established,
                            :businessfact_entry_date,
                            :businessfact_creator,
                            :businessfact_created )";

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

        $counter = 0;

        foreach ($businessfacts as $businessfact) {

            $businessfact_legacy_id = $businessfact['BizFactsRecordID'] ?? null;
            $businessfact_company = $businessfact['Company'] ?? null;
            $businessfact_address_one = $businessfact['Address1'] ?? null;
            $businessfact_address_two = $businessfact['Address2'] ?? null;
            $businessfact_city = $this->getCityByCityName($businessfact['City']) ?? null;
            $businessfact_state = $businessfact['State'] ?? null;
            $businessfact_zip = $businessfact['Zip'] ?? null;
            $businessfact_county = $this->getCountyByCountyName($businessfact['County']) ?? null;
            $businessfact_phone = $this->normailizePhoneNumber($businessfact['Phone']) ?? null;
            $businessfact_fax = $this->normailizePhoneNumber($businessfact['Fax']) ?? null;
            $businessfact_email_address = $this->normailizeEmailAddress($businessfact['EmailAddress']) ?? null;
            $businessfact_business_class = $this->getDropdownSerialByValue($businessfact['BC']) ?? null;
            $businessfact_action = $this->getDropdownSerialByValue($businessfact['Description']) ?? null;
            $businessfact_employee_count = $businessfact['ES'] ?? null;
            $businessfact_inception = $businessfact['BizInception'] ?? null;
            $businessfact_sic_code = $businessfact['SIC'] ?? null;
            $businessfact_contact_name = $businessfact['ContactName'] ?? null;
            $businessfact_contact_title = $businessfact['Title'] ?? null;
            $businessfact_license_date = $businessfact['LicenseDate'] ?? null;
            $businessfact_home_based_business = $businessfact['Home'] ?? null;
            $businessfact_year_established = $businessfact['YearEst'] ?? null;
            $businessfact_entry_date = $businessfact['EntryDate'] ?? null;

            $statement->bindValue(':businessfact_legacy_id', $businessfact_legacy_id, PDO::PARAM_INT);
            $statement->bindValue(':businessfact_company', $businessfact_company, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_address_one', $businessfact_address_one, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_address_two', $businessfact_address_two, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_city', $businessfact_city, PDO::PARAM_INT);
            $statement->bindValue(':businessfact_state', $businessfact_state, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_zip', $businessfact_zip, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_county', $businessfact_county, PDO::PARAM_INT);
            $statement->bindValue(':businessfact_phone', $businessfact_phone, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_fax', $businessfact_fax, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_email_address', $businessfact_email_address, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_business_class', $businessfact_business_class, PDO::PARAM_INT);
            $statement->bindValue(':businessfact_action', $businessfact_action, PDO::PARAM_INT);
            $statement->bindValue(':businessfact_employee_count', $businessfact_employee_count, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_inception', $businessfact_inception, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_sic_code', $businessfact_sic_code, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_contact_name', $businessfact_contact_name, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_contact_title', $businessfact_contact_title, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_license_date', $businessfact_license_date, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_home_based_business', $businessfact_home_based_business, PDO::PARAM_INT);
            $statement->bindValue(':businessfact_year_established', $businessfact_year_established, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_entry_date', $businessfact_entry_date, PDO::PARAM_STR);
            $statement->bindValue(':businessfact_creator', 'Migration', PDO::PARAM_STR);
            $statement->bindValue(':businessfact_created', date("Y-m-d"), PDO::PARAM_STR);

            $statement->execute();

            $counter++;

            // Issue an update message every 1000 records

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

    // ======================
    // Normalize Phone Number
    // ======================

    private function normailizePhoneNumber($phonenumber) {

        return preg_replace('/\D+/', '', $phonenumber);  // \D = non-digit
    }

    // ======================
    // Normalize Phone Number
    // ======================

    function normailizeEmailAddress(string $email): string {
        // Split at the first #
        $clean = explode('#', $email, 2)[0];

        // Normalize case
        return strtolower(trim($clean));
    }

    // ============================
    // Return a Business Facts Object
    // ============================

    private function getBusinessFacts() {

        $SQL = "select * from BizFacts_tbl";

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

        return $businessfacts;
    }

    // =================================
    // Return a Business Facts Dues Object
    // =================================

    private function getDropdownSerialByValue($description) {

        $SQL = "select dropdown_serial from dropdowns where dropdown_value = '{$description}'";

        $dropdown_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['dropdown_serial'] ?? null;

        return $dropdown_serial;
    }

    // ============================
    // Return a Business Facts County
    // ============================

    private function getCountyByCountyName($county_name) {

        $SQL = "select county_serial from counties where county_name = '{$county_name}'";

        $county_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['county_serial'] ?? null;

        return $county_serial;
    }

    // ============================
    // Return a Business Facts City
    // ============================

    private function getCityByCityName($city_name) {

        $SQL = "select city_serial from cities where city_name = '{$city_name}'";

        $city_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['city_serial'] ?? null;

        return $city_serial;
    }
}

?>