<?php
require_once('common/header.php');
$locationObj = new Table("location");

if(isset($_POST['doReport'])){


    $table = new Table('transaction');

    $from = strtotime( $_POST['from'] );
    $to = strtotime( $_POST['to'] );
    $location = $_POST['location'];
    $filter = $_POST['filter'];

    // get pos in location
    $posObj = new Table('pos');
    $poss = $posObj->findWhere("`Location_id` = '$location'");

    foreach ($poss AS $k=>$v) {
        $poss[$k] = '"'.$v['Machineid'].'"';
    }

    $locationList = "(".implode(',',$poss).")";

    $q = "
    SELECT *
    FROM transaction
    WHERE 1=1";
    if ($from) {
        $q .= " AND Date >= '$from' ";
    }
    if ($to) {
        $q .= " AND Date <= '$to' ";
    }
    if ($locationList) {
        $q .= " AND Pos_id IN $locationList";
    }
    if ($filter ) {
        if ($filter == 'Bought') {
            $q .= " AND action LIKE  '%reduce%'  ";
        }
        if ($filter == 'Awarded points') {
            $q .= " AND action LIKE  '%add_points%'  ";
        }
        if ($filter == 'Redeemed points') {
            $q .= " AND action LIKE  '%redeem_points%'  ";
        }
    }

    $allRows    = $table->executeSql($q);


    $childTableInformation = $table->getChildTableInformation();
    //If no data is found, redirect to add new data

    $allFields = $table->getTableFields();

    //$columnsCount = count($allFields);
    //bug fixed:
    $columnsCount = $table->findSql("SELECT COUNT(id) AS COUNT FROM system WHERE table_name = '".unhashTable($tableName)."' AND is_visible = 1");
    $columnsCount = $columnsCount[0]['COUNT'];


    $tableInfo = $table->getTableInfo();

}

?>
<?php
/*
IMAGE POP
*/
include(ADMIN_PATH.DS."plugins".DS."imagepop.php");

if ($filter) {
    $loc =  reset($locationObj->findWhere("`id` = $location"));

    echo "<h3>Viewing: $filter - Location: {$loc['Location']} - From: {$_POST['from']} / To: {$_POST['to']}</h3>";
}
?>

<script type="text/javascript" src="<?php echo ADMIN_PATH_HTML;?>/js/qtip/qtip.js"></script>
<link rel="stylesheet" href="<?php echo ADMIN_PATH_HTML;?>/js/qtip/qtip.css" type="text/css" />


