<?php $___notjson=1;

class Install {

    private $db;
    private $pointsDb = 'db/cdekPoints.db';

    public function __construct(){
        $this->openDb('db/setting.db');
        $this->checkExistsDb();
        $this->param = $this->getParamFromDb();
		//echo "<pre>"; print_r($this->param); exit;
        if ( $this->checkCountParam() ) {
            $this->addDefaultParam();
            $this->saveDefaultParam();
        } else {
			if ( !isset($this->param['markupProc']) ) $this->updateDb('db/setting.db');
			$this->param = $this->getParamFromDb();
		}
    }

	public function openDb($filename) {
		try {
			$this->db = new PDO("sqlite:$filename");
			$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		} catch ( PDOException $e ) {
			$this->errorDb($e->getMessage(), $e->getLine());
		}
	}

    public function checkExistsDb() {
        try {
            $this->db->exec("CREATE TABLE IF NOT EXISTS `settings` (
                `type` INTEGER DEFAULT NULL,
                `typeText1` VARCHAR(13),
                `typeText2` VARCHAR(13),
                `typeText3` VARCHAR(13),
                `typeText4` VARCHAR(13),
                `account` TEXT,
                `password` TEXT,
                `tariff_id` TEXT,
                `tariff_name` TEXT,
                `tariff_priority` TEXT,
                `markup` INTEGER,
                `markupProc` INTEGER,
                `work` INTEGER,
                `package` INTEGER,
                `weightpack` INTEGER,
                `typeweight` VARCHAR(1),
                `weightDefault` INTEGER,
                `typeCurrency` VARCHAR(6),
                `freeDelivery` INTEGER,
                `rusDel` VARCHAR(1),
                `ukrDel` VARCHAR(1),
                `blrDel` VARCHAR(1),
                `kazDel` VARCHAR(1),
                `armDel` VARCHAR(1),
                `kgzDel` VARCHAR(1),
                `zhoDel` VARCHAR(1),
                `dD1` INTEGER,
                `dD2` INTEGER,
                `dD3` INTEGER,
                `dD031` INTEGER DEFAULT '',
                `dD032` INTEGER DEFAULT '',
                `dD033` INTEGER DEFAULT '',
                `dD361` INTEGER DEFAULT '',
                `dD362` INTEGER DEFAULT '',
                `dD363` INTEGER DEFAULT '',
                `dD691` INTEGER DEFAULT '',
                `dD692` INTEGER DEFAULT '',
                `dD693` INTEGER DEFAULT '',
                `dD9121` INTEGER DEFAULT '',
                `dD9122` INTEGER DEFAULT '',
                `dD9123` INTEGER DEFAULT '',
                `dD12151` INTEGER DEFAULT '',
                `dD12152` INTEGER DEFAULT '',
                `dD12153` INTEGER DEFAULT '',
                `dD15181` INTEGER DEFAULT '',
                `dD15182` INTEGER DEFAULT '',
                `dD15183` INTEGER DEFAULT '',
                `dD18211` INTEGER DEFAULT '',
                `dD18212` INTEGER DEFAULT '',
                `dD18213` INTEGER DEFAULT '',
                `dD21251` INTEGER DEFAULT '',
                `dD21252` INTEGER DEFAULT '',
                `dD21253` INTEGER DEFAULT '',
                `dD25301` INTEGER DEFAULT '',
                `dD25302` INTEGER DEFAULT '',
                `dD25303` INTEGER DEFAULT '',
                `dD30501` INTEGER DEFAULT '',
                `dD30502` INTEGER DEFAULT '',
                `dD30503` INTEGER DEFAULT '',
                `dDlast1` INTEGER DEFAULT '',
                `dDlast2` INTEGER DEFAULT '',
                `dDlast3` INTEGER DEFAULT '',
                `dimFromWeight` VARCHAR(1),
                `deliveryDate` VARCHAR(1),
                `deliveryMyDate` INTEGER,
                `WeightFromWeight` VARCHAR(1),
                `wfw3` INTEGER DEFAULT '',
                `wfw36` INTEGER DEFAULT '',
                `wfw69` INTEGER DEFAULT '',
                `wfw912` INTEGER DEFAULT '',
                `wfw1215` INTEGER DEFAULT '',
                `wfw1518` INTEGER DEFAULT '',
                `wfw1821` INTEGER DEFAULT '',
                `wfw2125` INTEGER DEFAULT '',
                `wfw2530` INTEGER DEFAULT '',
                `wfw3050` INTEGER DEFAULT '',
                `wfw50100` INTEGER DEFAULT '',
                `priceFromWeight` VARCHAR(1),
                `pfw3` INTEGER DEFAULT '',
                `pfw36` INTEGER DEFAULT '',
                `pfw69` INTEGER DEFAULT '',
                `pfw912` INTEGER DEFAULT '',
                `pfw1215` INTEGER DEFAULT '',
                `pfw1518` INTEGER DEFAULT '',
                `pfw1821` INTEGER DEFAULT '',
                `pfw2125` INTEGER DEFAULT '',
                `pfw2530` INTEGER DEFAULT '',
                `pfw3050` INTEGER DEFAULT '',
                `pfw50100` INTEGER DEFAULT '',
                `myCity` VARCHAR(255),
                `cdekId` INTEGER,
                `userDelType` VARCHAR(1),
                `type2` VARCHAR(1),
                `cityMap` VARCHAR(50),
                `typeMap` VARCHAR(1),
                `cityMapX` VARCHAR(10),
                `cityMapY` VARCHAR(10),
                `dimensionsW` VARCHAR(1),
                `dimensionsH` VARCHAR(1),
                `dimensionsL` VARCHAR(1),
                `typeDimensions` VARCHAR(1),
                `consumer_key` VARCHAR(40),
                `consumer_secret` VARCHAR(40),
                `oauth_token` VARCHAR(40),
                `oauth_token_secret` VARCHAR(40),
                `url` VARCHAR(255),
                `dimensions1` VARCHAR(1),
                `dimensionsWHL` VARCHAR(1),
                `delimiter` VARCHAR(255),
                `volumeCheck` VARCHAR(1),
                `selectVolumeField` VARCHAR(1),
                `placeCheck` VARCHAR(1),
                `roundRes` VARCHAR(1),
                `orderField` VARCHAR(2),
                `orderFieldDate` VARCHAR(2)
            );");
        } catch ( PDOException $e ) {
            $this->errorDb($e->getMessage(), $e->getLine());
        }
    }

