<?php
/*
 * Barcode document creator
 * eDokumenty script
 * Copyrights by BetaSoft 2014 
 * 
 */
date_default_timezone_set('Europe/Warsaw');
error_reporting(E_ALL);
ini_set('memory_limit', '512M');
set_time_limit(120);
             
// ustawienie biezacej sciezki
$aCurDir = pathinfo(__FILE__);
$cdir = trim(getcwd(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
chdir($aCurDir['dirname']);

//trigger_error(''.$cdir.$file_name.'', E_USER_ERROR);
//exit(1);

function printHelp() {
    echo "\nLista obslugiwanych parametrów:\n";
    echo "\t-h - wyswietla pomoc - opis parametrow\n\n";
    echo "\t-f plik\n";
    //echo "\t-org target orunid\n";
    //echo "\t-a rodzaj akcji\n";
    echo "\n";
    
    exit(1);
}

$args = array();
if (isset($_SERVER['argv'])) {
    $args = $_SERVER['argv'];
    array_shift($args);
    
    $file_name = NULL;
    $action = NULL;
    
    if (($k = array_search('-f', $args)) !== FALSE) {
        $file_name = $args[++$k];
    } 
    if (($k = array_search('-a', $args)) !== FALSE) {
        $action = $args[++$k];
    } 

    if (empty($file_name) OR (array_search('-h', $args) !== FALSE)) {
        printHelp();
    }
    if (!file_exists($cdir.$file_name)) trigger_error('Plik '.$cdir.$file_name.' nie istnieje', E_USER_ERROR);
    if (!is_readable($cdir.$file_name)) trigger_error('Nie można czytać pliku '.$cdir.$file_name.'', E_USER_ERROR);
    
} else {
    printHelp();
}
    require_once('config.inc');
    
    if (!isset(Config::$NAME_REGEX)) trigger_error('NAME_REGEX not defined', E_USER_ERROR);
    
    require_once('EDokApiClient.inc');
    
    // w location 
	
    $ops = array(
        'location' => Config::$EDOK_API_LOCATION,
        "uri" => "eDokumentyAPI",
        'encoding'=>'UTF-8'
    );
            
    $client = new EDokApiClient(null, $ops);
    $client->setUser(Config::$EDOK_API_LOGIN);
    $client->setPass(md5(Config::$EDOK_API_PASSWORD));
    $header = new SoapHeader('eDokumentyAPI', 'entity_symbol', Config::$DEFAULT_ENTITY_SYMBOL);
    $client->__setSoapHeaders($header);
    
    try {
        $params = array();
        $file_name = trim($file_name);
        $pi = pathinfo($file_name);
        $data = array(
            '%source_path' => $cdir.$file_name,
            '%source_dir' => $cdir.$pi['dirname'],
            '%source_file' => $pi['basename'],
        );
        $fpath = $pi['dirname'];
        $file_name = $pi['basename'];
        
        $fpath = $cdir.$fpath.DIRECTORY_SEPARATOR.$file_name;
        
        if (file_exists($fpath) && is_readable($fpath)) {
            if (preg_match('/\.pdf$/i', $fpath)) {
                $eof = FALSE;
                $timeout = 15;
                while (--$timeout && !($fp = @fopen($fpath, 'rb'))) {
                    sleep(1);
                }
                if ($fp) {
                    $timeout = 20;
                    while (--$timeout) {
                        if (fseek($fp, -10, SEEK_END) > -1) {
                            $contents = fread($fp, 10);
                            if (strpos($contents, '%%EOF') !== FALSE) {
                                $eof = TRUE;
                                break;
                            }
                        }
                        sleep(1);
                    }
                    fclose($fp);
                }
                if (!$eof) {
                    throw new Exception('%%EOF not found in '.$fpath);
                }
            }
        } else {
            throw new Exception('can\'t open '.$fpath.' for reading');
        }
        
        // jeżeli to pdf zeskanowany to zmieniamy nazwę pliku na przeczytaną z qrcode
        if (preg_match(Config::$SOURCE_FILE_NAME_REGEX, $file_name)) {
            $file_name = '';
            $file_name_2 = str_replace('.pdf', '', $data['%source_path']);
            
            $cmd_path = realpath('poppler/bin');
            $cmd = '"'.$cmd_path.'\\pdftocairo.exe" -png -mono -singlefile "'.$data['%source_path'].'" "'.$file_name_2.'"'.PHP_EOL;
            $cmd_path = realpath('ZBar/bin');
            $cmd .= '"'.$cmd_path.'\\zbarimg.exe" -q --noxml --raw "'.$file_name_2.'.png"';
            
            $bat = md5($cmd).'.bat';
            
            file_put_contents($bat, $cmd);
            $res = exec($bat, $out, $ret);
            
            if (($ret !== 0) || empty($res)) {
                $cmd_path = realpath('poppler/bin');
                $cmd = '"'.$cmd_path.'\\pdftocairo.exe" -png -gray -singlefile "'.$data['%source_path'].'" "'.$file_name_2.'"'.PHP_EOL;
                $cmd_path = realpath('ZBar/bin');
                $cmd .= '"'.$cmd_path.'\\zbarimg.exe" -q --noxml --raw "'.$file_name_2.'.png"';
                
                file_put_contents($bat, $cmd);
                $res = exec($bat, $out, $ret);
            }
            
    //        unlink($bat);
    //        unlink($file_name_2.'.png');
            
            error_log(var_export($ret, true));
            error_log(var_export($res, true));
            error_log(var_export($out, true));

            if (($ret === 0) && !empty($res)) {
                $data['%code'] = $res;
                $file_name = str_replace(array_keys($data), array_values($data), Config::$TARGET_FILE);
                if (!$file_name || !preg_match(Config::$NAME_REGEX, $file_name, $params)) {
                    throw new Exception('Przeczytanna wartość kodu ('.$file_name.'), nie pasuje do wzorca "'.Config::$NAME_REGEX.'"');
                }
        
                $timeout = 2;
                while ($timeout-- && (($resr = @rename($data['%source_path'], $file_name)) == FALSE)) {
                    sleep(1);
                }
            }
        } else {
            exit(0);
        }
        
        if (!$file_name || !preg_match(Config::$NAME_REGEX, $file_name, $params)) {
            throw new Exception($file_name.' nie pasuje do wzorca "'.Config::$NAME_REGEX.'"');
        }
        
        //kazdy tekst musi być w UTF-8
        foreach($params as &$value) {
            if (!is_numeric($value)) { 
                $value = iconv('Windows-1250', 'UTF-8', $value);
            }
        }
        
        $data = array();    
        $params['dctpid'] = 2;
        if (isset($params['dctptp']) AND !empty($params['dctptp'])) {
            $data['dctptp'] = $params['dctptp'];
        }
        if (isset($params['dctpid']) AND !empty($params['dctpid'])) {
            $data['dctpid'] = 2;
        }
        //var_dump($data);
        if (!empty($data)) {
            $dtyp = $client->getDocumentTypeData($data);
        //var_dump($dtyp);
            
            $params['dctpid'] = NULL;
			if (isset($dtyp[0]) && is_array($dtyp[0])) $dtyp = $dtyp[0];
            if (isset($dtyp['dctpid'])) $params['dctpid'] = $dtyp['dctpid'];            
        }
        //var_dump($params);
        if (!isset($params['dctpid'])) {
            throw new Exception('');
        }
        $dscrpt = '';
        if ($dtyp['dctptp'] != 'Other') $dscrpt = $dtyp['dctpnm'];
        
        if (isset($params['type'])) $dscrpt .= (empty($dscrpt) ? '' : ' ').$params['type'];
        
        if (isset($params['name'])) $dscrpt .= ' od '.$params['name'];
        
        $target = (isset($params['target']) and $params['target']) ? $params['target'] : (isset(Config::$TARGET_ORUNID) ? Config::$TARGET_ORUNID : 1); 

		$data = array(
		    'dscrpt' => 'Dokument NR '.iconv('Windows-1250', 'UTF-8', $res),
			'fixinf' => str_replace('.pdf', '', iconv('Windows-1250', 'UTF-8', $file_name)),
            'target' => $target,
            'dctpid' => isset($params['dctpid']) ? $params['dctpid'] : 2,
		);
        if (isset($params['client']) AND ($params['client'] !== '0_BEZ_KLIENTA')) {
            $data['to_contact_symbol'] = $params['client'];
        }
        // data wplywu
        if (isset($params['adddat'])) {
            $data['adddat'] = preg_replace('/(\d{2})(\d{2})(\d{2})/', '20$3-$2-$1', $params['adddat']);
        }
        // data wystawienia
        if (isset($params['crtdat'])) {
            $data['crtdat'] = preg_replace('/(\d{4})(\d{2})(\d{2})/', '$1-$2-$3', $params['crtdat']);
        }
        //var_dump($data);
        //exit(0);
        try {
            $doc_id = $client->createDocument($data);
        
        } catch(SoapFault $fault) {
            throw new Exception("[{$fault->faultcode}]: {$fault->faultstring}");
        }
        if (isset($doc_id) AND $doc_id) {
            $dd = 0;
            try {
                $file = base64_encode(file_get_contents($file_name));
                $name = iconv('Windows-1250', 'UTF-8', $res.".pdf");
                
                $dd = $client->addAttachmentToDocument($file, $name, $doc_id);
                
            } catch(SoapFault $fault) {
                throw new Exception("[{$fault->faultcode}]: {$fault->faultstring}");
            }

                

            if ($dd > 0) {
                // po udanych operacjach usuń plik
                if (isset(Config::$SENT_DIR)) {
                    rename($file_name, rtrim(Config::$SENT_DIR, '\\/').'/'.$name);
                } else {
                    unlink($file_name);
                }
            } else {
                throw new Exception('Attachment not created');
            }
        } else {
            throw new Exception('Document not created (unknown error)');
        }
    
    } catch(Exception $e) {
        // oznacz błędny plik
        if (file_exists($fpath)) {
            rename($fpath, $fpath.'_');
        
            trigger_error($e->getMessage(), E_USER_ERROR);
        }
    }

exit(0);

?>