<div class="form round drop_shadow" id="list">

    <?php if (!empty($allRows)) { ?>
        <table cellpadding="0" cellspacing="0" border="0" class="display" id="example" style="width:100%">
            <thead>

                <tr class="ui-state-disabled">
                    <?php

                    foreach($allFields as $fieldName):

                        if(!$table->isFieldActive($fieldName) || !$table->isVisible($fieldName)){
                            continue;
                        }
                        ?>

                        <th style='text-align: center'><h2><?php echo printTableName($fieldName); ?></h2></th>
                        <?php endforeach; ?>

                </tr>
            </thead>
            <tbody class="content">
                <?php
                // count transactions & ponts
                $totalPoints = 0;
                $totalSpent = 0;

                foreach($allRows as $row) :

                    if ($tableName == 'branch_transactions') {
                        $totalPoints += $row['points_equivalent'];
                        $totalSpent += $row['purchase_value'];
                    }
                    ?>
                    <tr height="30" style="border-bottom:thin solid #eeeee1;line-height:30px;" id="sort_<?php echo $row['id']; ?>">
                        <?php  foreach ($row as $fieldName => $value):
                            $fieldValueDisplay = '';
                            if(!$table->isFieldActive($fieldName)  || !$table->isVisible($fieldName)){
                                continue;
                            }

                            $fieldType = $table->returnFieldType($fieldName);

                            // editable fields
                            $jeditable = '';
                            $nonEditable = array('id','photo_upload','checkbox','date','foreign','thumbnail','textarea','textarea_nostyles','enum','mp3_upload','select');
                            if (!in_array($fieldType,$nonEditable)){
                                $jeditable = 'jeditable';
                            }

                            $jeditable = '';


                            if($fieldType == 'foreign'){

                                //  $row[$fieldName] = $table->getForeignKeyValue($row[$fieldName],$fieldName);

                                $row[$fieldName] = join(' <> ',$table->createAdminBreadCrumb($row[$fieldName],$fieldName));
                                /*
                                $element = new FormElement($table->getRawTableName(), $fieldName, $row['id']);
                                $fieldValue = '';
                                $fieldValueDisplay = $element->displayFormElement();
                                */

                            }elseif($fieldType == 'colorpicker'){
                                $withHash = strpos($row[$fieldName],'#') !== false ? $row[$fieldName] : '#'.$row[$fieldName];
                                $row[$fieldName] = '<div style="width:30px; display:inline-block; height:30px; background:'. $withHash .'"></div><div style="display:inline-block; left: 10px;    position: relative;   top: -10px;">' .$withHash.'</div>';

                            }elseif($fieldType == 'checkbox'){
                                $row[$fieldName] = $row[$fieldName]==1 ? 'Yes' : 'No';
                            }elseif($fieldType == 'date'){
                                $row[$fieldName] = formatDate($row[$fieldName]);
                            }elseif($fieldType == 'photo_upload'){

                                if(empty($row[$fieldName])){
                                    $row[$fieldName] = 'No image added.';
                                } else {

                                    $row[$fieldName] = '    <div class="thumbnail-item">
                                    <a href="#"><img src="'.thumbnailLink($row[$fieldName],50,50).'" class="thumbnail"/></a>
                                    <div class="tooltip">
                                    <img src="'.thumbnailLink($row[$fieldName],330,185).'" alt="" width="330" height="185" />
                                    <span class="overlay"></span>
                                    </div>
                                    </div> ';
                                }

                            } else if ( $fieldType == 'thumbnail'){
                                if(empty($row[$fieldName])){
                                    $row[$fieldName] = 'No thumbnail added.';
                                } else {

                                    $row[$fieldName] = '    <div class="thumbnail-item">
                                    <a href="#"><img src="'.thumbnailLink($row[$fieldName],50,50).'" class="thumbnail"/></a>
                                    <div class="tooltip" style="border:0;outline:0;">
                                    <img src="'.thumbnailLink($row[$fieldName],100,null,false).'" alt=""  />
                                    <span class="overlay"></span>
                                    </div>
                                    </div> ';
                                }
                            }


                            if($fieldType != 'foreign'){
                                $fieldValue = truncateUtf8(strip_tags($row[$fieldName]),80);
                            }else{
                                $fieldValue=$row[$fieldName];
                            }
                            $fieldValueJeditable = '';
                            if ($jeditable != '') { $fieldValueJeditable = $fieldValue;}

                            if($fieldType == 'photo_upload' || $fieldType == 'thumbnail' || $fieldType == 'colorpicker'){
                                $fieldValue = $row[$fieldName];
                            }

                            // roy
                            if($fieldType == 'timestamp' ){
                                $fieldValue = date("Y-m-d H:i:s",$row[$fieldName]);
                            }
                           // if($fieldType == 'usd' ){
//                                $fieldValue = "USD ".round($row[$fieldName],2);
//                            }
//                            if($fieldType == 'lbp' ){
//                                $fieldValue = "LBP ".$row[$fieldName];
//                            }

                            $fieldValueDisplay = $fieldValue;

                            $currency = '';
                            if ($tableName = 'user' && $fieldName == 'Balance' ) {
                                $currency = ' USD';
                            }
                            ?>
                            <td align="center" class='<?php echo h($jeditable);?>' id='<?php echo h($fieldName);?>|<?php echo $row['id']?>|<?php echo h($fieldValue);?>'><?php echo $fieldValueDisplay .$currency; ?></td>
                            <?php endforeach; ?>


                    </tr>
                    <?php endforeach; ?>
            </tbody>
        </table><br />

        <?php
    } // end condtion empty all rows


    // reports part

    $locations = $locationObj->findAll();
    ?>
    <div class="clear"></div>

    <div>
    <br />
    <br />
        <form class='form' id='generatForm' method='post'>
            <h3>View most
            <select name='filter'>
            <option>Redeemed Points</option>
            <option>Bought</option>
            <option>Awarded points</option>
            </select>:
            </h3>
            <br />
            <div class='field'>
                <label class="input-control text">
                <div class='label'>Location</div>
                <select name='location' style='width:auto'>
                    <?php
                    foreach($locations AS $k=>$loc) {
                        echo "<option value='{$loc['id']}'>{$loc['Location']}</option>";
                    }
                    ?>
                </select>
            </div>
            </label>
            <br />
            <div class='field'>
                <label class="input-control text">
                    <div class='label'>From</div>
                    <input type='text'  class="date-pick" name='from' style='width:120px' />
                </label>
            </div>
            <br />
            <div class='field'>
                <label class="input-control text">
                    <div class='label'>To</div>
                    <input type='text'  class="date-pick" name='to' style='width:120px' />
                </label>
            </div>
            <br /> <br />
            <input class="submit round drop_shadow" name='doReport' type="submit" value="Submit" />
        </form>
    </div>



    <br />
    <br />
    <br />

    <div class="clear"></div>
    <!--<a href="<?php echo pageLink('csvExport.php?table='.$tableName.''); ?>">[Export to CSV]</a>-->