    public function getParamFromDb() {
        try {
            $param = $this->db->prepare("SELECT * FROM `settings`");
            $param->execute();
            return $param->fetch(PDO::FETCH_ASSOC);
        } catch ( PDOException $e ) {
            $this->errorDb($e->getMessage(), $e->getLine());
        }
    }

    public function saveDefaultParam() {
        $query = "INSERT INTO `settings` (`type`, `typeText1`, `typeText2`, `typeText3`, `typeText4`, `account`, `password`, `tariff_id`, ";
		$query .= "`tariff_name`, `tariff_priority`, `markup`, `markupProc`, `work`, `package`, `weightpack`, `typeweight`, `weightDefault`, `typeCurrency`, `freeDelivery`, ";
        $query .= "`rusDel`, `ukrDel`, `blrDel`, `kazDel`, `armDel`, `kgzDel`, `zhoDel`, `dD1`, `dD2`, `dD3`, ";
        $query .= "`dD031`, `dD032`, `dD033`, `dD361`, `dD362`, `dD363`, `dD691`, `dD692`, `dD693`, `dD9121`, `dD9122`, `dD9123`, ";
        $query .= "`dD12151`, `dD12152`, `dD12153`, `dD15181`, `dD15182`, `dD15183`, `dD18211`, `dD18212`, `dD18213`, ";
        $query .= "`dD21251`, `dD21252`, `dD21253`, `dD25301`, `dD25302`, `dD25303`, `dD30501`, `dD30502`, `dD30503`, `dDlast1`, ";
        $query .= "`dDlast2`, `dDlast3`, `dimFromWeight`, `deliveryDate`, `deliveryMyDate`, `WeightFromWeight`, `wfw3`, ";
        $query .= "`wfw36`, `wfw69`, `wfw912`, `wfw1215`, `wfw1518`, `wfw1821`, `wfw2125`, `wfw2530`, `wfw3050`, `wfw50100`, `priceFromWeight`, `pfw3`, ";
        $query .= "`pfw36`, `pfw69`, `pfw912`, `pfw1215`, `pfw1518`, `pfw1821`, `pfw2125`, `pfw2530`, `pfw3050`, `pfw50100`, `myCity`, ";
        $query .= "`cdekId`, `userDelType`, `type2`, `cityMap`, `typeMap`, `cityMapX`, `cityMapY`, `dimensionsW`, `dimensionsH`, `dimensionsL`, `typeDimensions`, ";
        $query .= "`consumer_key`, `consumer_secret`, `oauth_token`, `oauth_token_secret`, `url`, `dimensions1`, `dimensionsWHL`, `delimiter`, ";
        $query .= "`volumeCheck`, `selectVolumeField`, `placeCheck`, `roundRes`, `orderField`, `orderFieldDate`) ";
        $query .= "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,";
        $query .= "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,";
        $query .= "?,?,?,?,?,?,?)";
        try {
            $save = $this->db->prepare($query);
            $data = array();
            foreach ( $this->param[0] as $value ) {
                array_push($data, $value);
            }
            $save->execute($data);
        } catch ( PDOException $e ) {
            $this->errorDb($e->getMessage(), $e->getLine());
        }
    }

