<?php $this->xinclude('partials/header'); ?>

<?php if(System\Session::exists('error')): ?>
    <div class="home-error-wrap">
      <div class="alert btn-danger">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;&nbsp;<?php echo System\Session::flash('error'); ?>
      </div>
    </div>
<?php endif; ?>

<?php if(System\Session::exists('success')): ?>
    <div class="home-error-wrap">
        <div class="alert alert-success view-success">
          <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
          <h1><i class="fa fa-check" aria-hidden="true"></i>
          &nbsp; <?php echo System\Session::flash('success'); ?></h1>
        </div>
    </div><br/>
<?php endif; ?>

<div class="manage-links-wrapper">
    <h1 class="register-title">Manage <?php echo ucwords($this->recordType); ?></h1>

    <div class="row table-options">
        <div class="col-md-4">
          
          <?php if(in_array($this->recordType, ['links', 'users'])): ?>
            <form action="/manage/search" method="post">
                <div class="input-group">
                    <input type="text" value="<?php echo $this->searchTerm; ?>" class="form-control manage-search" name="search" placeholder="Search for a Record..." autocomplete="off">
                    <input type="hidden" name="record_type" value="<?php echo $this->recordType; ?>">
                    <span class="input-group-btn">
                        <button class="btn btn-primary" type="submit">Search Records</button>
                    </span> 
                 </div>
            </form>
          <?php endif; ?>
      
        </div>
        <div class="col-md-8 bulkActions">
            <div class="btn-group pull-right">
              <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                 Bulk Actions &nbsp;<i class="fa fa-caret-down" aria-hidden="true"></i>
             </button>
              <ul class="dropdown-menu">

                <li><a href="javascript:void(0);" id="deleteselectedrecords">
                    <i class="fa fa-times" aria-hidden="true"></i> Delete Selected</a>
                </li>
              </ul>
            </div>
            <div class="pull-right perPage"> Records Per Page:
                 <select id="showPerPage" class="show-per-page">
                    <option value="10" <?php if($this->perPage == 10){ echo "selected='selected'"; }?>>10</option>
                    <option value="25" <?php if($this->perPage == 25){ echo "selected='selected'"; }?>>25</option>
                    <option value="50" <?php if($this->perPage == 50){ echo "selected='selected'"; }?>>50</option>
                    <option value="100" <?php if($this->perPage == 100){ echo "selected='selected'"; }?>>100</option>
                    <option value="250" <?php if($this->perPage == 250){ echo "selected='selected'"; }?>>250</option>
                  </select>
            </div>
        </div>
    </div>

    <?php if(!System\Check::type('post')): ?>
      <div class="row paginateTopOptions">
          <div class="col-md-6 showingRecords">
             Showing <?php echo $this->showedCount;?> of <?php echo $this->totalFieldsCount;?> records
          </div>
      </div>
     <?php else: ?>
      <hr/> 
    <?php endif; ?>

    <div class="row" id="no-more-tables">
    <table id="dataTable" class="table table-bordered table-hover"> 
        <thead>
        <tr>
            <th class="check-all" id="checkAllRecords">
                <i class="fa fa-check-square" aria-hidden="true"></i>
             </th>
            <?php foreach ($this->fields as $k):

                $method = 'DESC';
                $iconMethod = 'desc';

                $order = ($this->sortOrder == 'DESC')? 'ASC' : 'DESC';

                if($k == $this->sortField){
                    $method = $order;
                    $iconMethod = strtolower($order);
                }
             
            if($k == 'id' && $this->isAdmin){ 

                echo'<th>
                     <a href="javascript:void(0);" class="sortByButton" fieldname="id" method="'.$method.'">
                        ID <i class="fa fa-sort-amount-'.$iconMethod.'" aria-hidden="true"></i>
                     </a>
                  </th>';
            }
            
            if($k == 'name'){

                 echo '<th>
                         <a href="javascript:void(0);" class="sortByButton" fieldname="uid" method="'.$method.'">
                            Name <i class="fa fa-sort-amount-'.$iconMethod.'" aria-hidden="true"></i>
                         </a>
                    </th>';

            }

             if($k == 'status'){

                echo ' <th>
                     <a href="javascript:void(0);" class="sortByButton" fieldname="status" method="'.$method.'">
                        Status <i class="fa fa-sort-amount-'.$iconMethod.'" aria-hidden="true"></i>
                     </a>
                </th>';
             }

            if($k == 'views'){

                 echo '<th>
                         <a href="javascript:void(0);" class="sortByButton" fieldname="views" method="'.$method.'">
                            Views <i class="fa fa-sort-amount-'.$iconMethod.'" aria-hidden="true"></i>
                         </a>
                    </th>';

            }

            if($k == 'username'){

                echo '<th>Username</th>';
            }

            if($k == 'paid'){

                echo '<th>Status</th>';
            }


            if($k == 'created'){

                $type = 'created';

                if($this->recordType == 'users')
                    $type = 'joined';

                echo '<th>
                     <a href="javascript:void(0);" class="sortByButton" fieldname="'.$type.'" method="'.$method.'">
                        Created <i class="fa fa-sort-amount-'.$iconMethod.'" aria-hidden="true"></i>
                     </a>
                </th>';
             }

             endforeach; ?>
            <th>Actions</th>
        </tr>
      </thead>
        <tbody>
        <?php foreach ($this->records as $value): 
            
           // get object vars 
          $recordVars = get_object_vars($value);

          ?>
           <tr> 
          <?php
            // if its a id
           if(isset($recordVars['id'])){

                $lid = $recordVars['id'];

                echo '<td data-title="Check" class="check">
                     <input type="checkbox" class="checkRecord" id="'.$lid.'">
                  </td>';
                  
              if($this->isAdmin)
                    echo '<td data-title="Id" class="recordId">'.$lid.'</td>';
           } 

           // if its a name
           if(isset($recordVars['name'])){  

                echo '<td data-title="Name">'.ucwords(limit_text($recordVars['name'], 50)).'</td>';
           }


                   // if its a name
           if(isset($recordVars['views'])){  

                echo '<td data-title="Views">'.number_format($recordVars['views']).'</td>';
           }


           // if its a status
           if(isset($recordVars['status'])){

             $statusColor = (in_array($recordVars['status'], ['reviewed', 'active']))? 'label-success' : 'label-danger';

            echo  '<td class="dataStatus" data-title="Status">
                   <span record_id="'.$lid.'" id="'.$recordVars['status'].'_'.$lid.'" status="'.$recordVars['status'].'" class="changeStatus label '.$statusColor.'">'.$recordVars['status'].'</span>
               </td>';
           }

             // if its a lang
           if(isset($recordVars['username'])){

            echo  '<td data-title="Username">
                      '.ucwords(limit_text($recordVars['username'], 50)).'
               </td>';

           }elseif($this->recordType == 'links' &&  $this->isAdmin){

              echo  '<td data-title="Username">
                    Anonymouse
               </td>';
           }

            if(isset($recordVars['paid'])){

              echo '<td data-title="Paid">'.$recordVars['paid'].'</td>';
           } 

                      // if its a date
           if(isset($recordVars['created'])){

              echo '<td data-title="Created">'.date('d M', strtotime($recordVars['created'])).'</td>';
           } 


         ?>
              
           <td  data-title="Actions" class="action">
            <div class="btn-group">
               
            <?php if(in_array($this->recordType, ['links', 'payment_history'])):

                if($this->recordType == 'payment_history'){

                    $edit = '/admin/edit/'.$lid;

                }else{

                    $edit = '/edit/'.$this->recordType.'/'.$lid;
                }

             ?>     
             <a href="<?php echo $edit; ?>" class="btn label-warning">
                 <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
             </a>
            <?php endif; ?>

               <?php 

               if($this->recordType == 'links'){

                $view = '/view/'.$recordVars['name'];

               }elseif($this->recordType == 'users'){

                $view = '/payment/'.$lid;

               }elseif($this->recordType == 'payment_history'){

                $view = '/payment/'.$recordVars['user_id'];

               }


               ?>
                <a target="_blank" href="<?php echo $view; ?>" class="btn label-info">
                    <i class="fa fa-eye" aria-hidden="true"></i>
                </a>

            <?php if(in_array($this->recordType, ['links'])): ?>
                 <a href="javascript:void(0);" data-id="<?php echo $lid; ?>" class="deleteRecord btn label-danger">
                     <i class="fa fa-trash-o" aria-hidden="true"></i>
                </a>
            <?php endif; ?>


                </div>
           </td>
        </tr>
         <?php  endforeach; ?>
      </tbody>
 </table>

