<form action="index.php">
<input type='hidden' name='module' value='EcmReports'>
<input  type='hidden' name='action' value='ewkaCSV'>
<table>
<tr>
	<td>
	Data od:
	</td>
	<td>
	<input autocomplete="off" type="text" name="date_start" id="date_start" value="<?php echo ''.($_REQUEST['date_start']!='' ? $_REQUEST['date_start'] : date('01.m.Y')).'' ?>" title="" tabindex="105" size="10" maxlength="10"> (dd.mm.yyyy)
	</td>
	<td>
	<img border="0" src="themes/Sugar5/images/jscalendar.gif?s=bed8cd35065048ceebdc639ebe305e2c&amp;c=1" alt="Wprowadź datę" id="date_start_trigger" align="absmiddle">
		<script type="text/javascript">
Calendar.setup ({
inputField : "date_start",
daFormat : "%d.%m.%Y %H:%M",
button : "date_start_trigger",
singleClick : true,
dateStr : "05.01.2016",
step : 1,
weekNumbers:false
}
);
</script>
	</td>
</tr>
<tr>
	<td>
	Data do:
	</td>
	<td>
	<input autocomplete="off" type="text" name="date_end" id="date_end" value="<?php echo ''.($_REQUEST['date_end']!='' ? $_REQUEST['date_end'] : date('t.m.Y')).'' ?>" title="" tabindex="105" size="10" maxlength="10"> (dd.mm.yyyy)
	</td>
	<td>
	<img border="0" src="themes/Sugar5/images/jscalendar.gif?s=bed8cd35065048ceebdc639ebe305e2c&amp;c=1" alt="Wprowadź datę" id="date_end_trigger" align="absmiddle">
			<script type="text/javascript">
Calendar.setup ({
inputField : "date_end",
daFormat : "%d.%m.%Y %H:%M",
button : "date_end_trigger",
singleClick : true,
dateStr : "05.01.2016",
step : 1,
weekNumbers:false
}
);
</script>
	</td>
</tr>
</table>
<br><input type="submit" value="Generuj" name="submit">
</form>
<?php
global $current_user;

class raportTxT {

    public $fileName;
    private $db;
    private $fp;
    private $separator;
    private $nl;
    private $header;
    private $to_write;
    private $docTypes;
    private $dateFrom;
    private $dateTo;
    private $stockList;

    function __construct($fileName, $separator, $nl,$date_start,$date_end) {
        $this->fileName = $fileName;
        $this->separator = $separator;
        $this->nl = $nl;
        $this->db = $GLOBALS['db'];
        $this->getStockList();
        $this->documentTypes();
        $this->setDateFrom(date('Y-m-d',strtotime($date_start)));
        $this->setDateTo(date('Y-m-d',strtotime($date_end)));
        $this->drawHeader();
        $this->openFile();
        $this->writeLine();
        $this->createFileContent();
    }

    function getStockList() {
        $res = $this->db->query('SELECT id, name, tmp_number FROM ecmstocks order by tmp_number');
        $this->stockList = array();
        while ($dane = $this->db->fetchByAssoc($res)) {
            $this->stockList[$dane['id']] = $dane;
        }
    }

    function getStockNumber($stockId) {
        return 'MG_' . $this->stockList[$stockId]['tmp_number'];
    }

    function setDateFrom($data = NULL) {
        if (isset($data) && strlen($data) > 8) {
            try {
                $this->dateFrom = new DateTime($data);
            } catch (Exception $e) {
                $this->dateFrom = NULL;
            }
        } else {
            $this->dateFrom = NULL;
        }
    }

    function setDateTo($data = NULL) {
        if (isset($data) && strlen($data) > 8) {
            try {
                $this->dateTo = new DateTime($data);
            } catch (Exception $e) {
                $this->dateTo = NULL;
            }
        } else {
            $this->dateTo = NULL;
        }
    }

    function getQueryWhere() {
        $check = false;
        $whereQuery = '';
        if (isset($this->dateFrom) && is_a($this->dateFrom, 'DateTime')) {
            if (!$check) {
                $check = true;
                $whereQuery = " WHERE ";
            }
            $whereQuery .= " register_date >= '" . $this->dateFrom->format("Y-m-d") ."' ";
        }
        if (isset($this->dateTo) && is_a($this->dateTo, 'DateTime')) {
            if (!$check) {
                $check = true;
                $whereQuery = " WHERE ";
            }
            $whereQuery .= " AND register_date <= '" . $this->dateTo->format("Y-m-d") . "' ";
        }
        $whereQuery.='and deleted=0 and canceled=0 ';
        if ($check) {
            return $whereQuery;
        } else {
            return '';
        }
    } 

