<?php

// ============
// Import Class
// ============

class Import extends Base {

    const UPLOADS_DIRECTORY = "uploads";

    // Variables

    private $current_user_serial = 0;
    private $current_user_id = "";
    private $current_user_name = "";
    private $current_user_email = "";

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

    public function __construct() {

        set_error_handler(array($this, "displayError"));

        date_default_timezone_set(self::TIMEZONE);

        $this->current_user_serial = $_SESSION[self::USER_SERIAL] ?? 0;
        $this->current_user_id = $_SESSION[self::USER_ID] ?? "";
        $this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
        $this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
    }

    // ===============
    // Upload CSV File
    // ===============

    public function uploadCSVFile() {

        set_time_limit(0);

        $step = filter_input(INPUT_POST, "step") ?: "prompt";

        switch ($step) {

            case "prompt":

                $content = $this->applyXSL("", $this->getXSL("uploadCSVFile"));
                $this->displayContent($content);

                break;

            case "upload":

                $XSLParms['UPLOAD_STATUS'] = "UPLOAD SUCCESSFUL";
                $environment = (string) $this->getSettings()->Environment ?: "Production";

                if (empty($environment)) {
                    $this->logError("Invalid Environment ({$environment}). " . __METHOD__);
                }

                $environment_directory = self::UPLOADS_DIRECTORY . "/{$environment}";

                // Process the Attachment

                if (!empty($_FILES)) {

                    if (!is_dir($environment_directory)) {
                        mkdir($environment_directory);
                    }

                    $tempname = $_FILES["csvfile"]["tmp_name"];
                    $filename = $_FILES["csvfile"]["name"];

                    if (empty($tempname) or empty($filename)) {
                        return;
                    }

                    if (!move_uploaded_file($tempname, "{$environment_directory}/{$filename}")) {
                        $XSLParms['UPLOAD_STATUS'] = "UPLOAD FAILED";
                    }
                }

                $file_directory = "{$environment_directory}/{$filename}";

                $import = $this->parseCSVFile($file_directory);

                $content = $this->applyXSL("", $this->getXSL("uploadMessage"), $XSLParms);
                $this->displayContent($content);

                break;
        }
    }

    // ==============
    // Parse CSV File
    // ==============