</div>
</form>
<?php if (!empty($allRows)) { ?>
    <script>
        var oTable;
        /*
        * define the column number of position column
        *  function to read data from cells dynamically on every sort
        */

        $(document).ready( function () {
            // initialize data tables
            // exclude sorting on last 2 columns
            // sort by 'pos' in case available
            var oTable = $('#example').dataTable( {
                "iDisplayLength": 25,
                "aLengthMenu": [[10, 25, 50, 100, 150, 200, 300, -1], [10, 25, 50, 100, 150, 200, 300, "All"]],
                "sDom": 'C<"clear">lfrtip',
                "oColVis": {
                    "aiExclude": [ <?php echo $columnsCount ; ?>,<?php echo $columnsCount + 1; ?> ]
                },
                "aoColumnDefs": [
                    { "bSortable": false, "aTargets": [ -1, -2 ] }
                ],
                "oLanguage": { "sSearch": "" }

            } );

            // add placeholder text to the search field
            $('.dataTables_filter input').attr("placeholder", "Search...");


            /* Apply the jEditable handlers to the table */
            $('td.jeditable', oTable.fnGetNodes()).editable( 'actions/jeditable.php', {
                "callback": function( sValue, y ) {
                    var aPos = oTable.fnGetPosition( this );
                    oTable.fnUpdate( sValue, aPos[0], aPos[1] );
                },
                "submitdata": function ( value, settings ) {
                    return {
                        "row_id": this.parentNode.getAttribute('id'),
                        "column": oTable.fnGetPosition( this )[2],
                        "table" : "<?php echo $tableName; ?>",
                        "token" : "<?php echo CSRF::generateToken(); ?>"
                    };
                },
                cssclass : 'metroJedit',
                tooltip: 'Click to edit...',
                indicator: "<img src='images/loading.gif' />",
                intercept: function (jsondata) {
                    obj = jQuery.parseJSON(jsondata);
                    // do something with obj.status and obj.other
                    if (obj.status == 'fail') {
                        var msg = "An error occured, value was not changed!";
                        if (obj.msg != '') {
                            msg = obj.msg;
                        }
                        alert (msg);
                    }
                    return(obj.value);
                }
            } );



        } );

        $(document).ready(function()
            {
                // MAKE SURE YOUR SELECTOR MATCHES SOMETHING IN YOUR HTML!!!
                $('.showAddChildrenTooltip').each(function() {
                    $(this).qtip({
                        content: {
                            text: $(this).closest("td").find('.tooltipAddChildrenText')
                        },
                        position  : {
                            my: 'top right',  // Position my top left...
                            at: 'bottom right',
                        },
                        hide: {
                            fixed: true
                        }
                    });
                });
        });
    </script>
    <?php } ?>