    function openFile() {
        unlink($this->fileName);
        $this->fp = fopen($this->fileName, 'w+');
    }

    function documentTypes() {
        $tmp = array();
        $tmp[] = 'EcmStockDocIn';
        $tmp[] = 'EcmStockDocOut';
        $tmp[] = 'EcmInvoiceOut';
        $tmp[] = 'EcmStockDocInsideIn';
        $tmp[] = 'EcmStockDocInsideOut';
        $tmp[] = 'EcmStockDocCorrect';
        $tmp[] = 'EcmStockDocMove';

        $this->docTypes = $tmp;
        unset($tmp);
    }

    function createFileContent() {

        foreach ($this->docTypes as $key => $val) {
            $callMe = 'Get' . $val;

            $this->$callMe($val);
        }
    }

    function GetEcmInvoiceOut($mod) {
        // echo 'wywoluje?';
        // echo '<br>';
        // echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
        // echo '<br>';
        $zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
        // echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
        while ($dane = $this->db->fetchByAssoc($zap)) {
            // echo "<pre>";
            $tmp = array();

            if ($dane['type'] == 'normal') {
                $tmp[] = 'FK';
            } else {
                $tmp[] = 'KF';
            }
            $tmp[] = $dane['document_no'];
            $tmp[] = $dane['register_date'];
            $tmp[] = $dane['purchase_price'];
            $tmp[] = $dane['total_netto'];
            $tmp[] = $dane['total_vat'];
            $tmp[] = $dane['total_brutto'];
            $tmp[] = $dane['pdf_type'];
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $a = new Account();
            $a->retrieve($dane['parent_id']);
            $tmp[] = $a->ks_account;
            $tmp[] = $a->index_dbf;
			$tmp[] = $dane['payment_date_days'];
			$zap2 = $this->db->query("select name from ecminvoicecategories where id='".$dane['category']."'");
			$dane2 = $this->db->fetchByAssoc($zap2); 
			    
			
			$tmp[] = $dane2['name'];
			$tmp[]=  $dane['currency_value_nbp'];
			$tmp[] = '';
            unset($a);

            $this->to_write = implode($this->separator, $tmp) . ';';
            unset($tmp);
            $this->writeLine();
        }
    }

    function GetEcmStockDocOut($mod) {
        // echo 'wywoluje?';
        // echo '<br>';
        // echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
        // echo '<br>';
        global $app_list_strings;
        $zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
        while ($dane = $this->db->fetchByAssoc($zap)) {
            $purchasePrice = 0;
            $purchasePriceResult = $this->db->query("Select quantity*price as suma from ecmstockdocoutitems WHERE ecmstockdocout_id='" . $dane['id'] . "'");
            while ($danepurchase = $this->db->fetchByAssoc($purchasePriceResult)) {
                $purchasePrice += $danepurchase['suma'];
            }
            $tmp = array();
            $tmp[] = 'WZ';
            $tmp[] = $dane['document_no'];
            $tmp[] = $dane['register_date'];
            $tmp[] = $purchasePrice;
            $tmp[] = $dane['total_netto'];
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $a = new Account();
            $a->retrieve($dane['parent_id']);
            $tmp[] = $a->ks_account;
            $tmp[] = $a->index_dbf;
			$tmp[] = '';
			$tmp[] = $app_list_strings['ecmstockdocouts_category_list'][$dane['category']];
			$tmp[] = '';
			$tmp[] = '';
            unset($a);

            $this->to_write = implode($this->separator, $tmp) . ';';
            unset($tmp);
            $this->writeLine();
        }
    }

    function GetEcmStockDocIn($mod) {
        // echo 'wywoluje?';
        // echo '<br>';
        // echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
        // echo '<br>';
        $zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
        while ($dane = $this->db->fetchByAssoc($zap)) {
            $tmp = array();
            $tmp[] = 'PZ';
            $tmp[] = $dane['document_no'];
            $tmp[] = $dane['register_date'];
            $tmp[] = $dane['total_netto'];
            $tmp[] = $dane['total_netto'];
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = $dane['kind'];
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $a = new Account();
            $a->retrieve($dane['parent_id']);
            $tmp[] = $a->ks_account;
            $tmp[] = $a->index_dbf;
			$tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
            unset($a);

            $this->to_write = implode($this->separator, $tmp) . ';';
            unset($tmp);
            $this->writeLine();
        }
    }

