<?php

// ====================
// Migrate Permit Facts
// ====================

class Migrate_PermitFacts {

    // Variables

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

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

    public function __construct() {

        // Open the Log

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

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

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

        $this->migratePermitFacts();

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

    // ====================
    // Migrate Permit Facts
    // ====================

    private function migratePermitFacts() {

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

        $permitfacts = $this->getPermitFacts();

        $SQL = "INSERT INTO permitfacts (
                             permitfact_legacy_id,
                             permitfact_entry_date,
                             permitfact_permit_number,
                             permitfact_permit_date,
                             permitfact_county,
                             permitfact_project_address,
                             permitfact_project_name,
                             permitfact_project_type,
                             permitfact_project_city,
                             permitfact_project_state,
                             permitfact_project_zip,
                             permitfact_company,
                             permitfact_address,
                             permitfact_city,
                             permitfact_state,
                             permitfact_zip,
                             permitfact_phone,
                             permitfact_size,
                             permitfact_value,
                             permitfact_work_type,
                             permitfact_building_type,
                             permitfact_lot_block,
                             permitfact_dist_ll,
                             permitfact_owner_name,
                             permitfact_owner_address,
                             permitfact_owner_city,
                             permitfact_owner_state,
                             permitfact_owner_zip,
                             permitfact_owner_phone,
                             permitfact_creator,
                             permitfact_created )
                   VALUES (
                            :permitfact_legacy_id,
                            :permitfact_entry_date,
                            :permitfact_permit_number,
                            :permitfact_permit_date,
                            :permitfact_county,
                            :permitfact_project_address,
                            :permitfact_project_name,
                            :permitfact_project_type,
                            :permitfact_project_city,
                            :permitfact_project_state,
                            :permitfact_project_zip,
                            :permitfact_company,
                            :permitfact_address,
                            :permitfact_city,
                            :permitfact_state,
                            :permitfact_zip,
                            :permitfact_phone,
                            :permitfact_size,
                            :permitfact_value,
                            :permitfact_work_type,
                            :permitfact_building_type,
                            :permitfact_lot_block,
                            :permitfact_dist_ll,
                            :permitfact_owner_name,
                            :permitfact_owner_address,
                            :permitfact_owner_city,
                            :permitfact_owner_state,
                            :permitfact_owner_zip,
                            :permitfact_owner_phone,
                            :permitfact_creator,
                            :permitfact_created ) ";

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

        $counter = 0;

        foreach ($permitfacts as $permitfact) {

            $permitfact_legacy_id       = $permitfact['PermitFactsID']                                 ?? null;
            $permitfact_entry_date      = $permitfact['EntryDate']                                     ?? null;
            $permitfact_permit_number   = $permitfact['PermitNum']                                     ?? null;
            $permitfact_permit_date     = $permitfact['PermitDate']                                    ?? null;
            $permitfact_county          = $this->getCountyByCountyName($permitfact['County'])          ?? null;
            $permitfact_project_address = $permitfact['ProjectAddr']                                   ?? null;
            $permitfact_project_name    = $permitfact['ProjectName']                                   ?? null;
            $permitfact_project_type    = $this->getDropdownSerialByValue($permitfact['ProjectType'])  ?? null;
            $permitfact_project_city    = $this->getCityByCityName($permitfact['ProjectCity'])         ?? null;
            $permitfact_project_state   = $permitfact['ProjectState']                                  ?? null;
            $permitfact_project_zip     = $permitfact['ProjectZip']                                    ?? null;
            $permitfact_company         = $permitfact['Company']                                       ?? null;
            $permitfact_address         = $permitfact['Address']                                       ?? null;
            $permitfact_city            = $this->getCityByCityName($permitfact['City'])                ?? null;
            $permitfact_state           = $permitfact['State']                                         ?? null;
            $permitfact_zip             = $permitfact['Zip']                                           ?? null;
            $permitfact_phone           = $this->normailizePhoneNumber($permitfact['Phone'])           ?? null;
            $permitfact_size            = $permitfact['Size']                                          ?? null;
            $permitfact_value           = $permitfact['Value']                                         ?? null;
            $permitfact_work_type       = $this->getDropdownSerialByValue($permitfact['WorkType'])     ?? null;
            $permitfact_building_type   = $this->getDropdownSerialByValue($permitfact['BldgType'])     ?? null;
            $permitfact_lot_block       = $permitfact['Lot_BLK']                                       ?? null;
            $permitfact_dist_ll         = $permitfact['Dist_LL']                                       ?? null;
            $permitfact_owner_name      = $permitfact['OwnerName']                                     ?? null;
            $permitfact_owner_address   = $permitfact['OwnerAddress']                                  ?? null;
            $permitfact_owner_city      = $this->getCityByCityName($permitfact['OwnerCity'])           ?? null;
            $permitfact_owner_state     = $permitfact['OwnerState']                                    ?? null;
            $permitfact_owner_zip       = $permitfact['OwnerZip']                                      ?? null;
            $permitfact_owner_phone     = $this->normailizePhoneNumber($permitfact['OwnerPhone'])      ?? null;

            $statement->bindValue(':PermitFactsID',              $permitfact_legacy_id,        PDO::PARAM_STR);
            $statement->bindValue(':permitfact_entry_date',      $permitfact_entry_date,        PDO::PARAM_STR);
            $statement->bindValue(':permitfact_permit_number',   $permitfact_permit_number,     PDO::PARAM_STR);
            $statement->bindValue(':permitfact_permit_date',     $permitfact_permit_date,       PDO::PARAM_STR);
            $statement->bindValue(':permitfact_county',          $permitfact_county,            PDO::PARAM_INT);
            $statement->bindValue(':permitfact_project_address', $permitfact_project_address,   PDO::PARAM_STR);
            $statement->bindValue(':permitfact_project_name',    $permitfact_project_name,      PDO::PARAM_STR);
            $statement->bindValue(':permitfact_project_type',    $permitfact_project_type,      PDO::PARAM_INT);
            $statement->bindValue(':permitfact_project_city',    $permitfact_project_city,      PDO::PARAM_INT);
            $statement->bindValue(':permitfact_project_state',   $permitfact_project_state,     PDO::PARAM_STR);
            $statement->bindValue(':permitfact_project_zip',     $permitfact_project_zip,       PDO::PARAM_STR);
            $statement->bindValue(':permitfact_company',         $permitfact_company,           PDO::PARAM_STR);
            $statement->bindValue(':permitfact_address',         $permitfact_address,           PDO::PARAM_STR);
            $statement->bindValue(':permitfact_city',            $permitfact_city,              PDO::PARAM_INT);
            $statement->bindValue(':permitfact_state',           $permitfact_state,             PDO::PARAM_STR);
            $statement->bindValue(':permitfact_zip',             $permitfact_zip,               PDO::PARAM_STR);
            $statement->bindValue(':permitfact_phone',           $permitfact_phone,             PDO::PARAM_STR);
            $statement->bindValue(':permitfact_size',            $permitfact_size,              PDO::PARAM_INT);
            $statement->bindValue(':permitfact_value',           $permitfact_value,             PDO::PARAM_STR);
            $statement->bindValue(':permitfact_work_type',       $permitfact_work_type,         PDO::PARAM_INT);
            $statement->bindValue(':permitfact_building_type',   $permitfact_building_type,     PDO::PARAM_INT);
            $statement->bindValue(':permitfact_lot_block',       $permitfact_lot_block,         PDO::PARAM_STR);
            $statement->bindValue(':permitfact_dist_ll',         $permitfact_dist_ll,           PDO::PARAM_STR);
            $statement->bindValue(':permitfact_owner_name',      $permitfact_owner_name,        PDO::PARAM_STR);
            $statement->bindValue(':permitfact_owner_address',   $permitfact_owner_address,     PDO::PARAM_STR);
            $statement->bindValue(':permitfact_owner_city',      $permitfact_owner_city,        PDO::PARAM_INT);
            $statement->bindValue(':permitfact_owner_state',     $permitfact_owner_state,       PDO::PARAM_STR);
            $statement->bindValue(':permitfact_owner_zip',       $permitfact_owner_zip,         PDO::PARAM_STR);
            $statement->bindValue(':permitfact_owner_phone',     $permitfact_owner_phone,       PDO::PARAM_STR);
            $statement->bindValue(':permitfact_creator',         'Migration',                   PDO::PARAM_STR);
            $statement->bindValue(':permitfact_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
    }

    // ============================
    // Return a Permit Facts Object
    // ============================

    private function getPermitFacts() {

        $SQL = "select * from PermitFacts_tbl";

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

        return $permitfacts;
    }

    // =================================
    // Return a Permit 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 Permit 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 Permit 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;
    }
}


?>