<?php
ini_set('display_errors',1);
/**
 * EcmKpkw report
 */
require_once('include/utils.php');
global $db,$app_strings;

$stop = new DateTime('NOW');

$start = clone $stop;
$start->sub(new DateInterval('P3Y'));

$currentTo = @$_GET['date_to'] ? : $stop->format('t.m.Y');
$currentFrom = @$_GET['date_from'] ? : $start->format('01.m.Y');

?>

<script type="text/javascript">
    window.onbeforeunload = function() {
        return '';
    };

    window.onunload = function() {
        var req = mint.Request();
        var url = 'index.php?module=EcmReports&action=interruptQuery';

        req.OnSuccess = function() {
            console.log(this.responseText);
        }

        req.Send(url);
    };
</script>

<style type="text/css">
    table.report {
        margin: 15px 0;
        width: 100%;

        border-spacing: 1px;

        font-family: 'Calibri';
        font-size: 13px;
    }

    table.report thead tr th,
    table.report tbody tr td {
        padding: 2px 5px;
        border: 1px solid #CCCCCC;

        text-align: center;
    }

    table.report thead tr th {
        background: #ebebeb;
    }

    table.report tbody tr.odd {
        background: #f6f6f6;
    }

    table.report tbody tr.even {
        background: #ffffff;
    }
</style>
<?php if($_GET['to_pdf']!=1){?>
<table cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td>
            <h2><?php echo translate('LBL_RAPORT_TITLE', 'EcmKpkw'); ?></h2>
        </td>
    </tr>
</table>

<br />

<ul class="tablist">
    <li>
        <a class="current" href="#">Opcje</a>
    </li>
</ul>

<form action="index.php" method="get" name="search_reports">
    <input type="hidden" name="module" value="EcmKpkw" />
    <input type="hidden" name="action" value="kpkw_report" />
    <input type="hidden" name="process" value="yes" />

    <table style="border-top: 0px none; margin-bottom: 4px; width:100%" class="tabForm" border="0" cellpadding="0" cellspacing="0">
        <tbody>
            <tr>
                <td class="dataLabel" width="5%" nowrap="nowrap">
                   <?php echo translate('LBL_DATE_START', 'EcmKpkw');?>
                </td>
                <td class="dataField" width="10%" nowrap="nowrap">
                    <input autocomplete="off" name="date_from" id="date_from" value="<? echo $currentFrom; ?>" title="" tabindex="" size="11" maxlength="10" type="text">
                    <img src="themes/default/images/jscalendar.gif" alt="Enter Date" id="date_from_trigger" align="absmiddle" border="0">
                    <script type="text/javascript">
                        Calendar.setup ({
                            inputField : "date_from",
                            daFormat : '<? echo str_replace(array('d', 'm', 'Y'), array('%d', '%m', '%Y'), $GLOBALS['timedate']->get_date_format()); ?>',
                            button : 'date_from_trigger',
                            singleClick : true,
                            dateStr : '',
                            step : 1
                        });
                    </script>
                </td>
                <td class="dataLabel" width="5%" nowrap="nowrap">
                   <?php echo translate('LBL_DATE_END', 'EcmKpkw');?>
                </td>
                <td class="dataField" width="10%" nowrap="nowrap">
                    <input autocomplete="off" name="date_to" id="date_to" value="<? echo $currentTo; ?>" title="" tabindex="" size="11" maxlength="10" type="text">
                    <img src="themes/default/images/jscalendar.gif" alt="Enter Date" id="date_to_trigger" align="absmiddle" border="0">
                    <script type="text/javascript">
                        Calendar.setup ({
                            inputField : "date_to",
                            daFormat : '<? echo str_replace(array('d', 'm', 'Y'), array('%d', '%m', '%Y'), $GLOBALS['timedate']->get_date_format()); ?>',
                            button : 'date_to_trigger',
                            singleClick : true,
                            dateStr : '',
                            step : 1
                        });
                    </script>
                </td>
				<td class="dataLabel" width="5%" nowrap="nowrap">
                     <?php echo translate('LBL_CASH2', 'EcmKpkw');?>
                </td>
                <td class="dataField" width="10%" nowrap="nowrap">
                    <input autocomplete="off" name="ecmcash_id" id="ecmcash_id" type="hidden" value="<?php echo $_GET['ecmcash_id'];?>" title="" tabindex="" size="11" maxlength="10" type="text">
                    <input autocomplete="off" name="id_currency" id="id_currency" type="hidden" value="<?php echo $_GET['id_currency'];?>" title="" tabindex="" size="11" maxlength="10" type="text">
                    <input autocomplete="off" name="cash_name" id="cash_name" value="<?php echo $_GET['cash_name'];?>" title="" tabindex="" size="11" maxlength="10" type="text">
                    <input title="Wybierz [Alt+T]" accesskey="T" type="button" class="button" value="<?php echo translate('LBL_SELECT', 'EcmKpkw');?>" name="btn1" onclick='open_popup("EcmCashs", 600, 400, "", true, false,
                         {"call_back_function":"set_return","form_name":"search_reports","field_to_name_array":
                             {"id":"ecmcash_id","name":"cash_name","currency_id":"id_currency"}}, "single", true);'></span>
                </td>
								<td class="dataLabel" width="5%" nowrap="nowrap">
                  <?php echo translate('LBL_CASH_USER2', 'EcmKpkw');?>
                </td>
                <td class="dataField" width="10%" nowrap="nowrap">
                  <select name="kasjer" id="kasjer">
				  <option value=""><?php echo translate('LBL_ALL', 'EcmKpkw');?></option>
				  <?php
				  $r=$GLOBALS['db']->query("select u.first_name,u.last_name,u.id from users as u join ecmcashs_ecmkpkw as rel on rel.user_id=u.id group by u.id");
				  	while($dn = $GLOBALS['db']->fetchByAssoc($r)){
		echo '<option value="'.$dn['id'].'" '.$sel.'>'.$dn['first_name'].' '.$dn['last_name'].'</option>';

	}
				  ?>
				  </select>
                </td>
                <td class="dataLabel" width="70%" nowrap="nowrap"></td>
            </tr>
        </tbody>
    </table> 