    public function checkCountParam() {
        if ( empty($this->param) ) return true;
        else return false;
    }

    public function response() {
        return $this->param;
    }

    public function addDefaultParam() {
        $this->param = array(
            '0' => array(
                'type' => 4,
                'typeText1' => 'Дверь - Дверь',
                'typeText2' => 'Дверь - Склад',
                'typeText3' => 'Склад - Дверь',
                'typeText4' => 'Склад - Склад',
                'account' => '',
                'password' => '',
                'tariff_id' => '136,137,138,139,233,234,1,10,11,12,15,16,17,18',
                'tariff_name' => 'Посылка склад-склад (код 136),Посылка склад-дверь (код 137),Посылка дверь-склад (код 138),Посылка дверь-дверь (код 139),Экономичная посылка склад-дверь (код 233),Экономичная посылка склад-склад (код 234),Экспресс лайт дверь-дверь (код 1),Экспресс лайт склад-склад (код 10),Экспресс лайт склад-дверь (код 11),Экспресс лайт дверь-склад (код 12),Экспресс тяжеловесы склад-склад (код 15),Экспресс тяжеловесы склад-дверь (код 16),Экспресс тяжеловесы дверь-склад (код 17),Экспресс тяжеловесы дверь-дверь (код 18)',
                'tariff_priority' => '136,137,138,139,233,234,1,10,11,12,15,16,17,18',
                'markup' => 0,
				'markupProc' => 0,
                'work' => 0,
                'package' => 0,
                'weightpack' => 0,
                'typeweight' => 0,
                'weightDefault' => 1000,
                'typeCurrency' => 'RUB',
                'freeDelivery' => 0,
                'rusDel' => 1,
                'ukrDel' => 0,
                'blrDel' => 0,
                'kazDel' => 0,
                'armDel' => 0,
                'kgzDel' => 0,
                'zhoDel' => 0,
                'dD1' => 10,
                'dD2' => 10,
                'dD3' => 10,
                'dD031' => '',
                'dD032' => '',
                'dD033' => '',
                'dD361' => '',
                'dD362' => '',
                'dD363' => '',
                'dD691' => '',
                'dD692' => '',
                'dD693' => '',
                'dD9121' => '',
                'dD9122' => '',
                'dD9123' => '',
                'dD12151' => '',
                'dD12152' => '',
                'dD12153' => '',
                'dD15181' => '',
                'dD15182' => '',
                'dD15183' => '',
                'dD18211' => '',
                'dD18212' => '',
                'dD18213' => '',
                'dD21251' => '',
                'dD21252' => '',
                'dD21253' => '',
                'dD25301' => '',
                'dD25302' => '',
                'dD25303' => '',
                'dD30501' => '',
                'dD30502' => '',
                'dD30503' => '',
                'dDlast1' => '',
                'dDlast2' => '',
                'dDlast3' => '',
                'dimFromWeight' => 0,
                'deliveryDate' => 1,
                'deliveryMyDate' => 0,
                'WeightFromWeight' => 0,
                'wfw3' => '',
                'wfw36' => '',
                'wfw69' => '',
                'wfw912' => '',
                'wfw1215' => '',
                'wfw1518' => '',
                'wfw1821' => '',
                'wfw2125' => '',
                'wfw2530' => '',
                'wfw3050' => '',
                'wfw50100' => '',
                'priceFromWeight' => 0,
                'pfw3' => '',
                'pfw36' => '',
                'pfw69' => '',
                'pfw912' => '',
                'pfw1215' => '',
                'pfw1518' => '',
                'pfw1821' => '',
                'pfw2125' => '',
                'pfw2530' => '',
                'pfw3050' => '',
                'pfw50100' => '',
                'myCity' => '',
                'cdekId' => '',
                'userDelType' => 0,
                'type2' => 1,
                'cityMap' => 'МОСКВА',
				'typeMap' => 1,
                'cityMapX' => '55.76',
                'cityMapY' => '37.64',
                'dimensionsW' => 1,
                'dimensionsH' => 2,
                'dimensionsL' => 3,
                'typeDimensions' => 2,
                'consumer_key' => '',
                'consumer_secret' => '',
                'oauth_token' => '',
                'oauth_token_secret' => '',
                'url' => '',
                'dimensions1' => 0,
                'dimensionsWHL' => 1,
                'delimiter' => '',
                'volumeCheck' => 0,
                'selectVolumeField' => 1,
                'placeCheck' => 1,
                'roundRes' => 2,
                'orderField' => 0,
                'orderFieldDate' => 0
            )
        );
        return $this->param[0];
    }

