<?php

// Offset blank line;
echo PHP_EOL;

// BOF: Prepare connection.
$driverOptions = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8\';',
);

$pdo = new PDO('mysql:host=127.0.0.1;dbname=crm', 'root', '1ptimu6', $driverOptions);
// EOF: Prepare connection.

// BOF: Methods used with importing.
$pcmap = array(
    // KOMPENSATA
    // PRZEDPŁATA
    // ZAPŁACONO KARTĄ
    // PRZELEW
    // GOTÓWKA POBRANIE
    // ZAPŁATA ODROCZONA
    // GOTÓWKA
    '003' => '8283a1fd-d588-11c5-0d0a-51d541551977',
    '001' => '8267a913-ce6c-1242-953b-51d54199ebad',
    '1' => '824a0cd7-141c-d4ef-ebcb-51d541171424',
    '2' => '822eb003-7555-9470-85b1-51d541b2e321',
    '004' => '82125e3b-a0b9-3a07-f137-51d54116f439',
    '002' => '81f6ab43-14b7-6d65-f7c1-51d5418c6eb3',
    '3' => '81cd0875-a950-086d-a651-51d54152c07b',
);

$def = array(
    'ROK',
    'MIESIAC',
    'SYM_OPER',
    'NR_SYSTEM',
    'IDENT_K',
    'SYM_DOK',
    'NR_DOK',
    'POZ_DOK',
    'DAT_DOK',
    'ID_DOK',
    'SPAR_TR',
    'ZOB_NAL',
    'DAT_ZN',
    'SYM_PAR',
    'NR_PAR',
    'SP_ZAP',
    'IL_DNI',
    'DAT_ZAP',
    'K_SYN',
    'K_ANAL',
    'DAT_REJ',
    'OPIS_1',
    'OPIS_2',
    'KWOTA',
    'K_SYN_WN',
    'K_ANAL_WN;',
    'K_SYN_MA',
    'K_ANAL_MA',
    'NICKNAME',
    'NIP',
    'REZERWA',
    'KWOTA_WAL',
    'SYMB_WAL',
    'KURS_WAL',
    'DAT_ZGO',
    'KOD_CZYNSZ',
    'IDE_CZYNSZ',
);


$defI = array(
  'NR_SYSTEMC',
  'KODA',
  'NAZWA:',
  'KWOTAt',
  'K_SYN_WNŰ',
  'K_ANAL_WN',
  'K_SYN_MA',
  'K_ANAL_MA',
  'DAT_DOK',
  'SP_ZAP',
  'IL_DNI',
  'DAT_ZAP',
  'KWOTA_WA',
  'SYMB_WA',
  'KURS_WAL:',
);

$rel = array();

$acc = array();

$kinds = array();

$ident = array();

$table = array();

$symbols = array();

