<?php

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');
    require_once('../EDokApiClient.inc'); 
    if (!isset(Config::$NAME_REGEX)) trigger_error('NAME_REGEX not defined', E_USER_ERROR);
    
    // 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);
        $res = preg_match(Config::$NAME_REGEX, $file_name, $params);
        if (!$res) {
            throw new Exception($file_name.' nie pasuje do wzorca "'.Config::$NAME_REGEX.'"');
        }
        $pi = pathinfo($file_name);
        $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');
        }
        
        //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;
        }
        if (!empty($data)) {
            $dtyp = $client->getDocumentTypeData($data);
            
            $params['dctpid'] = NULL;
			if (isset($dtyp[0]) && is_array($dtyp[0])) $dtyp = $dtyp[0];
            if (isset($dtyp['dctpid'])) $params['dctpid'] = $dtyp['dctpid'];            
        }
        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 ('.iconv('Windows-1250', 'UTF-8', $file_name).')',
			'fixinf' => str_replace('.pdf', '', iconv('Windows-1250', 'UTF-8', $file_name)),
            'target' => $target,
            'dctpid' => isset($params['dctpid']) ? $params['dctpid'] : 2,
		);
        if ($params['client'] !== '0_BEZ_KLIENTA') {
            $data['to_contact_symbol'] = $params['client'];
        }
        // data wplywu
        if (isset($params['adddat'])) {
            $data['adddat'] = preg_replace('/(\d{4})(\d{2})(\d{2})/', '$1-$2-$3', $params['adddat']);
        }
        // data wystawienia
        if (isset($params['crtdat'])) {
            $data['crtdat'] = preg_replace('/(\d{4})(\d{2})(\d{2})/', '$1-$2-$3', $params['crtdat']);
        }
//file_put_contents('c:/log.txt', implode(";", $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($fpath));
                $file_name = iconv('Windows-1250', 'UTF-8', $file_name);
                
                $dd = $client->addAttachmentToDocument($file, $file_name, $doc_id);
                
            } catch(SoapFault $fault) {
                throw new Exception("[{$fault->faultcode}]: {$fault->faultstring}");
            }
            if ($dd > 0) {
                // po udanych operacjach usuń plik
                rename($fpath, 'C:\\ED-SKANY\\WYSLANE\\'.$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
        //rename($fpath, $fpath.'_');
        
        trigger_error($e->getMessage(), E_USER_ERROR);
    }

exit(0);

?>