    public function updateSettings($row) {
        $query = "UPDATE `settings` SET ";
        $query .= "`type`=:type, `account`=:account, ";
        $query .= "`password`=:password, `tariff_priority`=:tariff_priority, `markup`=:markup, `markupProc`=:markupProc, `work`=:work, ";
        $query .= "`package`=:package, `weightpack`=:weightpack, `typeweight`=:typeweight, `weightDefault`=:weightDefault, ";
        $query .= "`typeCurrency`=:typeCurrency, `freeDelivery`=:freeDelivery, `rusDel`=:rusDel, ";
        $query .= "`ukrDel`=:ukrDel, `blrDel`=:blrDel, `kazDel`=:kazDel, `armDel`=:armDel, `kgzDel`=:kgzDel, `zhoDel`=:zhoDel, ";
        $query .= "`dD1`=:dD1, `dD2`=:dD2, `dD3`=:dD3, `dD031`=:dD031, `dD032`=:dD032, `dD033`=:dD033, ";
        $query .= "`dD361`=:dD361, `dD362`=:dD362, `dD363`=:dD363, `dD691`=:dD691, `dD692`=:dD692, `dD693`=:dD693, ";
        $query .= "`dD9121`=:dD9121, `dD9122`=:dD9122, `dD9123`=:dD9123, `dD12151`=:dD12151, `dD12152`=:dD12152, `dD12153`=:dD12153, ";
        $query .= "`dD15181`=:dD15181, `dD15182`=:dD15182, `dD15183`=:dD15183, `dD18211`=:dD18211, `dD18212`=:dD18212, `dD18213`=:dD18213, ";
        $query .= "`dD21251`=:dD21251, `dD21252`=:dD21252, `dD21253`=:dD21253, `dD25301`=:dD25301, `dD25302`=:dD25302, `dD25303`=:dD25303, ";
        $query .= "`dD30501`=:dD30501, `dD30502`=:dD30502, `dD30503`=:dD30503, `dDlast1`=:dDlast1, `dDlast2`=:dDlast2, `dDlast3`=:dDlast3, ";
        $query .= "`dimFromWeight`=:dimFromWeight, `deliveryDate`=:deliveryDate, `deliveryMyDate`=:deliveryMyDate, ";
        $query .= "`WeightFromWeight`=:WeightFromWeight, `wfw3`=:wfw3, `wfw36`=:wfw36, `wfw69`=:wfw69, `wfw912`=:wfw912, `wfw1215`=:wfw1215, ";
        $query .= "`wfw1518`=:wfw1518, `wfw1821`=:wfw1821, `wfw2125`=:wfw2125, `wfw2530`=:wfw2530, `wfw3050`=:wfw3050, `wfw50100`=:wfw50100, ";
        $query .= "`priceFromWeight`=:priceFromWeight, `pfw3`=:pfw3, `pfw36`=:pfw36, `pfw69`=:pfw69, `pfw912`=:pfw912, `pfw1215`=:pfw1215, ";
        $query .= "`pfw1518`=:pfw1518, `pfw1821`=:pfw1821, `pfw2125`=:pfw2125, `pfw2530`=:pfw2530, `pfw3050`=:pfw3050, `pfw50100`=:pfw50100, ";
        $query .= "`myCity`=:myCity, `cdekId`=:cdekId, `userDelType`=:userDelType, `type2`=:type2, `cityMap`=:cityMap, `typeMap`=:typeMap, ";
        $query .= "`cityMapX`=:cityMapX, `cityMapY`=:cityMapY, `dimensionsW`=:dimensionsW, `dimensionsH`=:dimensionsH, `dimensionsL`=:dimensionsL, ";
        $query .= "`typeDimensions`=:typeDimensions, `consumer_key`=:consumer_key, `consumer_secret`=:consumer_secret, `oauth_token`=:oauth_token, ";
        $query .= "`oauth_token_secret`=:oauth_token_secret, `url`=:url, `dimensions1`=:dimensions1, `dimensionsWHL`=:dimensionsWHL, `delimiter`=:delimiter, ";
        $query .= "`volumeCheck`=:volumeCheck, `selectVolumeField`=:selectVolumeField, `placeCheck`=:placeCheck, `roundRes`=:roundRes, `orderField`=:orderField, `orderFieldDate`=:orderFieldDate";
        if (!isset($row['rusDel'])) $row['rusDel'] = 0; else $row['rusDel'] = 1;
        if (!isset($row['ukrDel'])) $row['ukrDel'] = 0; else $row['ukrDel'] = 1;
        if (!isset($row['blrDel'])) $row['blrDel'] = 0; else $row['blrDel'] = 1;
        if (!isset($row['kazDel'])) $row['kazDel'] = 0; else $row['kazDel'] = 1;
        if (!isset($row['armDel'])) $row['armDel'] = 0; else $row['armDel'] = 1;
        if (!isset($row['kgzDel'])) $row['kgzDel'] = 0; else $row['kgzDel'] = 1;
        if (!isset($row['zhoDel'])) $row['zhoDel'] = 0; else $row['zhoDel'] = 1;
        if (!isset($row['dimFromWeight'])) $row['dimFromWeight'] = 0; else $row['dimFromWeight'] = 1;
        if (!isset($row['deliveryDate'])) $row['deliveryDate'] = 0; else $row['deliveryDate'] = 1;
        if (!isset($row['WeightFromWeight'])) $row['WeightFromWeight'] = 0; else $row['WeightFromWeight'] = 1;
        if (!isset($row['priceFromWeight'])) $row['priceFromWeight'] = 0; else $row['priceFromWeight'] = 1;
        if (!isset($row['userDelType'])) $row['userDelType'] = 0; else $row['userDelType'] = 1;
        if (!isset($row['dimensions1'])) $row['dimensions1'] = 0; else $row['dimensions1'] = 1;
        if (!isset($row['volumeCheck'])) $row['volumeCheck'] = 0; else $row['volumeCheck'] = 1;
        if (!isset($row['placeCheck'])) $row['placeCheck'] = 0; else $row['placeCheck'] = 1;
        $cityAndCoord = explode('||', $row['cityMap']);
        $data = array(
            ':type' => $row['type'],
            ':account' => $row['account'],
            ':password' => $row['password'],
            ':tariff_priority' => $row['tariffs_id'],
            ':markup' => $row['markup'],
			':markupProc' => $row['markupProc'],
            ':work' => $row['work'],
            ':package' => $row['package'],
            ':weightpack' => $row['weightpack'],
            ':typeweight' => $row['typeweight'],
            ':weightDefault' => $row['weightDefault'],
            ':typeCurrency' => $row['typeCurrency'],
            ':freeDelivery' => $row['freeDelivery'],
            ':rusDel' => $row['rusDel'],
            ':ukrDel' => $row['ukrDel'],
            ':blrDel' => $row['blrDel'],
            ':kazDel' => $row['kazDel'],
            ':armDel' => $row['armDel'],
            ':kgzDel' => $row['kgzDel'],
            ':zhoDel' => $row['zhoDel'],
            ':dD1' => $row['dD1'],
            ':dD2' => $row['dD2'],
            ':dD3' => $row['dD3'],
            ':dD031' => $row['dD031'],
            ':dD032' => $row['dD032'],
            ':dD033' => $row['dD033'],
            ':dD361' => $row['dD361'],
            ':dD362' => $row['dD362'],
            ':dD363' => $row['dD363'],
            ':dD691' => $row['dD691'],
            ':dD692' => $row['dD692'],
            ':dD693' => $row['dD693'],
            ':dD9121' => $row['dD9121'],
            ':dD9122' => $row['dD9122'],
            ':dD9123' => $row['dD9123'],
            ':dD12151' => $row['dD12151'],
            ':dD12152' => $row['dD12152'],
            ':dD12153' => $row['dD12153'],
            ':dD15181' => $row['dD15181'],
            ':dD15182' => $row['dD15182'],
            ':dD15183' => $row['dD15183'],
            ':dD18211' => $row['dD18211'],
            ':dD18212' => $row['dD18212'],
            ':dD18213' => $row['dD18213'],
            ':dD21251' => $row['dD21251'],
            ':dD21252' => $row['dD21252'],
            ':dD21253' => $row['dD21253'],
            ':dD25301' => $row['dD25301'],
            ':dD25302' => $row['dD25302'],
            ':dD25303' => $row['dD25303'],
            ':dD30501' => $row['dD30501'],
            ':dD30502' => $row['dD30502'],
            ':dD30503' => $row['dD30503'],
            ':dDlast1' => $row['dDlast1'],
            ':dDlast2' => $row['dDlast2'],
            ':dDlast3' => $row['dDlast3'],
            ':dimFromWeight' => $row['dimFromWeight'],
            ':deliveryDate' => $row['deliveryDate'],
            ':deliveryMyDate' => $row['deliveryMyDate'],
            ':WeightFromWeight' => $row['WeightFromWeight'],
            ':wfw3' => $row['wfw3'],
            ':wfw36' => $row['wfw36'],
            ':wfw69' => $row['wfw69'],
            ':wfw912' => $row['wfw912'],
            ':wfw1215' => $row['wfw1215'],
            ':wfw1518' => $row['wfw1518'],
            ':wfw1821' => $row['wfw1821'],
            ':wfw2125' => $row['wfw2125'],
            ':wfw2530' => $row['wfw2530'],
            ':wfw3050' => $row['wfw3050'],
            ':wfw50100' => $row['wfw50100'],
            ':priceFromWeight' => $row['priceFromWeight'],
            ':pfw3' => $row['pfw3'],
            ':pfw36' => $row['pfw36'],
            ':pfw69' => $row['pfw69'],
            ':pfw912' => $row['pfw912'],
            ':pfw1215' => $row['pfw1215'],
            ':pfw1518' => $row['pfw1518'],
            ':pfw1821' => $row['pfw1821'],
            ':pfw2125' => $row['pfw2125'],
            ':pfw2530' => $row['pfw2530'],
            ':pfw3050' => $row['pfw3050'],
            ':pfw50100' => $row['pfw50100'],
            ':myCity' => $row['myCity'],
            ':cdekId' => $row['cdekId'],
            ':userDelType' => $row['userDelType'],
            ':type2' => $row['type2'],
            ':cityMap' => $cityAndCoord[0],
			':typeMap' => $row['typeMap'],
            ':cityMapX' => $cityAndCoord[2],
            ':cityMapY' => $cityAndCoord[1],
            ':dimensionsW' => $row['dimensionsW'],
            ':dimensionsH' => $row['dimensionsH'],
            ':dimensionsL' => $row['dimensionsL'],
            ':typeDimensions' => $row['typeDimensions'],
            ':consumer_key' => $row['consumer_key'],
            ':consumer_secret' => $row['consumer_secret'],
            ':oauth_token' => $row['oauth_token'],
            ':oauth_token_secret' => $row['oauth_token_secret'],
            ':url' => $row['url'],
            ':dimensions1' => $row['dimensions1'],
            ':dimensionsWHL' => $row['dimensionsWHL'],
            ':delimiter' => $row['delimiter'],
            ':volumeCheck' => $row['volumeCheck'],
            ':selectVolumeField' => $row['selectVolumeField'],
            ':placeCheck' => $row['placeCheck'],
            ':roundRes' => $row['roundRes'],
            ':orderField' => $row['orderField'],
            ':orderFieldDate' => $row['orderFieldDate']
        );

        try {
            $update = $this->db->prepare($query);
            $update->execute($data);
        } catch (PDOException $e) {
            $this->errorDb($e->getMessage(), $e->getLine());
        }
        $this->statusSave('ok', 'Изменения сохранены!');
    }