<!-- Advanced Search -->
<div class="advanced-search" style="display: none;">
    <form name="advancedSearch" method="post"  style="background: #001072; width: 400px; padding:10px;" action="<?php echo pageLink('list.php?table='.$tableName.'&action=search'); ?>">
        <fieldset>
            <legend><strong>Advanced Search</strong></legend>
            <?php foreach($tableInfo as $field) :

                if(in_array($field['field_type'], array ('auto_date','position','id','photo_upload','thumbnail','pdf_upload','mp3_upload'))){
                    continue;
                }
                ?>

                <div class="field">
                    <label class="input-control text"><strong><?php echo printTableName($field['field_name']); ?></strong>
                        <?php echo $table->getFormElement($field['field_name']); ?>
                    </label>
                </div>

                <?php endforeach; ?>
            <input type="submit" name="submit" value="Search" />
            <input type="reset" name="reset" value="Reset" />
        </fieldset>
    </form>
</div>
<!-- END Advanced Search -->

<?php if($table->isCrudEnabled()) :  ?>
    <div class="modal hide"></div>
    <div class="hide shadow round bulkEditContainer" id="bulkEditContainer">
        <div class="closeBulkEditBtn close">x</div>
        <div class="title">
            <h3>Edit Multiple entries</h3>
            <div class="result"></div>
        </div>
        <form action="actions/bulkEdit.php" method="post" name="bulkEditForm" class="bulkEditForm">
            <input type="hidden" name="token" value="<?php echo CSRF::generateToken(); ?>" />
            <div class="highlight input-control select">
                <label for="cmsgen_rowsToEdit">Select the rows you want to edit:</label><br />
                <select name="cmsgen_rowsToEdit[]" multiple="multiple" id="cmsgen_rowsToEdit" class="fullWidth">
                    <?php
                    $displayField = $table->getDisplayField();
                    foreach($allRows as $row) : ?>
                        <option value="<?php echo $row['id']; ?>"><?php echo $row['id'] .' | '.$row[$displayField]; ?></option>
                        <?php endforeach; ?>
                </select>
            </div>


            <?php
            //Loop through the current table's fields and output the corresponding form
            foreach($table->returnFieldsNamesTypes() as $fieldName => $fieldTypeLength){
                $fieldType = $table->getFieldType($fieldName);
                if(in_array($fieldName,array('id','pos')) || in_array($fieldType,array('photo_upload','thumbnail','textarea','mp3_upload','auto_date'))){
                    continue;
                }


                echo'<div class="field"><label class="input-control text"><div class="label '. ($table->isRequired($fieldName) ? 'required' : '' ) .'">';

                $tooltip = $table->getTooltip($fieldName);

                echo printTableName($fieldName);
                echo'</div>';
                echo $table->getFormElement($fieldName); //Displays the corresponding form element to the following field
                if(!empty($tooltip))
                    echo '<span title="'.$tooltip.'" class="tooltipMessage"></span>';

                echo '</label></div>';
                echo '<br />';

            }
            ?>
            <br />
            <button class="submit round drop_shadow saveBulkEdit" style="float:left">Save</button>
            <input class="submit round drop_shadow"  type="reset" value="Reset" style="float:left;margin-left:4px;">
            <button class="submit round drop_shadow closeBulkEditBtn"  value="Close" style="float:left;margin-left:4px; background: red;">Close</button>
            <input type="hidden" value="<?php echo $tableName;?>" name="table" />
        </form>
    </div>
    <?php endif; ?>
<?php if($table->isTableSortable()) : ?>
    <style type="text/css">
        #list tr td:nth-child(<?php echo $columnsCount; ?>){ cursor:move;}
    </style>
    <?php endif; ?>

<?php require_once('common/footer.php'); ?>