function addRegister($kind, $a, $c = false) {
    global $pcmap, $def, $acc, $pdo, $rel, $kinds, $ident, $symbols;

    // echo var_export($a, true);
    // echo var_export(array_keys($a), true);
    // exit;

    $r = array_combine($def, $a);

    $now = new DateTime();

    $documentDate = clone $now;
    $documentDate->setDate(substr($r['DAT_DOK'], 0, 4), substr($r['DAT_DOK'], 4, 2), substr($r['DAT_DOK'], 6, 2));
    $documentDate->setTime(0, 0, 0);

    $znDate = clone $now;
    $znDate->setDate(substr($r['DAT_ZN'], 0, 4), substr($r['DAT_ZN'], 4, 2), substr($r['DAT_ZN'], 6, 2));
    $znDate->setTime(0, 0, 0);

    $zapDate = clone $now;
    $zapDate->setDate(substr($r['DAT_ZAP'], 0, 4), substr($r['DAT_ZAP'], 4, 2), substr($r['DAT_ZAP'], 6, 2));
    $zapDate->setTime(0, 0, 0);

    $rejDate = clone $now;
    $rejDate->setDate(substr($r['DAT_REJ'], 0, 4), substr($r['DAT_REJ'], 4, 2), substr($r['DAT_REJ'], 6, 2));
    $rejDate->setTime(0, 0, 0);

    $zgoDate = clone $now;
    
    if ($r['DAT_ZGO']) {
        $zgoDate->setDate(substr($r['DAT_ZGO'], 0, 4), substr($r['DAT_ZGO'], 4, 2), substr($r['DAT_ZGO'], 6, 2));
        $zgoDate->setTime(0, 0, 0);
    } else {
        $zgoDate = false;
    }
    
    $arr = array(
        'id' => create_guid(),
        'date_entered' => $now ? $now->format('Y-m-d') : '',
        // 'date_modified' => '',
        'created_by' => 'd9c0007b-1247-5e82-31b6-4f168a01d290',
        // 'modified_by' => '',
        'deleted' => '0',
        'description' => addslashes(ch(($r['OPIS_1']) . (strlen($o = ($r['OPIS_2'])) ? (PHP_EOL . $o) : ''))),
        'type' => 0,
        'ecmfkvatkind_id' => $kind,
        'status' => 0,
        'year' => $r['ROK'],
        'month' => $r['MIESIAC'],
        'sym_oper' => $r['SYM_OPER'],
        'nr_sys' => $r['NR_SYSTEM'],
        // 'ident_k' => $r['IDENT_K'],
        'ident_k_id' => $r['IDENT_K'],//
        'sym_dok' => $r['SYM_DOK'],
        'sym_dok_id' => $r['SYM_DOK'],//
        'nr_dok' => $r['NR_DOK'],
        'poz_dok' => $r['POZ_DOK'],
        'dat_dok' => $documentDate ? $documentDate->format('Y-m-d') : '',
        'id_dok' => $r['ID_DOK'],
        'spar_tr' => $r['SPAR_TR'],
        'zob_nal' => $r['ZOB_NAL'],
        'dat_zn' => $znDate ? $znDate->format('Y-m-d') : '',
        'sym_par' => $r['SYM_PAR'],
        'sym_par_id' => $r['SYM_PAR'],//
        'nr_par' => $r['NR_PAR'],
        'sp_zap' => $pcmap[$r['SP_ZAP']],
        'il_dni' => $r['IL_DNI'],
        'dat_zap' => $zapDate ? $zapDate->format('Y-m-d') : '',
        'acc' => $r['K_SYN'] . (($anal = $r['K_ANAL']) ? ('-' . $anal) : ''),
        'dat_rej' => $rejDate ? $rejDate->format('Y-m-d') : '',
        'amount' => $r['KWOTA'],
        'acc_wn' => $r['K_SYN_WN'] . (($analWn = $r['K_ANAL_WN;']) ? ('-' . $analWn) : ''),
        'acc_ma' => $r['K_SYN_MA'] . (($analMa = $r['K_ANAL_MA']) ? ('-' . $analMa) : ''),
        'nickname' => $r['NICKNAME'],
        'nip' => $r['NIP'],
        'reserve' => $r['REZERWA'],
        'kwota_wal' => $r['KWOTA_WAL'],
        'symbol_wal' => $r['SYMB_WAL'],
        'kurs_wal' => $r['KURS_WAL'],
        'dat_zgo' => $zgoDate ? $zgoDate->format('Y-m-d') : '',
        'kod_czynsz' => $r['KOD_CZYNSZ'],
        'ide_czynsz' => $r['IDE_CZYNSZ'],
    );
    
    if (true == array_key_exists($key = $arr['sym_dok_id'], $symbols)) {
        $arr['sym_dok_id'] = $symbols[$key];
    } else {
        $q = 'select id from ecmsymbols where symbol = \'' . $key . '\'  LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (true == is_array($result)) {
            $arr['sym_dok_id'] = $symbols[$key] = $result['id'];
        } else {
            $arr['sym_dok_id'] = null;
        }
    }
    
    if (true == array_key_exists($key = $arr['sym_par_id'], $symbols)) {
        $arr['sym_par_id'] = $symbols[$key];
    } else {
        $q = 'select id from ecmsymbols where symbol = \'' . $key . '\'  LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (true == is_array($result)) {
            $arr['sym_par_id'] = $symbols[$key] = $result['id'];
        } else {
            $arr['sym_par_id'] = null;
        }
    }
    
    if (true == array_key_exists($key = $arr['ecmfkvatkind_id'], $kinds)) {
        $arr['ecmfkvatkind_id'] = $kinds[$key];
    } else {
        $q = 'select id from ecmfkvatkinds where position = \'' . $key . '\' and type = \'' . 4 . '\' LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (true == is_array($result)) {
            $arr['ecmfkvatkind_id'] = $kinds[$key] = $result['id'];
        } else {
            $arr['ecmfkvatkind_id'] = null;
        }
    }

    if (true == array_key_exists($key = $arr['ident_k_id'], $ident)) {
        $arr['ident_k_id'] = $ident[$key];
    } else {
        $q = 'select id from ecmidentifiers where name = \'' . $key . '\' LIMIT 1;';
        // echo var_export($q, true);
        // exit;
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (true == is_array($result)) {
            $arr['ident_k_id'] = $ident[$key] = $result['id'];
        } else {
            $arr['ident_k_id'] = null;
        }
    }

    if (true == array_key_exists($key = (string) $arr['acc'], $acc)) {
        $arr['acc'] = $acc[$key];
    } else {
        $q = 'select id from ecmbankaccounts where code = \'' . $key . '\' LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (true == is_array($result)) {
            $arr['acc'] = $acc[$key] = $result['id'];
        } else {
            $arr['acc'] = null;
        }
    }

    if (true == array_key_exists($key = (string) $arr['acc_wn'], $acc)) {
        $arr['acc_wn'] = $acc[$key];
    } else {
        $q = 'select id from ecmbankaccounts where code = \'' . $key . '\' LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (true == is_array($result)) {
            $arr['acc_wn'] = $acc[$key] = $result['id'];
        } else {
            $arr['acc_wn'] = null;
        }
    }

    if (true == array_key_exists($key = (string) $arr['acc_ma'], $acc)) {
        $arr['acc_ma'] = $acc[$key];
    } else {
        $q = 'select id from ecmbankaccounts where code = \'' . $key . '\' LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (true == is_array($result)) {
            $arr['acc_ma'] = $acc[$key] = $result['id'];
        } else {
            $arr['acc_ma'] = null;
        }
    }
    
    // echo var_export($r, true);
    // echo PHP_EOL . PHP_EOL;
    // echo var_export($arr, true);
    // exit;

    // $arr = array_filter($arr, 'strlen');
    $in = array();
    
    foreach ($arr as $k => $v) {
        $in[] = sprintf('`%s` = \'%s\'', $k, ch($v));
        // $out[] = sprintf('`%s` VARCHAR(25) DEFAULT NULL' . PHP_EOL, $k);
    }

    $q = 'INSERT INTO `ecmfkvatregisters` SET ' . implode(', ', $in) . ';';

    // echo var_export(implode(', ', $out), true);
    // exit;
    
    $stmt = $pdo->prepare($q);
    $stmt->execute();
    
    if (($e = $stmt->errorCode()) != '0000') {
        echo var_export($q, true);
        echo PHP_EOL;
        echo var_export($stmt->errorInfo(), true);
        echo PHP_EOL;
        exit;
        // return false;
    }

    if (true == $c) {
        echo var_export($arr['id'], true);
        echo PHP_EOL;
    }
    
    
    $rel[$arr['nr_sys']] = $arr['id'];
    
    return true;
}