    public function parseCSVFile($file) {

        $connection = $this->connect();

        $csvfile = fopen($file, 'r');

        $RecordCount = 0;

        while (($data = fgetcsv($csvfile, 0, ",", '"', '\\')) !== FALSE) {

            $PermitFactsId = $data[1];
            $EntryDate = $this->fixDate($data[2]);
            $PermitNumber = $data[4];
            $PermitDate = $this->fixDate($data[5]);
            $ProjectAddress = $data[7];
            $SubdivisionName = $data[8];
            $ProjectType = $data[9];
            $Company = substr($data[10], 0, 30);
            $Address = substr($data[11], 0, 30);
            $City = $data[12];
            $State = $data[13];
            $Zip = $data[14];
            $Phone = $data[15];
            $ProjectCity = $data[16];
            $ProjectState = $data[17];
            $Size = $data[18] ?: 0;
            $Units = $data[19];
            $BuildingType = $data[20];
            $Value = $data[21] ?: 0;
            $WorkType = $data[22];
            $County = $data[23];
            $Lot = $data[24];
            $DistrictLL = $data[25];
            $Ctl = $data[26];
            $OwnerName = substr($data[27], 0, 30);
            $OwnerAddress = substr($data[28], 0, 30);
            $OwnerCity = $data[29];
            $OwnerState = substr($data[30], 0, 2);
            $OwnerZip = $data[31];
            $OwnerPhone = $data[32];
            $YTDPermits = $data[33] ?: 0;
            $YTDValue = $data[34] ?: 0;
            $TwelveMonthPreviousPermits = $data[35] ?: 0;

            $County = (new Counties())->getCountiesByName($County)->record->county_serial;

            $SQL = "INSERT INTO rdis (
                                    rdi_permit_facts_id,
                                    rdi_entry_date,
                                    rdi_permit_number,
                                    rdi_permit_date,
                                    rdi_project_addr,
                                    rdi_sub_div_name,
                                    rdi_project_type,
                                    rdi_company,
                                    rdi_address,
                                    rdi_city,
                                    rdi_state,
                                    rdi_zip,
                                    rdi_phone,
                                    rdi_project_city,
                                    rdi_project_state,
                                    rdi_size,
                                    rdi_units,
                                    rdi_building_type,
                                    rdi_value,
                                    rdi_work_type,
                                    rdi_county,
                                    rdi_lot,
                                    rdi_dist_ll,
                                    rdi_ct1,
                                    rdi_owner_name,
                                    rdi_owner_address,
                                    rdi_owner_city,
                                    rdi_owner_state,
                                    rdi_owner_zip,
                                    rdi_owner_phone,
                                    rdi_ytd_permits,
                                    rdi_ytd_value,
                                    rdi_12mth_prev_permits ) 
                           VALUES (
                                    :rdi_permit_facts_id,
                                    :rdi_entry_date,
                                    :rdi_permit_number,
                                    :rdi_permit_date,
                                    :rdi_project_addr,
                                    :rdi_sub_div_name,
                                    :rdi_project_type,
                                    :rdi_company,
                                    :rdi_address,
                                    :rdi_city,
                                    :rdi_state,
                                    :rdi_zip,
                                    :rdi_phone,
                                    :rdi_project_city,
                                    :rdi_project_state,
                                    :rdi_size,
                                    :rdi_units,
                                    :rdi_building_type,
                                    :rdi_value,
                                    :rdi_work_type,
                                    :rdi_county,
                                    :rdi_lot,
                                    :rdi_dist_ll,
                                    :rdi_ct1,
                                    :rdi_owner_name,
                                    :rdi_owner_address,
                                    :rdi_owner_city,
                                    :rdi_owner_state,
                                    :rdi_owner_zip,
                                    :rdi_owner_phone,
                                    :rdi_ytd_permits,
                                    :rdi_ytd_value,
                                    :rdi_12mth_prev_permits )";

            $statement = $connection->prepare($SQL);

            $statement->bindValue(":rdi_permit_facts_id", $PermitFactsId);
            $statement->bindValue(":rdi_permit_number", $PermitNumber);
            $statement->bindValue(":rdi_entry_date", $EntryDate);
            $statement->bindValue(":rdi_permit_date", $PermitDate);
            $statement->bindValue(":rdi_project_addr", $ProjectAddress);
            $statement->bindValue(":rdi_sub_div_name", $SubdivisionName);
            $statement->bindValue(":rdi_project_type", $ProjectType);
            $statement->bindValue(":rdi_company", $Company);
            $statement->bindValue(":rdi_address", $Address);
            $statement->bindValue(":rdi_city", $City);
            $statement->bindValue(":rdi_state", $State);
            $statement->bindValue(":rdi_zip", $Zip);
            $statement->bindValue(":rdi_phone", $Phone);
            $statement->bindValue(":rdi_project_city", $ProjectCity);
            $statement->bindValue(":rdi_project_state", $ProjectState);
            $statement->bindValue(":rdi_size", $Size);
            $statement->bindValue(":rdi_units", $Units);
            $statement->bindValue(":rdi_building_type", $BuildingType);
            $statement->bindValue(":rdi_value", $Value);
            $statement->bindValue(":rdi_work_type", $WorkType);
            $statement->bindValue(":rdi_county", $County);
            $statement->bindValue(":rdi_lot", $Lot);
            $statement->bindValue(":rdi_dist_ll", $DistrictLL);
            $statement->bindValue(":rdi_ct1", $Ctl);
            $statement->bindValue(":rdi_owner_name", $OwnerName);
            $statement->bindValue(":rdi_owner_address", $OwnerAddress);
            $statement->bindValue(":rdi_owner_city", $OwnerCity);
            $statement->bindValue(":rdi_owner_state", $OwnerState);
            $statement->bindValue(":rdi_owner_zip", $OwnerZip);
            $statement->bindValue(":rdi_owner_phone", $OwnerPhone);
            $statement->bindValue(":rdi_ytd_permits", $YTDPermits);
            $statement->bindValue(":rdi_ytd_value", $YTDValue);
            $statement->bindValue(":rdi_12mth_prev_permits", $TwelveMonthPreviousPermits);

            $statement->execute();

            $RecordCount++;
        }

        // Run Updates on rdi joining 12 month tables

//        $this->update1();
//        $this->update2();
//        $this->update3();
//        $this->update4();
//        $this->update5();
//        $this->update6();
        