    function GetEcmStockDocInsideIn($mod) {
        // echo 'wywoluje?';
        // echo '<br>';
        // echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
        // echo '<br>';
        $zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
        while ($dane = $this->db->fetchByAssoc($zap)) {
            $tmp = array();
            $tmp[] = 'PW';
            $tmp[] = $dane['document_no'];
            $tmp[] = $dane['register_date'];
            $tmp[] = $dane['total'];
            $tmp[] = $dane['total'];
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $a = new Account();
            $a->retrieve($dane['parent_id']);
            $tmp[] = '';
            $tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$kar= new EcmProductStockIndex();
			$kar->retrieve($dane['ecmproductstockindex_id']);
			$tmp[] = $kar->name;
            unset($a);
            unset($kar);
            $this->to_write = implode($this->separator, $tmp) . ';';
            unset($tmp);
            $this->writeLine();
        }
    }

    function GetEcmStockDocInsideOut($mod) {
        // echo 'wywoluje?';
        // echo '<br>';
        // echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
        // echo '<br>';
        $zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
        while ($dane = $this->db->fetchByAssoc($zap)) {
            $tmp = array();
            $tmp[] = 'RW';
            $tmp[] = $dane['document_no'];
            $tmp[] = $dane['register_date'];
            $tmp[] = $dane['total'];
            $tmp[] = $dane['total'];
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $a = new Account();
            $a->retrieve($dane['parent_id']);
            $tmp[] = '';
            $tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$kar= new EcmProductStockIndex();
			$kar->retrieve($dane['ecmproductstockindex_id']);
			$tmp[] = $kar->name;
            unset($a);
            unset($kar);

            $this->to_write = implode($this->separator, $tmp) . ';';
            unset($tmp);
            $this->writeLine();
        }
    }

    function GetEcmStockDocCorrect($mod) {
        // echo 'wywoluje?';
        // echo '<br>';
        // echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
        // echo '<br>';
        $zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
        while ($dane = $this->db->fetchByAssoc($zap)) {
            $tmp = array();
            $tmp[] = 'KS';
            $tmp[] = $dane['document_no'];
            $tmp[] = $dane['register_date'];
            $tmp[] = $dane['total'];
            $tmp[] = $dane['total'];
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $tmp[] = $this->getStockNumber($dane['stock_id']);
            $a = new Account();
            $a->retrieve($dane['parent_id']);
            $tmp[] = '';
            $tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$kar= new EcmProductStockIndex();
			$kar->retrieve($dane['ecmproductstockindex_id']);
			$tmp[] = $kar->name;
            unset($a);
            unset($kar);

            $this->to_write = implode($this->separator, $tmp) . ';';
            unset($tmp);
            $this->writeLine();
        }
    }

    function GetEcmStockDocMove($mod) {
        // echo 'wywoluje?';
        // echo '<br>';
        // echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
        // echo '<br>';
        $zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
        while ($dane = $this->db->fetchByAssoc($zap)) {
            $tmp = array();
            $tmp[] = 'MM';
            $tmp[] = $dane['document_no'];
            $tmp[] = $dane['register_date'];
            $tmp[] = $dane['total'];
            $tmp[] = $dane['total'];
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = '';
            $tmp[] = $this->getStockNumber($dane['stock_out_id']);
            $tmp[] = $this->getStockNumber($dane['stock_in_id']);
            $a = new Account();
            $a->retrieve($dane['parent_id']);
            $tmp[] = '';
            $tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$tmp[] = '';
			$kar= new EcmProductStockIndex();
			$kar->retrieve($dane['ecmproductstockindex_id']);
			$tmp[] = $kar->name;
            unset($a);
            unset($kar);

            $this->to_write = implode($this->separator, $tmp) . ';';
            unset($tmp);
            $this->writeLine();
        }
    }

    function closeFile() {
        fclose($this->fp);
    }

    function drawHeader() {
        $tmp = array();
        $tmp[] = 'SYMBOL DOK';
        $tmp[] = 'NR DOK';
        $tmp[] = 'DATA DOK';
        $tmp[] = 'WART MAG';
        $tmp[] = 'WART NET';
        $tmp[] = 'WART VAT';
        $tmp[] = 'WART B';
        $tmp[] = 'RODZAJ';
        $tmp[] = 'MAG ZR';
        $tmp[] = 'MAG DOC';
        $tmp[] = 'KONTO KS';
        $tmp[] = 'INDEKS';
		$tmp[] = 'DNI_PLATNOSCI'; 
		$tmp[] = 'KATEGORIA';
		$tmp[] = 'KURS VAL';
		$tmp[] = 'KARTOTEKA';

        $this->to_write = implode($this->separator, $tmp) . ';';
        unset($tmp);
    }

    function writeLine() {
        fwrite($this->fp, $this->to_write . $this->nl);
    }

} 
if($_REQUEST['submit']!=''){
$name='evka.csv';
$c = new raportTXT($name, ';', PHP_EOL,$_REQUEST['date_start'],$_REQUEST['date_end']);

$file=$name;


header("Location: ".$name);
}
?>