<?php 
defined('_JEXEC') or die('Restricted access');
class JFormFieldlikemelist extends JFormField {
  protected $type = 'likemelist';
  function getInput() {
    $db = JFactory::getDbo();
    $app = JFactory::getApplication();
    $pid = JRequest::getVar('extension_id');
    $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'), 'uint');
    $sort = $app->input->get('sort', 'ASC');
    $limitstart = $app->input->get('limitstart', 0, 'uint');
    
    $sort_dir = JRoute::_('index.php?option=com_plugins&view=plugin&layout=edit&extension_id='.$pid.'&limitstart='.$limitstart.'&sort='.($sort=='ASC'?'DESC':'ASC'));
    
    $list = '<div>';
    $document = JFactory::getDocument();
    //JHtml::_('jquery.framework');
    $document->addScriptDeclaration("jQuery(function(){
      document.getElementById('style-form').id='adminForm';
      jQuery('#sort_votes').click(function(){
        window.location = '$sort_dir'.replace(/&amp;/g, '&');
      });
      jQuery('button.reset-vote').click(function(e){
        e.preventDefault();
        var b = jQuery(this);
        jQuery.post(b.attr('data-url'), {action: 'resetvote', voteid: b.attr('data-voteid')}, function(res){
          if (!res) return;
          var m = res.substr(res.length - 2, 2);
          if (m == 'ER') return;
          b.parent().parent().remove();
        });
        return false;
      });
    });");
    
    if (count($_POST) && isset($_POST['action']) && isset($_POST['voteid'])) {
      ob_clean();
      $query = $db->getQuery(true)->select('iid')->from($db->quoteName('#__likeme'))->where($db->quoteName('id').'='.$db->quote($_POST['voteid']));
      $db->setQuery($query);
      $found = $db->loadResult();
      if (!$found) {
        echo 'ER';
        jexit(0);
      }
      $query = $db->getQuery(true)->delete($db->quoteName('#__likeme_votes'));
      $query->where($db->quoteName('iid').'='.$db->quote($found));
      $db->setQuery($query);
      $db->execute();
      $query = $db->getQuery(true)->delete($db->quoteName('#__likeme'));
      $query->where($db->quoteName('iid').'='.$db->quote($found));
      $db->setQuery($query);
      $db->execute();
      echo 'OK';
      jexit(0);
    }
    
    $query = $db->getQuery(true)
      ->select('a.*')
      ->from($db->quoteName('#__likeme', 'a'))
      ->leftJoin($db->quoteName('#__likeme_votes', 'b') . ' ON (' . $db->quoteName('a.iid') . ' = ' . $db->quoteName('b.iid') . ')')
      ->order('a.likes '. $sort);
    $db->setQuery($query, $limitstart, $limit);
    $results = $db->loadObjectList();
    if(!empty($results)) {
      $db->setQuery('SELECT FOUND_ROWS();');
      jimport('joomla.html.pagination');
      jimport('joomla.libraries.cms.pagination');
      $pager = new JPagination($db->loadResult(), $limitstart, $limit, '', $app);
      $links = $pager->getListFooter();
      $links = preg_replace_callback('/(href="#"\sonclick="document\.adminForm\.limitstart\.value=(\d+);\sJoomla.submitform\(\);return\sfalse;")/', function($m) use ($pid) {
        return 'href="'.JRoute::_('index.php?option=com_plugins&view=plugin&layout=edit&extension_id='.$pid.'&limitstart=').$m[2].'"';
      }, $links);
      $list .= $links;
      $list .= '<div class="row-fluid"><div class="span2">Preview</div><div class="span6">Likes <i id="sort_votes">Ascending</i></div><div class="span4">Reset</div></div>';
      foreach($results as $v) {
        $list .= '<div class="row-fluid" style="margin-bottom:20px;">';
        if (preg_match('/\.(png|gif|jpg|jpg)/', $v->iid)) {
          $list .= '<div class="span2"><img src="'.$v->iid.'" /></div>';
        } else {
          $list .= '<div class="span2">'.$v->iid.'</div>';
        }
        $list .= '<div class="span6">'.$v->likes.'</div>';
        $list .= '<div class="span4"><button class="reset-vote modal btn" data-voteid="'.$v->id.'" data-url="'.JRoute::_('index.php?option=com_plugins&view=plugin&layout=edit&extension_id='.$pid).'">Reset Likes to 0</button></div>';
        $list .= '</div>';
      }
      $list .= $links;
    } else {
      
    }
    $list .= '</div>';
    return $list;
  }
}
