<?php

defined('_VALID_CALL') or die('Direct Access is not allowed.');

require_once _SRV_WEBROOT . _SRV_WEB_PLUGINS. 'xt_ship_and_track/classes/constants.php';

global $db;

if( !$this->_FieldExists('shipper_code_ppcp', TABLE_SHIPPER))
{
    $db->Execute("ALTER TABLE `".TABLE_SHIPPER."` ADD COLUMN `shipper_code_ppcp` VARCHAR(128) NULL DEFAULT NULL AFTER `shipper_code`;");
}

$db->Execute("UPDATE ".TABLE_SHIPPER." SET ".COL_SHIPPER_API_ENABLED." = 0 where shipper_code = 'hermes'");

_updateShipper();

function _updateShipper()
{
    global $db;

    $dir = _SRV_WEBROOT.'plugins/xt_ship_and_track/installer/shipper/';

    $csv = file_exists($dir.'shipper.csv') ?  _getFileContentShipTrack($dir.'shipper.csv') : '';

    foreach(preg_split("/((\r?\n)|(\r\n?))/", $csv) as $line)
    {
        $data = explode(';', $line);
        try {
            $db->Execute("UPDATE ".TABLE_SHIPPER." SET ".COL_SHIPPER_CODE_PPCP." = ? where ".COL_SHIPPER_CODE." = ?" ,[$data[1], $data[0]]);
        } catch (exception $e) {}
    }

    $db->Execute("UPDATE ".TABLE_SHIPPER." SET ".COL_SHIPPER_CODE_PPCP." = 'OTHER' where ".COL_SHIPPER_CODE_PPCP." IS NULL");

}

function _getFileContentShipTrack($filename) {
    $handle = fopen($filename, 'rb');
    $content = fread($handle, filesize($filename));
    fclose($handle);
    return $content;

}