<?php 
$url="index.php?action=wydruk_raport&module=EcmKpkw&process=yes&to_pdf=1&date_from=".$_GET['date_from']."&date_to=".$_GET['date_to']."&kasjer=".$_GET['kasjer']."&ecmcash_id=".$_GET['ecmcash_id']."&cash_name=".$_GET['cash_name']."&id_currency=".$_GET['id_currency'];
?>
    <input class="button" value="<?php echo translate('LBL_SUBMIT', 'EcmKpkw');?>" type="submit"/>
    <input class="button" value="<?php echo translate('LBL_PRINT_PDF', 'EcmKpkw');?>" type="button" onClick="location.href='<?php echo $url;?>'"/>
</form>
<?php }?>
<div id="mainTable" style="overflow-x: scroll; width: 100%">
    <?php if(isset($_REQUEST['process'])) : ?>
        <?php
            $additionalWhereConditions = array(
                '\'' . $start->format('Y-m-01') . '\'',
                '\'' . $stop->format('Y-m-t') . '\'',
            );
	
            if($from = @$_GET['date_from']) {
                $fromDate = new DateTime($from);
                $additionalWhereConditions[0] = '\'' . $fromDate->format('Y-m-d') . '\'';
            }
			

            if($to = @$_GET['date_to']) {
                $toDate = new DateTime($to);
                $additionalWhereConditions[1] = '\'' . $toDate->format('Y-m-d') . '\'';
            }
            if($_GET['ecmcash_id']!=''){
                $additionalWhereConditions[2]='cash_id=\'' . $_GET['ecmcash_id'] . '\'';
            }
            if($_GET['kasjer']!=''){
            	$kasjer=" and `created_by`='".$_GET['kasjer']."'";
            } 
            	

            $additionalWhere = '`date_entered` BETWEEN ' . implode(' AND ', $additionalWhereConditions)." ".$kasjer;
            

            $query = '
                SELECT

				`description`,`description`,`amount`,`document_no`,
				`parent_address_street`,`parent_address_city`,`parent_address_postalcode`,
				`parent_address_country`,`parent_contact_name`,`parent_contact_title`,
				`date_entered`,`type_id`,`parent_name`

                FROM `ecmnewkpkws`

                WHERE
                ' . (additionalWhere ? ($additionalWhere) : '') . '

                ORDER BY

                `date_entered` ASC;
            ';

            // echo $query; //exit;
            echo $query;
            $result = $db->query($query);
			$query_bo = "SELECT SUM(IF(type_id = 0, amount, -amount)) AS `sum` FROM `ecmnewkpkws` WHERE `date_entered` < ".$additionalWhereConditions[0]." ".$kasjer;
			//echo $query_bo; exit;
			$result_bo = $db->query($query_bo);
			if($row_bo = $db->fetchByAssoc($db->query($query_bo)))
				{
					$bo = $row_bo["sum"];
					//ECHO $row["sum"];
				}
			
			
        ?>

        <?php if($result->num_rows > 0) : ?>
		<center><h1><?php echo translate('LBL_RAPORT_LABEL', 'EcmKpkw'); ?> <br><?php echo translate('LBL_TIME', 'EcmKpkw');?> <?php echo $fromDate->format('01/m/Y')." - ".$toDate->format('t/m/Y'); ?>
		<?php if($_GET['cash_name']!='') echo ", ".translate('LBL_CASH', 'EcmKpkw').": ".$_GET['cash_name'].", ".translate('LBL_CURRENCY_PDF', 'EcmKpkw').": ".$_GET['id_currency'];
		
		if($_GET['kasjer']!=''){
			$us=new User;
			$us->retrieve($_GET['kasjer']);
			echo ", ".translate('LBL_CASH_USER', 'EcmKpkw').": ". $us->full_name;	
		}
		?></h1></center><br>
            <table class="report" style="padding-top: 0px; margin-top:0px;">
                <tbody>
                <?php 
					$i = 0; 
					$suma1 = 0;	
					$suma2 = 0;
					
				?>
                <?php while($row = $db->fetchByAssoc($result)) : ?>
                    <?php $class = ($i % 2) ? 'odd' : 'even'; $i++; ?>
                    <tr class="<?php echo $class; ?>">
						<td width="5%"><?php echo $i ?></td>
						<td width="15%" style="text-align:left;"><table class="report" style="padding-top: 0px; margin-top:0px;"><tr class="<?php echo $class; ?>"><td style="text-align:left;"><?php echo $row['document_no']; ?></td></tr><tr><td style="text-align:left;"><?php echo date("d.m.Y", strtotime($row['date_entered'])); ?></td></tr></table></td>
						<td width="22%" style="text-align:left;"><?php echo $row['description']; ?></td>
						<td width="22%" style="text-align:left;"><?php echo $row['parent_name']; ?></td>
						<td width="17%" style="text-align:right;"><?php if($row['type_id']==0) { echo format_number($row['amount']); $suma1 += $row['amount']; } else echo "&nbsp;";?> 
						<td width="17%" style="text-align:right;"><?php if($row['type_id']==1) { echo format_number($row['amount']); $suma2 += $row['amount']; } else echo "&nbsp;";?> 
						</td>
                    </tr>
                <?php endwhile; ?>
				    <tr class="<?php
						$class = ($i % 2) ? 'odd' : 'even'; $i++; 
						echo $class; ?>">
						<td width="45%" style="border: 0px; background: #fff;" colspan="2">&nbsp;</td>
						<td width="15%" style="border: 0px; background: #fff;"></td>
						<td width="15%" style="text-align:left;"><?php echo translate('LBL_VALUE', 'EcmKpkw'); ?></td>
						<td width="15%" style="text-align:right;"><?php echo format_number(($suma1));  ?></td>
						<td width="20%" style="text-align:right;"><?php echo format_number(($suma2));  ?></td>
						<td width="20%" style="border: 0px;background: #fff;">&nbsp; 
						</td>
                    </tr>
				    <tr class="<?php
						$class = ($i % 2) ? 'odd' : 'even'; $i++; 
						echo $class; ?>">
						<td width="45%" style="border: 0px; background: #fff;" colspan="2">&nbsp;</td>
						<td width="15%" style="border: 0px; background: #fff;"></td>
						<td width="15%" style="text-align:left;"><?php echo translate('LBL_VALUE_BEFORE', 'EcmKpkw'); ?>:</td>
						<td width="15%" style="text-align:right;"><?php echo format_number(($bo));  ?></td>
						<td width="20%" style="text-align:right;"></td>
						<td width="20%" style="border: 0px;background: #fff;">&nbsp; 
						</td>
                    </tr>
				    <tr class="<?php
						$class = ($i % 2) ? 'odd' : 'even'; $i++; 
						echo $class; ?>">
						<td width="45%" style="border: 0px; background: #fff;" colspan="2">&nbsp;</td>
						<td width="15%" style="border: 0px; background: #fff;"></td>
						<td width="15%" style="text-align:left;"><?php echo translate('LBL_VALUE_TOTAL', 'EcmKpkw'); ?>:</td>
						<td width="15%" style="text-align:right;"><?php echo format_number((($bo+$suma1)-$suma2));  ?></td>
						<td width="20%" style="text-align:right;"></td>
						<td width="20%" style="border: 0px;background: #fff;">&nbsp; 
						</td>
                    </tr>
                </tbody>
                <thead>
                    <tr>
						<th><?php echo translate('LBL_NUMBER_LP', 'EcmKpkw'); ?></th>
                        <th><?php echo translate('LBL_DOCUMENT_NO', 'EcmKpkw'); ?><br><?php echo translate('LBL_CREATE_LAB', 'EcmKpkw'); ?></th>
						<th><?php echo translate('LBL_TITLE', 'EcmKpkw'); ?></th>
						<th><?php echo translate('LBL_PARENT_NAME', 'EcmKpkw'); ?></th>
						<th><?php echo translate('LBL_AMOUNT_PLUS', 'EcmKpkw'); ?></th>
						<th><?php echo translate('LBL_AMOUNT_MINUS', 'EcmKpkw'); ?></th>
                    </tr>
                </thead>
            </table>
        <?php else : ?>
            <p>Brak wyników dla danego okresu.</p>
        <?php endif; ?>
    <?php endif; ?>
</div>