<?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":

                $import_type = filter_input(INPUT_POST, "import_type") ?: "incremental";

                $XSLParms['IMPORT-TYPE'] = $import_type;

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

                break;

            case "upload":

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

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

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

                // Process the Attachment

                if (empty($_FILES["csvfile"])) {
                    $this->displayNotice("No CSV file was uploaded.");
                    return;
                }

                if (!is_dir($environment_directory) && !mkdir($environment_directory, 0775, true)) {
                    $this->displayNotice("Unable to create the upload directory. Please contact Support.");
                    return;
                }

                if ($_FILES["csvfile"]["error"] !== UPLOAD_ERR_OK) {
                    $this->displayNotice("The CSV file upload failed. Please try again.");
                    return;
                }

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

                if (empty($tempname) or empty($filename)) {
                    $this->displayNotice("The uploaded CSV file could not be read. Please try again.");
                    return;
                }

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

                if (!move_uploaded_file($tempname, $file_directory)) {
                    $this->displayNotice("Unable to save the uploaded CSV file. Please contact Support.");
                    return;
                }

                if ($upload_type === 'incremental') {
                    $this->parseCSVFile($file_directory);
                    $content = $this->applyXSL("", $this->getXSL("uploadMessage"), $XSLParms);
                    $this->displayContent($content);
                    return;
                }

                if ($upload_type === 'full') {

                    $successful = $this->createImportRequest($file_directory);

                    if (!$successful) {
                        $this->displayNotice("An error occurred while creating the import request. Please contact Support.");
                        return;
                    }

                    $this->displayNotice("Your import has been queued. You will receive a notification when it is complete.");
                    return;
                }

                $this->displayNotice("Invalid upload type. Please contact Support.");

                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 permits (
                                permit_permit_facts_id,
                                permit_entry_date,
                                permit_permit_number,
                                permit_permit_date,
                                permit_project_addr,
                                permit_sub_div_name,
                                permit_project_type,
                                permit_company,
                                permit_address,
                                permit_city,
                                permit_state,
                                permit_zip,
                                permit_phone,
                                permit_project_city,
                                permit_project_state,
                                permit_size,
                                permit_units,
                                permit_building_type,
                                permit_value,
                                permit_work_type,
                                permit_county,
                                permit_lot,
                                permit_dist_ll,
                                permit_ct1,
                                permit_owner_name,
                                permit_owner_address,
                                permit_owner_city,
                                permit_owner_state,
                                permit_owner_zip,
                                permit_owner_phone,
                                permit_ytd_permits,
                                permit_ytd_value,
                                permit_12mth_prev_permits )

                           VALUES (
                                :permit_permit_facts_id,
                                :permit_entry_date,
                                :permit_permit_number,
                                :permit_permit_date,
                                :permit_project_addr,
                                :permit_sub_div_name,
                                :permit_project_type,
                                :permit_company,
                                :permit_address,
                                :permit_city,
                                :permit_state,
                                :permit_zip,
                                :permit_phone,
                                :permit_project_city,
                                :permit_project_state,
                                :permit_size,
                                :permit_units,
                                :permit_building_type,
                                :permit_value,
                                :permit_work_type,
                                :permit_county,
                                :permit_lot,
                                :permit_dist_ll,
                                :permit_ct1,
                                :permit_owner_name,
                                :permit_owner_address,
                                :permit_owner_city,
                                :permit_owner_state,
                                :permit_owner_zip,
                                :permit_owner_phone,
                                :permit_ytd_permits,
                                :permit_ytd_value,
                                :permit_12mth_prev_permits )";

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

            $statement->bindValue(":permit_permit_facts_id", $PermitFactsId);
            $statement->bindValue(":permit_permit_number", $PermitNumber);
            $statement->bindValue(":permit_entry_date", $EntryDate);
            $statement->bindValue(":permit_permit_date", $PermitDate);
            $statement->bindValue(":permit_project_addr", $ProjectAddress);
            $statement->bindValue(":permit_sub_div_name", $SubdivisionName);
            $statement->bindValue(":permit_project_type", $ProjectType);
            $statement->bindValue(":permit_company", $Company);
            $statement->bindValue(":permit_address", $Address);
            $statement->bindValue(":permit_city", $City);
            $statement->bindValue(":permit_state", $State);
            $statement->bindValue(":permit_zip", $Zip);
            $statement->bindValue(":permit_phone", $Phone);
            $statement->bindValue(":permit_project_city", $ProjectCity);
            $statement->bindValue(":permit_project_state", $ProjectState);
            $statement->bindValue(":permit_size", $Size);
            $statement->bindValue(":permit_units", $Units);
            $statement->bindValue(":permit_building_type", $BuildingType);
            $statement->bindValue(":permit_value", $Value);
            $statement->bindValue(":permit_work_type", $WorkType);
            $statement->bindValue(":permit_county", $County);
            $statement->bindValue(":permit_lot", $Lot);
            $statement->bindValue(":permit_dist_ll", $DistrictLL);
            $statement->bindValue(":permit_ct1", $Ctl);
            $statement->bindValue(":permit_owner_name", $OwnerName);
            $statement->bindValue(":permit_owner_address", $OwnerAddress);
            $statement->bindValue(":permit_owner_city", $OwnerCity);
            $statement->bindValue(":permit_owner_state", $OwnerState);
            $statement->bindValue(":permit_owner_zip", $OwnerZip);
            $statement->bindValue(":permit_owner_phone", $OwnerPhone);
            $statement->bindValue(":permit_ytd_permits", $YTDPermits);
            $statement->bindValue(":permit_ytd_value", $YTDValue);
            $statement->bindValue(":permit_12mth_prev_permits", $TwelveMonthPreviousPermits);

            $statement->execute();

            $RecordCount++;
        }

        return true;
    }

    // =====================
    // Create Import Request
    // =====================

    public function createImportRequest($filepath = "") {

        if (!$filepath) {
            return false;
        }

        $SQL = "insert into importjobs

                         (  importjob_file_path,
                            importjob_notified,
                            importjob_creator,
                            importjob_created )

                  VALUES ( :importjob_file_path,
                           :importjob_notified,
                           :importjob_creator,
                           :importjob_created )";

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

        $statement->bindValue(":importjob_file_path", $filepath, PDO::PARAM_STR);
        $statement->bindValue(":importjob_notified", false, PDO::PARAM_BOOL);
        $statement->bindValue(":importjob_creator", $this->current_user_name, PDO::PARAM_STR);
        $statement->bindValue(":importjob_created", $this->getTimestamp());

        if (!$statement->execute()) {
            return false;
        }

        $to = $this->getSettings()->DeveloperEmail;
        $subject = "CSV Import Jobs Queued";
        $message = "Import initialized successfully. Processing will start momentarily.";

        (new Email())->sendEmail($to, $subject, $message);

        return true;
    }

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

    public function fixDate($givenDate) {

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

        return $formattedDate;
    }
}

?>
