<?php
require_once('common/header.php');

if(!empty($_GET['table'])){
		$tableName = $_GET['table'];
}else{
		$session->message('<strong>Please select a table.</strong>');
		redirect_to("dashboard.php?errorPage=list.php");
}

$table = new Table($tableName);

$totalRows  = $table->countAllRows();//Total number of entries
//Pagination
$page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = PER_PAGE;
$maxPages = ceil($totalRows/$perPage);//maximum number of pages that could be returned
$pagination = new Pagination($page,$perPage,$totalRows);


$allRows    = $table->optimizedList( 
		array (
				'pagination' => $pagination
		));

$childTableInformation = $table->getChildTableInformation();
//If no data is found, redirect to add new data
if(empty($allRows) && !isset($_GET['action']) ){
		redirect_to("generate.php?table=".$tableName);
}elseif(empty($allRows) && isset($_GET['action']) && $_GET['action'] == 'search'){
		$session->message('<strong>No search results match your query.</strong>');
		redirect_to("list.php?table=".$tableName);
}

$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'];

//Delete IDs
if(!empty($_POST['delete'])){
	$table->deleteRows($_POST['ids']);
	die;
}

$tableInfo = $table->getTableInfo();
$inactiveFields = array (); //Array containing the fields that should not be displayed
$fieldTypesArray = array (); //Array containing the field types
?>
<?php
/*
IMAGE POP
*/
include(ADMIN_PATH.DS."plugins".DS."imagepop.php");
?>

<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" />

