<?php
/**
 * Created by PhpStorm.
 * User: Jure
 * Date: 8.5.2014
 * Time: 15:18
 */
header('Content-type: text/plain; charset=utf-8');
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT . "init.php");
define("absolute_path", "/var/www/html/warpitDevelopment/");



 class NfieldDownloadParser
{
    public  $db;
    public static $id_structure = "0,8";
    public $nfieldId;
    public function  getTypesFile(){
        $array = array(1 => ".o", 2 => ".csv",3=>".dat");

        return   $array;
    }

    public function __construct($db,$nfieldId)
    {
        $this->db = $db;
        $this->nfieldId = $nfieldId;
    }

    function returnParseSyntax()
    {
        /*$sintaksa['1000000010'] = "28,8"; // interview_date
        $sintaksa['1000000020'] = "122,4"; //tstart
        $sintaksa['1000000030'] = "589,4"; //tstop
        $sintaksa['1000000040'] = "2103,1"; // D10
        $sintaksa['1000000050'] = "2104,2"; // D11
        $sintaksa['1000000060'] = "2106,2"; //D15a
        $sintaksa['1000000070'] = "2111,2"; // D40a
        $sintaksa['1000000080'] = "2113,2"; // D40b
        $sintaksa['1000000090'] = "2115,2"; //D40c*/

        //EB16(boost)
        /*$sintaksa['1000000010'] = "28,8"; // interview_date
        $sintaksa['1000000020'] = "1011,4"; //tstart
        $sintaksa['1000000030'] = "1409,4"; //tstop
        $sintaksa['1000000040'] = "577,1"; // D10 SPOL
        $sintaksa['1000000050'] = "578,2"; // D11 "Starost"; // D11
        $sintaksa['1000000060'] = "1284,2"; //D15a "Zaposlitev"
        $sintaksa['1000000070'] = "1289,2"; // D40aStevilo_clanov_vecje_15";
        $sintaksa['1000000080'] = "1291,2"; // D40b "Stevilo_otrok_<_10_let";
        $sintaksa['1000000090'] = "1293,2"; //D40c "Stevilo_otrok_10_in_14";*/
        $nfieldId = $this->nfieldId;

        $sql = "SELECT c.*  FROM nfield_config as c WHERE c.fk_id_nfield_project = '$nfieldId' ";
        $result = $this->db->SQLexecute($sql);
        if (!$result) {
            return "{success:false,error:'Error with fetching nfield config'}";
        }
        while ($row = $this->db->fetchAssoc($result)) {
            $this->arr[$row['code']] = $row['coordinate'];
        }

       /* $sintaksa['1000000010'] = "28,8"; // interview_date
        $sintaksa['1000000020'] = "123,4"; //tstart
        $sintaksa['1000000030'] = "692,4"; //tstop
        $sintaksa['1000000040'] = "577,1"; // D10
        $sintaksa['1000000050'] = "578,2"; // D11
        $sintaksa['1000000060'] = "580,2"; //D15a
        $sintaksa['1000000070'] = "585,2"; // D40a
        $sintaksa['1000000080'] = "587,2"; // D40b
        $sintaksa['1000000090'] = "589,2"; //D40c*/

        return $this->arr;
    }

    function getDataFromServer($pathfileName)
    {

        $allTextData = "";
        $handle = fopen($pathfileName, "r");
        if ($handle) {
            while (($line = fgets($handle)) !== false) {
                //$line = utf8_encode(fgets($handle));
                $allTextData .= $line;
            }
        } else {
            return "{success:false,error:'Cannot opening file'}";
        }
        fclose($handle);

        return $allTextData;
    }

