<?php
#require_once '../lib/Licensees.php';
require_once '/home/oregon56/public_html/boasearch/lib/Licensees.php';

class UploadData {
    var $firmsFileName;
    var $individualsFileName;
    var $firms = array();
    var $individuals = array();
    var $licenseesManager;

    function __construct($env) {
        $this->licenseesManager = new Licensees($env);
    }
    function prepareDatabase() {
        echo "... creating NEW tables .... \n";
        if (!$this->licenseesManager->createNewTables()) {
            $this->errorOut("The individuals_new and firms_new tables still exist. ".
                "Please remove these tables before continuing.\n");
        }
    }
    function setFirmsFileName($fn) {
        $this->firmsFileName = $fn;
    }
    function setIndividualsFileName($fn) {
        $this->individualsFileName = $fn;
    }
    function loadData() {
        $this->loadFirmsData();
        $this->loadIndividualsData();
        $this->saveData();
    }
    function loadFirmsData() {
        echo "... loading firms data .... \n";

        $row = 1;
        if (($handle = fopen($this->firmsFileName, "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//if (count($data) != 20) {
//    echo "yo\n".print_r($data);
//}
                if (count($data) == 20) {
                    $firm = new stdClass();
                    $firm->id = $this->f($data[1]);
                    $firm->name = $this->f($data[2]);
                    $firm->type = $this->f($data[3]);
                    $firm->date_granted = $this->f($data[4]);
                    $firm->date_expires = $this->f($data[5]);
                    $firm->owner = $this->f($data[6]);
                    $firm->complaints = $this->f($data[9]);
                    $firm->address = $this->f($data[11]);
                    $firm->city = $this->f($data[12]);
                    $firm->state = $this->f($data[13]);
                    $firm->zip = $this->f($data[14]);
                    $firm->status = $this->f($data[18]);

                    $row++;
                    array_push($this->firms, $firm);
                }


            }
            fclose($handle);
        } else {
            $this->errorOut("there was an issue with opening the file -- ".$this->firmsFileName.". \n");
        }
    }
    function loadIndividualsData() {
        echo "... loading individual data .... \n";

        $row = 1;
        if (($handle = fopen($this->individualsFileName, "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

//                if ($row >8356 && $row < 8360) {
//                    print_r($data);
//                }
//                if ($row == 5) {
//                    return;
//                }
                $row++;

                if (count($data) == 30) {
                    $individual = new stdClass();
                    $individual->id = $this->f($data['0']);
                    $individual->license_no = $this->f($data['1']);
                    $individual->type = $this->f($data['2']);
                    $individual->last_name = $this->f($data['3']);
                    $individual->first_name = $this->f($data['4']);
                    $individual->middle_name = $this->f($data['5']);
                    $individual->full_name = $this->ucf($this->f($data['4'])) . " " . $this->ucf($this->f($data['3']));
                    $individual->full_name2 = $this->ucf($this->f($data['3'])) . ", ". $this->ucf($this->f($data['4'])) . " " . $this->ucf($this->f($data['5']));
                    $individual->firm_name = $this->f($data['6']);
                    $individual->date_licensed = $this->f($data['7']);
                    $individual->date_expires = $this->f($data['8']);
                    $individual->status = $this->f($data['9']);
                    $individual->firm_id = $this->f($data['10']);
                    $individual->complaints = $this->f($data['15']);

                    if (strtolower($this->f($data['11'])) == 'work') {
                        $individual->address1 = $this->f($data['16']);
                        $individual->address2 = $this->f($data['17']);
                        $individual->city = $this->f($data['18']);
                        $individual->state = $this->f($data['19']);
                        $individual->zip = $this->f($data['20']);

                    } else {
                        $individual->address1 = $this->f($data['21']);
                        $individual->address2 = $this->f($data['22']);
                        $individual->city = $this->f($data['23']);
                        $individual->state = $this->f($data['24']);
                        $individual->zip = $this->f($data['25']);

                    }
//                    $individual->aa = $this->f($data['32']);
                    $individual->muni = $this->f($data['26']);
                    $individual->cpe_carryover = $this->f($data['29']);

                    array_push($this->individuals, $individual);
                }


            }
            fclose($handle);
        } else {
            $this->errorOut("there was an issue with opening the file -- ".$this->individualsFileName.". \n");
        }
    }
    function f($field) {
        // remove surrounding white space
        $f = trim($field);
/*
        $letters = str_split($f);
        foreach ($letters as $l) {
            if (ord($l) > 127) {
                echo " we have an unprintable character, and it is ".ord($l)."!!! in this string: $f\n\n";
            }
        }
  */
        // cure it of the "bad" microsoft word apostrophe
//        $f = str_replace('’', "'", $f);
        $f = str_replace(chr(194), "", $f);
        $f = str_replace(chr(146), "'", $f);


        return $f;
    }
    function saveData() {
        echo "... saving data .... \n";

        $this->saveIndividualData();
        $this->saveFirmData();

    }
    function saveIndividualData() {
        echo "... saving individuals .... \n";

        foreach ($this->individuals as $i) {
            $this->licenseesManager->insertIndividual($i);
        }
    }
    function saveFirmData() {
        echo "... saving firms .... \n";

        foreach ($this->firms as $f) {
            $this->licenseesManager->insertFirm($f);

        }
    }
    function swapOldForNew() {
        $this->licenseesManager->renameTables();
    }

    function errorOut($m) {
        $fe = fopen('php://stderr', 'w');
        fwrite($fe, $m);
        fclose($fe);
        exit(1);
    }
    function ucf($s) {
        $s = trim($s);
        if (empty($s)) {
            return $s;
        }
        $xx = explode(" ", $s);
        $ns = "";
        // is it more than one word?
        if (count($xx) > 1) {
            for ($i = 0; $i < count($xx); $i++) {
                // check to see if it's a word like der van den de la von
                $x = strtolower($xx[$i]);
                if ($x === "der"
                    || $x == "van"
                    || $x == "den"
                    || $x == "de"
                    || $x == "la"
                ) {
                    $ns .= " ".$x;
                    // check to see if it's ii or iii or iv
                } elseif ($x == "ii"
                    || $x == "iii"
                    || $x == "iv"
                ) {
                    $ns .= " ".strtoupper($x);
                } else {
                    if ($x != '') {
                        $ns .= " ".ucfirst($x);
                    }
                }
            }
        } else {
            $ns = ucfirst(strtolower($s));
            // check to see if it has an '
            $res = preg_match_all("/([A-Za-z]*)'([A-Za-z]*)/i", $s, $matches);
            if ($res == 1) {
                $ns = ucfirst(strtolower($matches[1][0])) . "'" . ucfirst(strtolower($matches[2][0]));

            }
            // check to see if beginning is mc
            if (substr($s, 0, 2) === "MC") {
                $ns = "Mc" . ucfirst(strtolower(substr($s, 2)));
            }
            // capitalize on [ ][a-z] and on ['][a-z]
        }
        // does it have a hyphen?
        $xx = explode("-", $ns);
        if (count($xx) > 1) {
                $capitalized_hyphenated_parts = array();
                for ($i = 0; $i < count($xx); $i++) {
                        array_push($capitalized_hyphenated_parts, ucfirst($xx[$i]));
                }
                $ns = implode("-", $capitalized_hyphenated_parts);
        }
        return trim($ns);
    }
}
