<?php

class Mbe_Shipping_Helper_Csv
{
    protected $_csvHeaderKnowDefinitions = array(
        'country'       => 'country',
        'region'        => 'region',
        'city'          => 'city',
        'zip'           => 'zip',
        'zip_to'        => 'zip_to',
        'weight_from'   => 'weight_from',
        'weight_to'     => 'weight_to',
        'price'         => 'price',
        'delivery_type' => 'delivery_type',
    );

    public function getCsvHeaderKnowDefinitions()
    {
        return $this->_csvHeaderKnowDefinitions;
    }

    public function readFile($importFilePath)
    {
        $file = fopen($importFilePath, "r");
        $i = 0;
        $header = null;
        $result = array();

        while (!feof($file)) {
            //$this->log("Reading row " . $i . " ...");
            $currentRow = fgetcsv($file, 0, ",", '"');
            if ($i == 0) {
                //File heading
                $header = $currentRow;
            }
            else {
                $current = $this->readCsvRowToArray($header, $currentRow);
                $result[] = $current;
            }
            $i++;
        }
        return $result;
    }

    function readCsvRowToArray($header, $row)
    {
        $result = array();
        if (is_array($row)) {
            foreach ($row as $index => $currentRowValue) {
                $headerName = $this->cleanString($header[$index]);
                $currentKey = $headerName;
                if (isset($this->_csvHeaderKnowDefinitions[$headerName])) {
                    $currentKey = $this->_csvHeaderKnowDefinitions[$headerName];
                }
                $currentRowValue = trim($currentRowValue);
                /*
                $currentRowValue = str_replace("  ", " ", $currentRowValue);
                $currentRowValue = str_replace("  ", " ", $currentRowValue);
                $currentRowValue = str_replace("  ", " ", $currentRowValue);
                $currentRowValue = str_replace("„", "\"", $currentRowValue);
                $currentRowValue = str_replace("“", "\"", $currentRowValue);
                $currentRowValue = str_replace("”", "\"", $currentRowValue);
                */
                $result[$currentKey] = $currentRowValue;
            }
        }
        return $result;
    }

    function cleanString($str)
    {
        $result = $str;
        $result = trim($result);
        $result = strtolower($result);
        $result = str_replace(" ", "_", $result);
        $result = str_replace(chr(160), "_", $result);
        $result = str_replace(chr(194), "_", $result);
        $result = str_replace(chr(195), "_", $result);
        $result = str_replace(",", "_", $result);
        $result = str_replace("/", "", $result);
        $result = str_replace("(", "", $result);
        $result = str_replace(")", "", $result);
        $result = str_replace("__", "_", $result);
        return $result;
    }
}