<form action="<?php echo pageLink('actions/delete.php'); ?>" method="post" enctype="multipart/form-data">
    <?php if(isset($_GET['action']) && $_GET['action'] == 'search') : ?>
        <h1 class="title">Advanced Search for <?php echo printTableName($tableName); ?> <a href='<?php echo pageLink('generate.php?table='.$tableName);?>'>[ + ]</a></h1>
        <?php else : ?>
        <h1 class="title">Listing all Entries <a href='<?php echo pageLink('generate.php?table='.$tableName);?>'>[ + ]</a></h1>
        <?php endif; ?>
    <hr />

    <?php if(isset($_GET['action']) && $_GET['action'] == 'search' && isset($_POST['data']['Search'] ) && !empty($_POST['data']['Search'] ) ) : ?>
        <h5>Searching for : </h5><?php
            foreach($_POST['data']['Search'] as $index => $value){
                if(empty($value)){
                    continue;   
                }
                echo '<strong>' .printTableName($index) .'</strong> : '. $value .' <br /> ';   
            }
        ?>
        <?php endif; ?>


    <div class="form round drop_shadow" id="list">
        <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):

                            $fieldType = $table->returnFieldType($fieldName);
                            $fieldTypesArray [$fieldName] = $fieldType;

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

                        <th style='text-align: center'><h2><?php echo printTableName($fieldName); ?></h2></th>
                        <?php endforeach; ?>
                    <th style="text-align: center;width:50px!important"><h2>Edit</h2></th>
                    <th style="text-align: center;width:50px!important">
                        <input type="checkbox" id="select-all" />
                    </th>
                </tr>
            </thead>
            <tbody class="content">
                <?php foreach($allRows as $row) : ?>
                    <tr height="30" style="border-bottom:thin solid #eeeee1;line-height:30px;" id="sort_<?php echo $row['id']; ?>">
                        <?php  foreach ($allFields as $fieldName):
                            $value = $row[$fieldName];
                            
                                $fieldValueDisplay = '';
                                if( in_array($fieldName,$inactiveFields) ){
                                    continue;
                                }

                                $fieldType = $fieldTypesArray[$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';
                                }


                                if($fieldType == 'foreign'){

                                  //  $row[$fieldName] = join(' <> ',$table->createAdminBreadCrumb($row[$fieldName],$fieldName));

                                }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];
                                }

                                $fieldValueDisplay = $fieldValue;

                            ?>
                            <td align="center" class='<?php echo h($jeditable);?>' id='<?php echo h($fieldName);?>|<?php echo $row['id']?>|<?php echo h($fieldValue);?>'><?php echo $fieldValueDisplay; ?></td>
                            <?php endforeach; ?>
                        <td width="30" style="text-align: center;"><a href="<?php echo pageLink('generate.php?table='.$tableName.'&id='.$row['id']); ?>"><img src="<?php echo ADMIN_PATH_HTML;?>/images/file_edit.png" width="20" alt="Edit" class="showAddChildrenTooltip" /></a>

                            <br />

                            <div class="tooltipAddChildrenText">
                                <a href="<?php echo pageLink('generate.php?table='.$tableName.'&id='.$row['id']); ?>">Edit this entry</a>
                                <br />
                                <br />

                                <?php foreach($childTableInformation as $childTable) : ?>
                                    <a style="font-size:10px;" href="<?php echo pageLink('generate.php?table='.$childTable['tableName'].'&'.$childTable['fieldName'].'='.$row['id']); ?>">Add <?php echo printTableName($childTable['tableName']); ?></a> <br />
                                    <?php endforeach; ?>
                                <?php if(VIEW_ON_WEBSITE_LINK) : ?>
                                    <a href="<?php  echo $table->returnFormatedLink($row['id']);   ?>">View on website</a>
                                    <?php endif; ?>
                            </div>
                        </td>
                        <td style="text-align: center;padding-right: 21px;">
                            <input type="checkbox" name="ids[]" value="<?php echo $row['id']; ?>" />
                        </td>

                    </tr>
                    <?php endforeach; ?>
            </tbody>
        </table><br />
      
        <?php echo $pagination->displayPagination(); ?>
        <div class="clear"></div>
        <br />
        <br />
        <br />
        <?php if($table->isCrudEnabled()) :  ?>
            <input type="hidden" name="table" value="<?php echo $tableName; ?>" />


            <!--  <input class="submit round drop_shadow"  type="button" value="Add" ONCLICK="window.location.href='<?php echo pageLink('generate.php?table='.$tableName);?>'"  style="float:left;margin-left:4px;" />-->
            <a class="submit drop_shadow" href="<?php echo pageLink('generate.php?table='.$tableName);?>"  style="float:left;margin-left:4px; text-align: center;height: 32px;line-height: 30px; color:#fff;"> Add </a>

            <input type="hidden" name="token" value="<?php echo CSRF::generateToken(); ?>" />
            <input type="submit" id="delete" name="delete" class="submit round drop_shadow" value="Delete" style="float:left;margin-left:4px;" />

            <input class="submit round drop_shadow" type="button" value="Inverse" id="inverse" style="float:left;margin-left:4px;" />

            <input class="submit round drop_shadow bulkEditBtn" type="button" value="Bulk Edit" id="bulkEditBtn" style="float:left;margin-left:4px;" />

            <input class="submit round drop_shadow advancedSearchBtn" type="button" value="Advanced Search" id="advancedSearchBtn" style="float:left;margin-left:4px;" />
            <?php endif; ?>

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

        $.fn.dataTableExt.afnSortData['dom-text'] = function  ( oSettings, iColumn ){
            return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
                    return $('td:eq('+iColumn+')', tr).html();
            } );
        }
        <?php endif; ?>
    $(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": "" }
                    <?php if ($table->isTableSortable()): ?>
                        ,"aoColumns": [<?php for($i=1;$i<$columnsCount;$i++) {echo 'null,';}?>{ "sSortDataType": "dom-text" },null,null  ],
                        "aaSorting": [[ posColumn, "asc" ]]
                        <?php else : ?>
                        ,"aoColumns": [<?php for($i=1;$i<$columnsCount;$i++) {echo 'null,';}?>{ "sSortDataType": "dom-text" },null,null  ],
                        "aaSorting": [[ 0, "desc" ]]
                        <?php endif; ?>
            } );

            // add placeholder text to the search field
            $('.dataTables_filter input').attr("placeholder", "Search...");
            <?php if($table->isTableSortable()) : ?>
                $("#list tbody.content").sortable({opacity: 0.6,cursor: 'move',items: "tr:not(.ui-state-disabled)",helper: function(e, tr){
                            var $originals = tr.children();
                            var $helper = tr.clone();
                            $helper.children().each(function(index)
                                {
                                    // Set helper cell sizes to match the original sizes
                                    $(this).width($originals.eq(index).width())
                            });
                            return $helper;
                        },update: function() {
                            var order = $(this).sortable("serialize") + '&action=updateRecordsListings&table=<?php echo $tableName; ?>&page=<?php echo $page; ?>';
                            var sortedIDs = $( this ).sortable( "toArray" );

                            $.post("<?php echo ADMIN_PATH_HTML; ?>/actions/order.php", order, function(theResponse){
                                    //                        var rows = oTable.fnGetNodes();
                                    var rows = $("#example tr");
                                    var cells = [];

                                    $.each(rows, function(i, row) {
                                            $(row).find("td:eq("+posColumn+")").html(i);
                                    });

                                    //                        for(var i=0;i<rows.length;i++){
                                    //                            var newOrder = i;
                                    //                            $(rows[i]).find("td:eq(2)").html(i);
                                    //                        }
                                    $("#saveResult").html(theResponse);
                                    $("#saveResult").hide();
                                    $("#saveResult").html("<div class='response_class'>Rows order updated</div>");
                                    $('#saveResult').fadeIn('slow').delay(2000).fadeOut("fast");
                            });
                        }
                });
                $("#list tbody.content").disableSelection();
                <?php endif; ?>



            /* 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>


        
<!-- 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 
                            switch($field['field_type']){
                                case 'checkbox':
                                    $element = new FormElement($table->getRawTableName(), $field['field_name'] );
                                    $fieldInfo = $element->getFieldInfo();
                                    echo '<select '.$fieldInfo.'>';
                                    echo '<option value="">Any</option>';
                                    echo '<option value="1">Checked</option>';
                                    echo '<option value="0">Unchecked</option>';
                                    echo '</select>';
                                    break;
                                default:
                                    echo $table->getFormElement($field['field_name']);
                                    break;   
                            }

                        ?>
                    </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'); ?>