    function parseVisitorData($data,$tableName)
    {

        $l = explode("\n", $data);
        foreach ($l as $line) {
            $t = explode("\t", $line);
            $t = preg_replace('/[^(\x20-\x7F)]*/', '', $t);

            $id = $t[0];
            if ($t[1] == "Address") {

                $data = json_decode($t[2], true);
                $sql = "INSERT IGNORE INTO nfield.".$tableName."_data_raw
						SET
						id_structure 	= 	" . $id . ",
						data_type		= 1,
						data_value		= '" . mysql_real_escape_string($data['details']) . "'";
                $res = $this->db->SQLexecute($sql);
                if(!$res){
                    return "{success:false,error:'Visitor data failed inserted row'}";
                }

            } elseif ($t[1] == "InterviewerId") {
               // echo "Interviewer ID: " . $t[2] . "<br>";
                $sql = "INSERT IGNORE INTO nfield.".$tableName."_data_raw
						SET
						id_structure 	= 	" . $id . ",
						data_type		= 2,
						data_value		= '" . str_replace("\"", "", $t[2]) . "'";
                $res = $this->db->SQLexecute($sql);
                if(!$res){
                    return "{success:false,error:'Visitor data failed inserted row'}";
                }
            }
            elseif ($t[1] == "LocationInfo") {

                $data = json_decode($t[2], true);
                //Add latitude
                $sql = "INSERT IGNORE INTO nfield.".$tableName."_data_raw
						SET
						id_structure 	= 	" . $id . ",
						data_type		= 3,
						data_value		= '" . mysql_real_escape_string($data['latitude']) . "'";
                $res = $this->db->SQLexecute($sql);
                if(!$res){
                    return "{success:false,error:'Visitor data failed inserted row'}";
                }
                //Add longtitude
                $sql = "INSERT IGNORE INTO nfield.".$tableName."_data_raw
						SET
						id_structure 	= 	" . $id . ",
						data_type		= 4,
						data_value		= '" . mysql_real_escape_string($data['longitude']) . "'";
                $res = $this->db->SQLexecute($sql);
                if(!$res){
                    return "{success:false,error:'Visitor data failed inserted row'}";
                }

            }
            elseif ($t[1] == "SamplingPointId") {
               // echo "Sample ID: " . $t[2] . "<br>";
            } elseif ($t[1] == "SamplingPointGroupId") {
               // echo "Sample Group ID: " . $t[2] . "<br>";
            }
        }
    }

    function parseOpenQuestionsData($data,$tableName)
    {

        $all = explode("\n", $data);

        foreach ($all as $line) {

            $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);

            $p = explode(" ", $line, 2);

            if($p[0] != ""){
                $sql = "INSERT IGNORE INTO nfield.".$tableName."_data_check SET
                            id_structure 	= " . substr($p[0], 0, 8);

                $res = $this->db->SQLexecute($sql);

                if(!$res){
                    return "{success:false,error:'Open answer data failed inserted row'}";
                }

                $sql = "INSERT IGNORE INTO nfield.".$tableName."_data_raw SET
                            id_structure 	= 	" . substr($p[0], 0, 8) . ",
                            data_type 		= 	" . substr($p[0], 8, 10) . ",
                            data_value 		= 	'" . mysql_real_escape_string($p[1]) . "'";

                $res = $this->db->SQLexecute($sql);
                if(!$res){
                    return "{success:false,error:'Open answer data failed inserted row'}";
                }
            }
        }

    }

    function parseData($syntax, $data,$tableName)
    {
        $l = explode("\n", $data);
        foreach ($l as $line) {
            $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
            $t = explode(",", NfieldDownloadParser::$id_structure);
            $id = substr($line, $t[0], $t[1]);

            if (!$id) continue;
            unset($data);
            foreach ($syntax as $k => $v) {

                $t = explode(",", $v);
                $data = substr($line, $t[0], $t[1]);
                //add ignore by Jure
                $sql = "INSERT IGNORE INTO nfield.".$tableName."_data_raw SET id_structure = " . $id . ", data_type = " . $k . ", data_value='" . mysql_real_escape_string($data) . "'";

                $res = $this->db->SQLexecute($sql);
                if(!$res){
                    return "{success:false,error:'Para data failed inserted row'}";
                }
                //echo $sql . "<br>";
            }
        }
    }
}
/*$a = new NfieldDownloadParser(null);
$file = "http://sorspbx.rmplus.si/warpitDevelopment/nfield/docs/EB81.3-si.csv";
$data = $a->getDataFromServer($file);
$a->parseVisitorData($data);
$a->parseOpenQuestionsData($data);

$a->parseData($a->returnParseSyntax(), $data);
echo $data;*/
