<?php

class excelimport {
    var $filename;
    var $errorcode = '';
    var $datarows = array();
    var $fieldnames = array(); // Spaltenueberschriften

    public function __construct($filename,$fieldnames) {
        $this->filename = $filename;
        $this->fieldnames = $fieldnames;
        return $this;
    }

    public function isvalid() {
        if ($this->filename == '') {
            $this->errorcode = 'NOFILENAME_ERROR';
            return false;
        }

        if (count($this->fieldnames) < 1) {
            $this->errorcode = 'NOFIELDNAMES_ERROR';
            return false;
        }
        $data = new Spreadsheet_Excel_Reader();
        // $data->setOutputEncoding('CP1251');
        $data->setOutputEncoding('UTF-8');
        if (! $data->read($this->filename)) {
            $this->errorcode = 'PARSE_ERROR';
            return false;
        }
         
        /* Extract first line, search for fieldnames */
        $sheet = $data->sheets[0];

        $numrows=$sheet['numRows'];
        $numcols=$sheet['numCols'];

        if ($numrows < 2 || $numcols < count($this->fieldnames)) {
            $this->errorcode = 'FORMAT_ERROR';
            return false;
        }
        for ($r=1; $r <= $numrows;$r++) {
            $validfirstrow = true;
            for($c=1;$c <= count($this->fieldnames);$c++) {
                $cellvalue = trim(strtolower($sheet['cells'][$r][$c]));
                if ($cellvalue != trim(strtolower($this->fieldnames[$c-1]))) {
                    $validfirstrow = false;
                }
            }
            if ($validfirstrow) {
                $this->readdatarows($sheet,$r);
                return true;
            }
        }
        $this->errorcode = 'FORMAT_ERROR';
        return false;
    }

    private function readdatarows($sheet,$r) {
        $r++;
        $rows = array();
        while (isset($sheet['cells'][$r])) {
            $rowcells = $sheet['cells'][$r];
            $row = array();
            for ($c=0; $c < count($this->fieldnames); $c++) {
                if (isset($rowcells[$c+1])) {
                    $row[$this->fieldnames[$c]] = trim(utf8_encode($rowcells[$c+1]));
                } else {
                    $row[$this->fieldnames[$c]] = '';
                }
            }
            /* check if row is just empty values */
            $empty = true;
            for ($c=0; $c < count($this->fieldnames); $c++) {
                if ($row[$this->fieldnames[$c]] != '') {
                    $empty = false;
                    break;
                }
            }
            if (!$empty) {
                array_push($rows,$row);
            }
            $r++;
        }
        $this->datarows = $rows;
    }
}