</div>
<?php if(!System\Check::type('post')): ?>
<div class="row">
     <div class="col-md-12 paginateBottom">
            <ul id="paginationBottom" class="pagination pagination-right">
            </ul>
     </div>
</div>
<?php endif; ?>

</div>
<?php $this->xinclude('partials/footer'); ?>
<script src="/script/bootstrap-paginator.js"></script>  
<script src="/script/bootbox.min.js"></script> 

<script>

$(function(){

// pagination options
var options = {
    currentPage: <?php echo $this->currentPage; ?>,
    totalPages: <?php echo $this->totalPages; ?>,
    numberOfPages: 8,
    bootstrapMajorVersion: 3,
    alignment:"right",
    pageUrl: function(type, page, current){
        return "<?php echo '/manage/'.$this->recordType; ?>/p:"+page+"/pp:<?php echo $this->perPage.'/sby:'.$this->sortField.':'.$this->sortOrder; ?>";
    },
    useBootstrapTooltip:true,
    itemContainerClass: function (type, page, current) {
        return (page === current) ? "active" : "pointer-cursor";
    },
    tooltipTitles: function (type, page, current) {
            switch (type) {
            case "first":
                return "Go to First Page";
            case "prev":
                return "Go to Previous Page";
            case "next":
                return "Go to Next Page";
            case "last":
                return "Go to Last Page";
            case "page":
                return "Go to page " + page;
            }
        }
}
// pagiation library
$('#paginationBottom').bootstrapPaginator(options);

// sorty
$('.sortByButton').on('click', function(){

    var sortField = $(this).attr('fieldname');
    var sortOrder = $(this).attr('method');

    document.location.href = '/manage/<?php echo $this->recordType ?>/p:1/pp:<?php echo $this->perPage; ?>/sby:'+ sortField +':'+ sortOrder;

});

// check all record
$('#checkAllRecords').on('click', function(){

    var checkArray = $('#dataTable input[type="checkbox"]');

    if(checkArray.is(':checked')){
        checkArray.prop('checked', false);
    }else{
        checkArray.prop('checked', true);
    }

});

// change active inactive
$('.changeStatus').on('click', function(){

    var currentId = $(this).attr('record_id');
    var currentStatus = $(this).attr('status');
    var currentItem = $(this);

    // active or not
    if(currentStatus == 'active'){
      var method = 'inactive';
      currentItem.removeClass('label-success').addClass('label-danger');

    }else{
      var method = 'active';
      currentItem.removeClass('label-danger').addClass('label-success');
    }
      
    $.post('/action', { type: 'status', method: method, table: '<?php echo $this->recordType; ?>', records: currentId});

    currentItem.attr('status', method);
    currentItem.attr('id', method+'_' + currentId); 
    currentItem.text(method);

});

// delete record
$('.deleteRecord').on('click', function(){

    var records = $(this).attr('data-id');

        bootbox.confirm({
        title: 'Confrm',
        message: 'Are you sure you want to delete this. There is no undo!',
        buttons: {
            'cancel': {
                label: 'No, It\'s a mistake',
                className: 'btn-success pull-right'
            },
            'confirm': {
                label: 'Yes, Just do it',
                className: 'btn-danger pull-right'
            }
        },
        callback: function(result) {

            if (result) {
                 
                $.post('/action', { type: 'delete' , table: '<?php echo $this->recordType; ?>', records: records}, function(data){

                   document.location.href = '/manage/<?php echo $this->recordType;?>/p:1/pp:<?php echo $this->perPage.'/sby:'. $this->sortField.':'.$this->sortOrder ;?>';

                });

              }
            }
        });

});

// recordsPerPage
$('#showPerPage').change(function(){
    var noItems = $(this).val();
    document.location.href = '/manage/<?php echo $this->recordType.'/';?>/p:1/pp:' + noItems + '/sby:<?php echo $this->sortField.':'.$this->sortOrder ;?>';
});

// delete multiple records
$('#deleteselectedrecords').on('click', function(){

    var checkArray = $('#dataTable input[type="checkbox"]');
    var recordArray = [];

    $.each(checkArray, function(){

        var current = $(this);

        if(!current.is(':checked')) return;

        recordArray.push(current.attr('id'));
    });

    if(!recordArray.length  > 0) return;

    var records = recordArray.join(',');

    bootbox.confirm({
    title: 'Confrm',
    message: 'Are you sure you want to delete these. There is no undo!',
    buttons: {
        'cancel': {
            label: 'No, It\'s a mistake',
            className: 'btn-success pull-right'
        },
        'confirm': {
            label: 'Yes, Just do it',
            className: 'btn-danger pull-right'
        }
    },
    callback: function(result) {
        if (result) {
             
           $.post('/action', { type: 'delete' , table: '<?php echo $this->recordType; ?>', records: records}, function(data){

                document.location.href = '/manage/<?php echo $this->recordType;?>/p:1/pp:<?php echo $this->perPage.'/sby:'. $this->sortField.':'.$this->sortOrder ;?>';

            });

          }
        }
    });

});


});
</script>