// waluty.dbf
$curr = array(
    'EURO' => 'EURO',
    'USD' => 'DOLAR AMERYKAŃSKI',
    'SEK' => 'KORONA SZWECKA',
    '0210' => 'OLEJ NAP. 3,5T',
    '0230' => 'BENZYNA',
    '0220' => 'OLEJ OSOBOWE',
    '0240' => 'GAZ OSOBOWE',
    '0250' => '0250',
);

$t = array();

function addRegisterItem($a, $c = false) {
    global $curr, $t, $defI, $acc, $pdo, $rel;

    // echo var_export(array_keys($a), true);
    // exit;

    $r = array_combine($defI, $a);

    $now = new DateTime();

    $dokDate = clone $now;
    $dokDate->setDate(substr($r['DAT_DOK'], 0, 4), substr($r['DAT_DOK'], 4, 2), substr($r['DAT_DOK'], 6, 2));
    $dokDate->setTime(0, 0, 0);

    $zapDate = clone $now;
    $zapDate->setDate(substr($r['DAT_ZAP'], 0, 4), substr($r['DAT_ZAP'], 4, 2), substr($r['DAT_ZAP'], 6, 2));
    $zapDate->setTime(0, 0, 0);

    $arr = array(
        'id' => create_guid(),
        'date_entered' => $now->format('Y-m-d'),
        // 'date_modified' => '',
        'created_by' => 'd9c0007b-1247-5e82-31b6-4f168a01d290',
        // 'modified_user_id' => '',
        'deleted' => '0',
        'nr_sys' => $r['NR_SYSTEMC'],
        'code' => $r['KODA'],
        'ecmfkvattable_id' => $r['KODA'],
        'name' => $r['NAZWA:'],
        'amount' => $r['KWOTAt'],
        'acc_wn' => $r['K_SYN_WNŰ'] . (($sWn = $r['K_ANAL_WN']) ? ('-' . $sWn) : ''),
        'acc_ma' => $r['K_SYN_MA'] . (($sMa = $r['K_ANAL_MA']) ? ('-' . $sMa) : ''),
        'dat_dok' => $r['DAT_DOK'] ? $dokDate->format('Y-m-d') : '',
        'sp_zap' => $r['SP_ZAP'],
        'il_dni' => $r['IL_DNI'],
        'dat_zap' => $r['DAT_ZAP'] ? $zapDate->format('Y-m-d') : '',
        'kwota_wa' => $r['KWOTA_WA'],
        'symb_wa' => $r['SYMB_WA'],
        'kurs_wal' => $r['KURS_WAL:'],

    );
    
    $arr['ecmfkvatregister_id'] = $rel[$arr['nr_sys']];
       
    
    if (true == array_key_exists($key = (string) $arr['ecmfkvattable_id'], $t)) {
        $arr['ecmfkvattable_id'] = $t[$key];
    } else {
        $q = 'select id from ecmfkvattables where position = \'' . $key . '\' and type = ' . 0 . ' LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (true == is_array($result)) {
            $arr['ecmfkvattable_id'] = $t[$key] = $result['id'];
        } else {
            $arr['ecmfkvattable_id'] = null;
        }
    }
    
    if (true == array_key_exists($key = (string) $arr['acc_wn'], $acc)) {
        $arr['acc_wn'] = $acc[$key];
    } else {
        $q = 'select id from ecmbankaccounts where code = \'' . $key . '\' LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (true == is_array($result)) {
            $arr['acc_wn'] = $acc[$key] = $result['id'];
        } else {
            $arr['acc_wn'] = null;
        }
    }

    if (true == array_key_exists($key = (string) $arr['acc_ma'], $acc)) {
        $arr['acc_ma'] = $acc[$key];
    } else {
        $q = 'select id from ecmbankaccounts where code = \'' . $key . '\' LIMIT 1;';
        // echo var_export($q, true);
        
        $stmt = $pdo->prepare($q);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (true == is_array($result)) {
            $arr['acc_ma'] = $acc[$key] = $result['id'];
        } else {
            $arr['acc_ma'] = null;
        }
    }
    
    // echo var_export($r, true);
    // echo PHP_EOL . PHP_EOL;
    // echo var_export($arr, true);
    // exit;

    // $arr = array_filter($arr, 'strlen');
    $in = array();
    
    foreach ($arr as $k => $v) {
        $in[] = sprintf('`%s` = \'%s\'', $k, ch($v));
        // $out[] = sprintf('`%s` VARCHAR(25) DEFAULT NULL' . PHP_EOL, $k);
    }

    $q = 'INSERT INTO `ecmfkvatregisteritems` SET ' . implode(', ', $in) . ';';

    // echo var_export(implode(', ', $out), true);
    // exit;
    
    $stmt = $pdo->prepare($q);
    $stmt->execute();
    
    if (($e = $stmt->errorCode()) != '0000') {
        echo var_export($q, true);
        echo PHP_EOL;
        echo var_export($stmt->errorInfo(), true);
        echo PHP_EOL;
        exit;
        // return false;
    }

    if (true == $c) {
        echo var_export($arr['id'], true);
        echo PHP_EOL;
    }
    
    return true;
}