        return true;
    }

    // ========================
    // Return an Formatted Date
    // ========================

    public function fixDate($givenDate) {

        $formattedDate = date('Y-m-d', strtotime($givenDate));

        return $formattedDate;
    }

    // ========
    // Update 1
    // ========

    public function update1() {

        $sql = "UPDATE rdis AS r
            INNER JOIN vw_ytd_permits_by_builder_sf v_ytd 
                    ON r.rdi_company          = v_ytd.company
                   AND r.rdi_city             = v_ytd.city
                   AND r.rdi_state            = v_ytd.state
                   AND r.rdi_zip              = v_ytd.zip
                   SET r.rdi_ytd_permits      = v_ytd.ytd_permits, 
                       r.rdi_ytd_value        = v_ytd.ytd_value
                 WHERE r.rdi_project_type 
                  LIKE 'SINGLE%'";

        $this->executeSQL($sql);
    }

    // ========
    // Update 2
    // ========

    public function update2() {

        $sql = "UPDATE rdis AS r
             LEFT JOIN vw_ytd_permits_by_builder_sf v_ytd 
                    ON r.rdi_company          = v_ytd.company
                   AND r.rdi_city             = v_ytd.city
                   AND r.rdi_state            = v_ytd.state
                   AND r.rdi_zip              = v_ytd.zip
                   SET r.rdi_ytd_permits      = 0,
                       r.rdi_ytd_value        = 0
                 WHERE v_ytd.company IS NULL 
                   AND r.rdi_project_type
                  LIKE 'SINGLE%';";

        $this->executeSQL($sql);
    }

    // ========
    // Update 3
    // ========

    public function update3() {

        $sql = "UPDATE rdis AS r
            INNER JOIN vw_12mth_prev_permits_by_builder_sf v_12p 
                    on r.rdi_company            = v_12p.company
                   AND r.rdi_city               = v_12p.city
                   AND r.rdi_state              = v_12p.state
                   AND r.rdi_zip                = v_12p.zip
                   SET r.rdi_12mth_prev_permits = v_12p.12mth_prev_permits
                 WHERE r.rdi_project_type 
                  LIKE 'SINGLE%';";

        $this->executeSQL($sql);
    }

    // ========
    // Update 4
    // ========

    public function update4() {

        $sql = "UPDATE rdis AS r
            INNER JOIN vw_ytd_permits_by_builder_mf v_ytd 
                    ON r.rdi_company      = v_ytd.company
                   AND r.rdi_city         = v_ytd.city
                   AND r.rdi_state        = v_ytd.state
                   AND r.rdi_zip          = v_ytd.zip
                   SET r.rdi_ytd_permits  = v_ytd.ytd_permits, 
                       r.rdi_ytd_value    = v_ytd.ytd_value
                 WHERE r.rdi_project_type 
                   LIKE 'MULTI%';";

        $this->executeSQL($sql);
    }

    // ========
    // Update 5
    // ========

    public function update5() {

        $sql = "UPDATE rdis AS r
             LEFT JOIN vw_ytd_permits_by_builder_mf v_ytd 
                    ON r.rdi_company         = v_ytd.company
                   AND r.rdi_city            = v_ytd.city
                   AND r.rdi_state           = v_ytd.state
                   AND r.rdi_zip             = v_ytd.zip
                   SET r.rdi_ytd_permits     = 0, 
                       r.rdi_ytd_value       = 0
                 WHERE v_ytd.company IS NULL 
                   AND r.rdi_project_type
                  LIKE 'MULTI%';";

        $this->executeSQL($sql);
    }

    // ========
    // Update 6
    // ========

    public function update6() {

        $sql = "UPDATE rdis AS r
            INNER JOIN vw_12mth_prev_permits_by_builder_mf v_12p 
                    on r.rdi_company              = v_12p.company
                   AND r.rdi_city                 = v_12p.city
                   AND r.rdi_state                = v_12p.state
                   AND r.rdi_zip                  = v_12p.zip
                   SET r.rdi_12mth_prev_permits   = v_12p.12mth_prev_permits
                 WHERE r.rdi_project_type 
                  LIKE 'MULTI%';";

        $this->executeSQL($sql);
    }
}

?>
