<?php
/**
 * Salva tabela de redução de stand para o Laudo Soja Granizo (lf016)
 */
preg_match("/^agrobr-app02\.*/", gethostname(), $matches);

if (count($matches)>0) {
    set_include_path(get_include_path().':/var/www/html/library/');
    $env = 'production';
} else {
    set_include_path(get_include_path().':/usr/share/php/:../library/');
    $env = 'docker';
}

require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();

$config = new Zend_Config_Ini('../application/config/application.ini', $env);

$Adapter = Zend_Db::factory('PDO_PGSQL', $config->resources->db->params);
Zend_Db_Table_Abstract::setDefaultAdapter($Adapter);
$db = Zend_Db_Table::getDefaultAdapter();
$table = 'regulacao.lf016_auxiliar_reducao_stand';

if (!isset($argv[1]) || empty($argv[1])) {
    print("\e[0;31mInforme um nome de arquivo(Ex: arquivo.csv)!\e[0m\n"); exit;
}

$fileName = $argv[1];
if (file_exists($fileName)) {
    $fileHandle = fopen($fileName, "r");
} else {
    print("\e[0;31mEste arquivo não existe!\e[0m\n"); exit;
}

$db->delete($table);

$count = 0;
while (($row = fgetcsv($fileHandle, 0, ";")) !== FALSE) {
    $count++;
}
$count--;


$i = 0;
$cabecalho = [];
rewind($fileHandle);
while (($row = fgetcsv($fileHandle, 0, ";")) !== FALSE) {
    if ($i == 0) {
        $cabecalho = $row;
    } else {
        foreach ($row as $key => $r) {
            if ($key > 0)
                $db->insert($table, array('vl_stand_original' => $row[0], 'vl_stand_restante' => $cabecalho[$key], 'vl_dano' => $r));
        }
    }
    
    printPerc($i, $count);
    $i++;
}


function printPerc($i, $count) {
    $perc = ($i/$count)*100;
    print("[");
    for($j = 0;$j<100;$j++) {
        if ($j<=$perc)
            print("#");
        else
            print(" ");
    }
    print("] ");
    print(number_format($perc)."% ");
    print("(".$i."/".$count.")\r");
}

//formato do arquivo csv, sendo a linha o stand original e a coluna o stand restante
//      445	444	443	442	441	440	439	438	437	436	435	434	433	432	431	430 ...
// 445	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 444	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 443	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 442	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 441	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 440	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 439	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 438	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 437	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 436	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 435	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 434	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 433	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 432	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 431	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 430	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// 429	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
// .
// .
// .