    public function statusSave($status, $message) {
        $arr = array(
            'status' => $status,
            'message' => $message
        );
        echo json_encode($arr);
        exit;
    }

    public function errorDb($message, $line) {
        echo "Строка $line выдает ошибку: $message";
        exit;
    }

    public function getCityPoints () {
        $time_sec = time();
        if ( file_exists ( $this->pointsDb ) ) {
            $time_file = filemtime( $this->pointsDb );
            $time = $time_sec-$time_file;
        }
        if ( !file_exists ( $this->pointsDb ) || $time >= 86400 || filesize($this->pointsDb) <= 3000 ) {
            $db = NULL;
            if ( file_exists ( $this->pointsDb ) ) unlink($this->pointsDb);
            $this->checkExistsPointsDb();
            $this->savePoints();
        }
        try {
            $db = new PDO('sqlite:db/cdekPoints.db');
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pvz = $db->prepare("SELECT * FROM points GROUP BY city"); //DISTINCT
            $pvz->execute();
            $results = $pvz->fetchAll(); //echo "<pre>"; print_r($results);
            return $results;
        } catch ( PDOException $e ) {
            echo "error: " . $e->getMessage() . "<br><br>" . $e->getLine() . "');";
            exit;
        }
    }

    public function savePoints() {
        $courier = 'CDEK';
        $pvz = $this->getPoint();
        $query = "INSERT INTO `points` (`PVZCode`, `Address`, `cityCode`, `City`, `WorkTime`, `Phone`, `coordX`, `coordY`, `courier`, `country`) VALUES ";
        $query .= "(:PVZCode, :Address, :cityCode, :City, :WorkTime, :Phone, :coordX, :coordY, :courier, :country)";
        try {
            $db = new PDO("sqlite:" . $this->pointsDb);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $prepared_query = $db->prepare($query);
            $db->beginTransaction();
            foreach ( $pvz as $get ) {
                $city = mb_strtoupper($get['City'], "UTF-8");
                $country = $this->getCountryFromCityCode($get['CityCode']);
                if ( !mb_stripos( $get['WorkTime'], 'не работает', 0,  'UTF-8' ) && !mb_stripos( $get['Note'], 'не работает', 0,  'UTF-8' ) ) {
                    $prepared_query->execute(
                        array(
                            ':PVZCode' => $get['Code'],
                            ':Address' => $get['Address'],
                            ':cityCode' => $get['CityCode'],
                            ':City' => $city,
                            ':WorkTime' => $get['WorkTime'],
                            ':Phone' => $get['Phone'],
                            ':coordX' => $get['coordX'],
                            ':coordY' => $get['coordY'],
                            ':courier' => $courier,
                            ':country' => $country
                        )
                    );
                }
            }
            $db->commit();
            return $pvz;
        } catch ( PDOException $e ) {
            echo "error: " . $e->getMessage() . "<br><br>" . $e->getLine() . "');";
            exit;
        }
    }