// EOF: Methods used with importing.
// BOF: Importing preparation.
include_once('../EcmFkBooks/class.dbf.php');
include_once('../EcmFkBooks/helper.php');


$files = array(
    'registers' => array(),
    'registeritems' => array(),
);

$dir = implode(DIRECTORY_SEPARATOR, array('import', 'o'));

$di = new DirectoryIterator($dir);

foreach ($di as $d) {
    if (true == $d->isFile() && false == $d->isDot()) {
        $matchCount = preg_match('/(\w{1})(\d{2})(\w{1})(\d{2})(\d{2})(\.dbf)$/i', $filename = $d->getFilename(), $matches);

        if ($matchCount) {
            list($match, $type, $pos, $importType, $year, $month) = $matches;

            switch ($importType) {
                default:
                    throw new Exception('Unknown type.');
                    break;
                case '_':
                    array_push($files['registers'], $filename);
                    break;
                case 't':
                    array_push($files['registeritems'], $filename);
                    break;
            }
        }
    }
}

// EOF: Importing preparation.
// echo var_export($files, true);
// exit;

// BOF: Importing.
$start = microtime(true);

$iT = $createdI = 0;
/**/
foreach ($files['registers'] as $k => $v) {
    $dbfp = new dbf_class($dir . DIRECTORY_SEPARATOR . $v);

    $kind = substr($v, 1, 2);
    // var_export((int)$kind);exit;    
    
    for ($i = 0, $iT += $iC = $dbfp->dbf_num_rec; $i < $iC; $i++) {
        $row = $dbfp->getRowAssoc($i);
        $createdI += addRegister((int)$kind, $row, false) ? 1 : 0;
    }
}

