<?php
defined('_JEXEC') or die('Restricted access');
/**
* @package OS CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Vladislav Prikhodko (vlados.vp1@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/
use OrdaSoft\os_lib\os_libMain;
use OrdaSoft\os_lib\os_libPagination;

// if( !class_exists("os_libMain") ){
//     try{
//         $ss = new os_libMain();
//     }catch( Exception $e ){
//         die("Please reinstall OrdaSoft Joomla CCK Package!");
//     }
// }
class AdminCoupons{
    public static function showCoupons($option){
        global $db, $app, $jConf;
        $db = new os_cckDb();
        if(!JFactory::getUser()->authorise('access_to_coupons', 'com_os_cck')){
            $app->enqueueMessage("Access denied", 'error');
            return;
        }
        // SORTING parameters start
        $session = JFactory::getSession();

        $item_sort_param = mosGetParam($_GET, 'sort', 'coup.coup_id');
        
        if (is_array($sort_arr = $session->get('eq_itemsort', ''))) {
          if(protectInjectionWithoutQuote('sorting_direction','')){
            if(protectInjectionWithoutQuote('sorting_direction')=="ASC"){
              $sort_arr['sorting_direction'] = "DESC";
            }else{
              $sort_arr['sorting_direction'] = "ASC";
            }
          }elseif($session->get('sorting_direction','')){ 
            $sort_arr['sorting_direction'] = $session->get('sorting_direction');
          }else{
            $sort_arr['sorting_direction']="ASC";
          }
          if ($item_sort_param == $sort_arr['field']) {
          } else {
            $sort_arr['field'] = $item_sort_param;
          }

          if($item_sort_param == 'coup_id'){
            $sort_string = 'coup.coup_id' . " " . $sort_arr['sorting_direction'];
          }else if($item_sort_param == "coup.coup_id"){
            $sort_string = $item_sort_param . " " . $sort_arr['sorting_direction'];
          }
          
          if($item_sort_param == 'coupon_name'){
            $sort_string = 'coup.name'. " " . $sort_arr['sorting_direction'];
          }else if($item_sort_param == "coup.name"){
            $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
          }
          
          if($item_sort_param == 'coupon_date_start'){
            $sort_string = 'coup.date_start'. " " . $sort_arr['sorting_direction'];
          }else if($item_sort_param == "coup.date_start"){
            $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
          }
          
          if($item_sort_param == 'coupon_date_finish'){
            $sort_string = 'coup.date_finish'. " " . $sort_arr['sorting_direction'];
          }else if($item_sort_param == "coup.date_finish"){
            $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
          }
        } else { 
          $sort_arr = array();
          if(protectInjectionWithoutQuote('sorting_direction','')){
            $sort_arr['sorting_direction'] = protectInjectionWithoutQuote('sorting_direction');
          }elseif($session->get('sorting_direction','')){ 
            $sort_arr['sorting_direction'] = $session->get('sorting_direction');
          }else{
            $sort_arr['sorting_direction']="ASC";
          }

          if($item_sort_param == 'coup_id'. " " . $sort_arr['sorting_direction']){
            $sort_string = 'coup.coup_id'. " " . $sort_arr['sorting_direction'];
          }else if($item_sort_param == "coup.coup_id"){
            $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
          }
          
          if($item_sort_param == 'coupon_name'){
            $sort_string = 'coup.name'. " " . $sort_arr['sorting_direction'];
          }else if($item_sort_param == "coup.name"){
            $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
          }
          
          if($item_sort_param == 'coupon_date_start'){
            $sort_string = 'coup.date_start'. " " . $sort_arr['sorting_direction'];
          }else if($item_sort_param == "coup.date_start"){
            $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
          }
          
          if($item_sort_param == 'coupon_date_finish'){
            $sort_string = 'coup.date_finish'. " " . $sort_arr['sorting_direction'];
          }else if($item_sort_param == "coup.date_finish"){
            $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
          }
          $sort_arr['field'] = $item_sort_param;
        }

        $session->set('eq_itemsort', $sort_arr);

        //maybe it is search below
        $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
        $limitstart = $app->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
        //$catid = $app->getUserStateFromRequest("catid{$option}", 'catid', '');
        $pub = $app->getUserStateFromRequest("pub{$option}", 'pub', '');
        //$approved = $app->getUserStateFromRequest("appr{$option}", 'appr', '');
        $userid = $app->getUserStateFromRequest("userid{$option}", 'userid', '');
        $search = trim($app->getUserStateFromRequest("search{$option}", 'search', ''));
        $entity_id = $app->getUserStateFromRequest("entity_id{$option}", 'entity_id', '');
        $entities = array();
        $entities[] = array('value' => '', 'text' => cck_lang_text('COM_OS_CCK_OPTION_ALL_ENTITIES'));
        // $query = "SELECT ent.eid AS value, ent.name AS text FROM #__os_cck_entity as ent"
        //           ."\n LEFT JOIN #__os_cck_layout as lay ON lay.fk_eid = ent.eid WHERE lay.type = 'add_instance' GROUP BY ent.eid";
        $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity ORDER BY name ";
        $db->setQuery($query);
        $ent = $db->loadObjectList("value");


        $entities_array = $ent;

        if( count($ent) > 1 ){
          $entities = array_merge($entities, (array)$ent) ;
        } else{
          //$entities = $entities;
          //set $entity_id == "" - when we haven 1 entity, and yet one - old was war selected we removed, 
          //for clear old values from $entity_list filter and from $where array
          $entity_id = "";
        }

        $entity_list = JHTML::_('select.genericlist',$entities, 'entity_id', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);

        $where = $where2 = array();
        $catwhere = "";
        if ($entity_id != '' && isset($ent[$entity_id])) {
            array_push($where, "coup.entities LIKE '%,{$entity_id},%'");
        }

        if ($pub == "pub") {
          array_push($where, "coup.published = 1");
        } else if ($pub == "not_pub") {
          array_push($where, "coup.published = 0");
        }

        // if($userid != 0 && $userid != ''){
        //   array_push($where, "coup.user_ids LIKE '%," . $userid.",%'");
        // }

        //pagination?*
        $selectstring = "SELECT count(DISTINCT coup.coup_id) " .
          "\n FROM #__os_cck_coupons AS coup " ;
          

        if($search){
          array_push($where2, "coup.name LIKE '%$search%' ");
        }

        $selectstring .=  (count($where) ? "\n WHERE " . implode(' AND ', $where) : "");

        if($search){
          $conditions_connect = count($where) ? 'AND' : 'WHERE';
          $selectstring .=  (count($where2) ? "\n".$conditions_connect." (" . implode(' OR ', $where2).')' : "");
        }
        $db->setQuery($selectstring);

        try {
            $total = $db->loadResult();
        } catch (RuntimeException $e) {
            echo $e->getMessage();
        }
        
        $limit = intval($limit);
        $language = JFactory::getApplication()->getLanguage();
        $language->load('os_lib',JPATH_ROOT);
        $pageNav = new os_libPagination($total, $limitstart, $limit);

        $selectstring = "SELECT coup.* " .
          "\nFROM #__os_cck_coupons AS coup" ;
          
          if($search){
            array_push($where2, "coup.name LIKE '%$search%' ");
          }

        $selectstring .= (count($where) ? "\n WHERE " . implode(' AND ', $where) : "");

        if($search){
          $conditions_connect = count($where) ? 'AND' : 'WHERE';
          $selectstring .=  (count($where2) ? "\n".$conditions_connect." (" . implode(' OR ', $where2).')' : "");
        }
        $selectstring .= " ORDER BY $sort_string " .
          "\n LIMIT $pageNav->limitstart,$pageNav->limit;";
  
        $db->setQuery($selectstring);
        try {
            $rows = $db->loadObjectList();
        } catch (RuntimeException $e) {
            echo $e->getMessage();
            return false;
        }
        
        $pubmenu[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_TO_PUBLIC'),'value','text');
        $pubmenu[] = JHTML::_('select.option','not_pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_NOT_PUBLIC'),'value','text');
        $pubmenu[] = JHTML::_('select.option','pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_PUBLIC'),'value','text');
        $publist = JHTML::_('select.genericlist',$pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);


        
        AdminViewCoupons::showCoupons($option, $rows, $publist, $search, $pageNav, $sort_arr, $entity_list, $userslist, $entities_array);
    }
    
    static function publishCoupons($eiids, $publish, $option){

        global $db, $user,$app, $os_cck_state;
        $db = new os_cckDb();
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }

        $catid = mosGetParam($_POST, 'catid', array(0));
        if (!is_array($eiids) || count($eiids) < 1) {
          $action = $publish ? 'publish' : 'unpublish';
          echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
          exit;
        }
        $eiids = implode(',', $eiids);
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        $db->setQuery("UPDATE #__os_cck_coupons SET published='$publish'"
                        . "\n WHERE coup_id IN ($eiids) ");
        try {
            $db->execute();
        } catch (RuntimeException $e) {
            echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
            exit ();
        }
        
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        // if (count($eiids) == 1) { - $eiids already not array  
        //   $instance = new os_cckEntityInstance($db->_db);
        //   $instance->checkin($eiids[0]);
        // }
        $app->redirect("index.php?option=$option&task=coupons");
    }
    
    static function editCoupon($option){
        global $db, $input, $app, $os_cck_state;
        $db = new os_cckDb();
        require JPATH_ADMINISTRATOR . '/components/com_os_cck/elements/getUserModal.php';
        if (version_compare(JVERSION, "4.0.0-alpha10", "lt")) {

        } else {
          $input = JFactory::getApplication()->input;
          $input->set('hidemainmenu', true);
        }
        JHtml::_('jquery.framework');
//        var_dump($db->getNullDate());
        $coupon = new os_cckCoupons($db->_db);
        
        $coup_id = $input->get('coup_id', array(), 'ARRAY');
        
        //var_dump($coup_id); exit;
        if(!empty($coup_id)){
            $coupon->load($coup_id[0]);
        }
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        //var_dump($coupon);
        $coupon_type_opt = array();
        $coupon_type_opt[] = JHTML::_('select.option', 'percent', '%','value','text');
        $coupon_type_opt[] = JHTML::_('select.option', 'value', 'Value','value','text');
        
        $coupon_type_input = JHTML::_('select.genericlist',$coupon_type_opt, 'type', 'class="inputbox" size="1"', 'value', 'text', $coupon->type);
        $coupon->_coupon_type_input = $coupon_type_input;
        
        $query = "SELECT eid, name FROM #__os_cck_entity WHERE published=1";
        $db->setQuery($query);
        $enteties = $db->loadObjectList();
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        $entities_opt = array();
        $entities_opt[] = JHTML::_('select.option', '-1', cck_lang_text('COM_OS_CCK_LABEL_ALL_ENTETIES'), 'value','text');
        foreach($enteties as $entity){
            $entities_opt[] = JHTML::_('select.option', $entity->eid,$entity->name, 'value','text');
        }
        if($coupon->entities){
            $entities_val = explode(',', $coupon->entities);
        }else{
            $entities_val = array();
        }
        $entities_input = JHTML::_('select.genericlist',$entities_opt, 'entities[]', 'class="inputbox" multiple="true, "size="3"', 'value', 'text', $entities_val);
        $coupon->_entities_input = $entities_input;
        
        $gtree = get_group_children_tree_cck();
        if($coupon->user_group_ids){
            $user_groups_val = explode(',',$coupon->user_group_ids);
        }else{
            $user_groups_val = array();
        }
        
        $attr = array (
            'list.attr' => ' multiple="true" ',
            'id' => "user_group_ids",
            'list.select' => $user_groups_val,
            'group.items' => null,
            'option.key.toHtml' => false,
            'option.text.toHtml' => false
        );
        //$coupon->_coupon_user_groups_input = JHTML::_('select.genericlist', $gtree, 'user_group_ids[]', 'multiple="multiple"','value', 'text',$user_groups_val);
        $coupon->_coupon_user_groups_input = JHTML::_('select.groupedlist',$gtree,"user_group_ids[]", $attr);
        
        
        $categories_list = CCK_CAT_Utils::categoryArray('com_os_cck',0);
        $coupon_categories_opt = array();
        $coupon_categories_opt[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_PLEASE_SELECT_OPTION'));
        
        foreach ($categories_list as $item) {
            $coupon_categories_opt[] = JHTML::_('select.option',$item->cid, $item->name);
        }
        if($coupon->category_ids){
            $categories_val = explode(',',$coupon->category_ids);
        }else{
            $categories_val = array();
        }
        $coupon_categories = JHTML::_('select.genericlist',$coupon_categories_opt, 'category_ids[]', 'multiple="multiple"','value', 'text', $categories_val);
        $coupon->_coupon_categories = $coupon_categories;
        
        $coupon_publish_opt = array();
        $coupon_publish_opt[] = JHTML::_('select.option', '1', 'Publish','value','text');
        $coupon_publish_opt[] = JHTML::_('select.option', '0', 'Unpublish','value','text');
        $coupon->_coupon_publish_input = JHTML::_('select.genericlist', $coupon_publish_opt, 'published', '','value', 'text',$coupon->publish);
        AdminViewCoupons::editCoupon($coupon);
    }
    
    static function saveCoupon($option){
        global $db, $input, $app, $os_cck_state;
        $db = new os_cckDb();
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
        $coupon = new os_cckCoupons($db->_db);
        
        $data = $_POST;
        $data = protectInjectionWithoutQuote($data, '', 'STRING', true);
        
        if($input->get('coup_id', '', 'INT') != ''){
            $coupon->load($input->get('coup_id', '', 'INT'));
        }else{
            $coupon->creation_date = date('Y-m-d');
        }
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        $entities = $input->get('entities', array(), 'ARRAY');
        if(!empty($entities)){
            $data['entities'] = ','.implode(',',$entities).',';
        }else{
            $data['entities'] = ',-1,';
        }

        $max_uses = $input->get('max_uses', -1, 'INT');
        $data['max_uses'] = $max_uses;

        $date_start = $input->get('date_start', '', 'STRING');
        if($date_start == ''){
          $data['date_start'] = get_curent_site_time();
        }

        $date_finish = $input->get('date_start', '', 'STRING');
        if($date_finish == ''){
          $data['date_finish'] = get_curent_site_time('+5 Year');
        }
        
        $user_group_ids = $input->get('user_group_ids', array(), 'ARRAY');
        if(!empty($user_group_ids)){
            $data['user_group_ids'] = ','.implode(',',$user_group_ids).',';
        }else{
            $data['user_group_ids'] = '1';
        }
        
        $category_ids = $input->get('category_ids', array(), 'ARRAY');
        if(!empty($category_ids)){
            $data['category_ids'] = ','.implode(',',$category_ids).',';
        }
        
        if($coupon->used_number == null){
            $coupon->used_number = 0;
        }
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }

        try {
          if(!$coupon->bind($data)){
              echo "<script>alert('Coupon with this name alredy exist'); window.history.go(-1);</script>/n";
              exit ();            
          }
          
          if($coupon->category_ids == null){
              $coupon->category_ids = '';
          }

          if($coupon->user_group_ids == null){
              $coupon->user_group_ids = '';
          }

          if(!$coupon->check()){
              echo "<script>alert('".addslashes( $coupon->getError() )."'); window.history.go(-1);</script>\n";
              exit ();            
          }

          if(!$coupon->store()){
              echo "<script>alert('".addslashes( $coupon->getError() ) ."'); window.history.go(-1);</script>\n";
              exit ();            
          }
        } catch (RuntimeException $e) {
            echo "<script> alert('" . addslashes( $e->getMessage() ) . "'); window.history.go(-1); </script>\n";
            exit ();            
        }
        
        $app->redirect("index.php?option={$option}&task=coupons");
        
        
        //var_dump($coupon); exit;
    }
    
    static function removeCoupon($option){
        global $db, $input, $app;
        $db = new os_cckDb();
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
        $coup_ids = $input->get('coup_id', array(), 'ARRAY');
        
        $coupon = new os_cckCoupons($db->_db);
        
        if(!empty($coup_ids)){
            foreach ($coup_ids as $coup_id){
                $coupon->delete($coup_id);
            }
        }
        
        $app->redirect("index.php?option={$option}&task=coupons");
    }
}