    public function checkExistsPointsDb() {
        try {
            $db = new PDO("sqlite:" . $this->pointsDb);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->exec("CREATE TABLE IF NOT EXISTS `points` (
			`id` INTEGER PRIMARY KEY AUTOINCREMENT,
			`PVZCode` VARCHAR(10),
			`Address` VARCHAR(255),
			`cityCode` INTEGER,
			`City` VARCHAR(50),
			`WorkTime` VARCHAR(100),
			`Phone` VARCHAR(100),
			`coordX` VARCHAR(20),
			`coordY` VARCHAR(20),
			`courier` VARCHAR(20),
			`country` VARCHAR(1)
		);");
        } catch (PDOException $e) {
            $this->calcError('Ошибка в строке ' . $e->getLine() . ': ' . $e->getMessage());
        }
    }

    public function getPoint() {
        $url = "https://integration.cdek.ru/pvzlist.php";
        $ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        $items = simplexml_load_string($output);
        return $items->Pvz;
    }

    public function getCountryFromCityCode($id) {
        try {
            $db = new PDO('sqlite:db/cdekCity.db');
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $options = $db->prepare("SELECT `country` FROM `city` WHERE `city_id`=:city_id");
            $options->execute(array(':city_id' => $id));
            $results = $options->fetch(PDO::FETCH_ASSOC);
            return $results['country'];
        } catch ( PDOException $e ) {
            echo "error: " . $e->getMessage() . "<br><br>" . $e->getLine() . "');";
            exit;
        }
    }

