<?php

echo PHP_EOL;

$sql = mysql_connect('localhost', 'root', '1ptimu6');
mysql_select_db('crm');

$namesResult = mysql_query('SET NAMES utf8;');

if(false == $namesResult) {
    return;
}
 
$def = array(
    'KOD_VAT',
    'S_VAT',
    'PROC_VAT',
    'ZM_VAT',
    'PLUS_SV_SP',
    'PLUS_SV_ZK',
);

function addVat($a, $c = false) {
    global $def;
    
    $now = new DateTime();
  
    $r = array_combine($def, $a);
    
    $arr = array(
        'id' => create_guid(),
        'deleted' => '0',
        'date_entered' => $now->format('Y-m-d'),
        // 'date_modified' => '',
        'created_by' => 'd9c0007b-1247-5e82-31b6-4f168a01d290',
        // 'modified_user_id' => '',
        'position' => $r['KOD_VAT'],
        'symbol' => $r['S_VAT'],
        'percentage' => $r['PROC_VAT'],
        'zm' => $r['ZM_VAT'],
        'sp' => $r['PLUS_SV_SP'],
        'zk' => $r['PLUS_SV_ZK'],
    );

    // echo var_export($r, true);
    // echo PHP_EOL . PHP_EOL;
    // echo var_export($arr, true);
    // exit;
    
    $arr = array_filter($arr, 'strlen');

    foreach ($arr as $k => $v) {
        $in[] = sprintf('`%s` = \'%s\'', $k, $v);
    }

    $query = 'INSERT INTO `ecmfkvats` SET ' . implode(', ', $in) . ';';

    // echo $query . PHP_EOL;
    // exit;  
    
    mysql_query($query);

    if($e = mysql_error()) {
        echo $query;
        echo PHP_EOL . PHP_EOL;
        echo var_export(mysql_error(), true);
        echo PHP_EOL . PHP_EOL;
        return false;
    }

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

include_once('class.dbf.php');
include_once('helper.php');

$created = 0;
$dbfp = new dbf_class('import/t_vat.dbf');
$num_recp = $dbfp->dbf_num_rec;

$start = microtime(true);
for ($i = 0; $i < $num_recp; $i++) {
    $rowp = $dbfp->getRowAssoc($i);
    $created += addVat($rowp, true) ? 1 : 0;
}

$stop = microtime(true);
$diff = $stop - $start;

echo 'Podsumowanie:' . PHP_EOL;
echo 'W dbf: ' . $num_recp . PHP_EOL;
echo 'Dodano: ' . $created . PHP_EOL;

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

mysql_close($sql);