$jT = $createdJ = 0;

foreach ($files['registeritems'] as $k => $v) {
    $dbfp = new dbf_class($dir . DIRECTORY_SEPARATOR . $v);

    for ($j = 0, $jT += $jC = $dbfp->dbf_num_rec; $j < $jC; $j++) {
        $row = $dbfp->getRowAssoc($j);
        
        if(false == is_array($row)) {
            continue;
            // echo var_export(is_array($row), true) . PHP_EOL;
            // echo var_export($row, true) . PHP_EOL;
            // echo var_export($j, true) . PHP_EOL;
            // echo var_export($jC, true) . PHP_EOL;
            // echo var_export($v, true) . PHP_EOL;
            // exit;
        }
        
        $createdJ += addRegisterItem($row, false) ? 1 : 0;
    }
}


$stop = microtime(true);
$diff = $stop - $start;
// EOF: Importing.

// BOF: Summary.
echo 'Podsumowanie:' . PHP_EOL;
echo 'W dbf: ' . ($iT + $jT) . '(' . $iT . '|' . $jT. ')'. PHP_EOL;
echo 'Dodano: ' . ($createdI + $createdJ) . '(' . $createdI . '|' . $createdJ. ')' . PHP_EOL;

echo 'Czas trawania:' . ($diff / 60) . ' minut' . PHP_EOL;
// EOF: Summary.