    public function queryCrypt($input,$decrypt=false) {
        $o = $s1 = $s2 = array();
        $basea = array('?','(','@',';','$','#',"]","&",'*');
        $basea = array_merge($basea, range('a','z'), range('A','Z'), range(0,9) );
        $basea = array_merge($basea, array('!',')','_','+','|','%','/','[','.',' ') );
        $dimension=9;
        for($i=0;$i<$dimension;$i++) {
            for($j=0;$j<$dimension;$j++) {
                $s1[$i][$j] = $basea[$i*$dimension+$j];
                $s2[$i][$j] = str_rot13($basea[($dimension*$dimension-1) - ($i*$dimension+$j)]);
            }
        }
        unset($basea);
        $m = floor(strlen($input)/2)*2;
        $symbl = $m==strlen($input) ? '':$input[strlen($input)-1];
        $al = array();
        for ($ii=0; $ii<$m; $ii+=2) {
            $symb1 = $symbn1 = strval($input[$ii]);
            $symb2 = $symbn2 = strval($input[$ii+1]);
            $a1 = $a2 = array();
            for($i=0;$i<$dimension;$i++) {
                for($j=0;$j<$dimension;$j++) {
                    if ($decrypt) {
                        if ($symb1===strval($s2[$i][$j]) ) $a1=array($i,$j);
                        if ($symb2===strval($s1[$i][$j]) ) $a2=array($i,$j);
                        if (!empty($symbl) && $symbl===strval($s2[$i][$j])) $al=array($i,$j);
                    }
                    else {
                        if ($symb1===strval($s1[$i][$j]) ) $a1=array($i,$j);
                        if ($symb2===strval($s2[$i][$j]) ) $a2=array($i,$j);
                        if (!empty($symbl) && $symbl===strval($s1[$i][$j])) $al=array($i,$j);
                    }
                }
            }
            if (sizeof($a1) && sizeof($a2)) {
                $symbn1 = $decrypt ? $s1[$a1[0]][$a2[1]] : $s2[$a1[0]][$a2[1]];
                $symbn2 = $decrypt ? $s2[$a2[0]][$a1[1]] : $s1[$a2[0]][$a1[1]];
            }
            $o[] = $symbn1.$symbn2;
        }
        if (!empty($symbl) && sizeof($al))
            $o[] = $decrypt ? $s1[$al[1]][$al[0]] : $s2[$al[1]][$al[0]];
        return implode('',$o);
    }

	public function updateDb($filename) {
		if (file_exists($filename)) {
			$this->db = null;
			unlink($filename);
			$this->openDb($filename);
			$this->checkExistsDb();
			$field = '';
			$fieldKey = '';
			$fieldValues = array();
			foreach ( $this->param as $key=>$value ) {
				$field .= $key . ',';
				$fieldKey .= ':' . $key . ',';
				$fieldValues[':' . $key] = $value;
			}
			// addTo Version 2.0
			if ( !isset($fieldValues['markupProc']) ) {
				$field .= "markupProc, typeMap";
				$fieldKey .= ":markupProc, :typeMap";
				$fieldValues[":markupProc"] = 0;
				$fieldValues[":typeMap"] = 1;
			}
			//
			$query = "INSERT INTO `settings` ($field) VALUES ($fieldKey)";
			try {
				$prepared_query = $this->db->prepare($query);
				$this->db->beginTransaction();
				$prepared_query->execute ($fieldValues);
				$this->db->commit ();
			} catch ( PDOException $e ) {
				echo "error: " . $e->getMessage() . "<br><br>" . $e->getLine() . "');";
				exit;
			}
		}
	}

}

?>