<?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.'', 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);
}

$params = array();
$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 (($k = array_search('-dctpid', $args)) !== FALSE) {
        $dctpid = trim($args[++$k]);
        if (preg_match('/^\d+$/', $dctpid)) $params['dctpid'] = $dctpid;
    } 
    
    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');
    
    // 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 {
        $file_name = trim($file_name);
        $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)) {
            $eof = FALSE;
            $timeout = 15;
            while (--$timeout && !($fp = @fopen($fpath, 'rb'))) {
                sleep(1);
            }
            if ($fp) {
                fclose($fp);
            }
        } 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);
            }
        }
        
        $dscrpt = '';
        $data = array();    
        if (!isset($params['dctpid']) AND isset($params['dctptp']) AND !empty($params['dctptp'])) {
            $data['dctptp'] = $params['dctptp'];
        }
        if (!empty($data)) {
            $dtyp = $client->getDocumentTypeData($data);
            
            $params['dctpid'] = NULL;
            if (isset($dtyp['dctpid'])) {
                $params['dctpid'] = $dtyp['dctpid'];
                
                if ($dtyp['dctptp'] != 'Other') $dscrpt = $dtyp['dctpnm'];
            }
        }
        
        $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' => iconv('Windows-1250', 'UTF-8', $file_name),
            'target' => $target,
            'dctpid' => isset($params['dctpid']) ? $params['dctpid'] : 2,
		);
        
        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
                if (isset(Config::$SENT_DIR)) {
                    rename($fpath, rtrim(Config::$SENT_DIR, '\\/').'/'.$file_name);
                } else {
                    unlink($fpath);
                }
            } 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);

?>
