<?php
defined('_JEXEC') or die('Restricted access');

/**
* @package OS CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@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 AdminInstance{
  static function showInstances($option, $avaibleUpdate = false){
    global $db, $app, $jConf, $entities_type, $doc;

//    $language = JFactory::getApplication()->getLanguage();
//    $language->load('os_lib',JPATH_ROOT);
    $db = new os_cckDb();
    
      if(!JFactory::getUser()->authorise('access_to_instancies', 'com_os_cck')){
          $app->enqueueMessage("Access denied", 'error');
          return;
      }
  
                    
    $instance = new os_cckEntityInstance($db->_db);
    $vars = $instance->getInstanceManager($option, $avaibleUpdate);

   
    
  //   if(false){
  //     $user_checked_out_categories = " UPDATE #__os_cck_entity_instance SET checked_out=0, checked_out_time='0000-00-00 00:00:00'
  //     WHERE checked_out_time > 0 AND ( TIME_TO_SEC('" . date('Y-m-d H:i:s') . "') - TIME_TO_SEC(checked_out_time) ) >= 7200;";
  //     $db->setQuery($user_checked_out_categories);
  //     $db->execute();
  //     // $doc->addScript(JURI::root()."components/com_os_cck/assets/bootstrap/js/bootstrapCCK.js");
  //     JHtml::_('bootstrap.modal');
  //     $session = JFactory::getSession();
      
  //     if($avaibleUpdate){
  //         $message = cck_lang_text('COM_OS_CCK_NEW_VERSION_AVALIABLE');
  //         $app->enqueueMessage($message);
  //     }

  //     // $session = JFactory::getSession();
  //     // $session->destroy();
      
  //     // SORTING parameters start
  //     $session = JFactory::getSession();
      
  //     $sort_string = '';
      
  //     $item_sort_param = mosGetParam($_GET, 'sort', 'jei.eiid');
      
  //     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']="DESC";
  //       }

  //       if(protectInjectionWithoutQuote('sort','')){
  //           $sort_arr['field'] = protectInjectionWithoutQuote('sort','');
  //           $item_sort_param = protectInjectionWithoutQuote('sort','');
  //       }elseif(isset($sort_arr['field']) && $sort_arr['field'] != ''){
          
  //           if(stripos($sort_arr['field'], 'category') === false && $sort_arr['field'] != 'c.title' && $sort_arr['field'] != 'cc.title'){
              
  //             $item_sort_param = $sort_arr['field'];
  //           }else{
  //             $sort_arr['field'] = $item_sort_param = 'cc.title';
  //           }
  //           //$sort_arr['field'] = $session->get('field','');
            
  //       }else{
  //           $sort_arr['field'] = $item_sort_param ='jei.eiid';
  //       }
        
  // //      if ($item_sort_param == $sort_arr['field']) {
  // //          
  // //      }
  // //      if ($item_sort_param == $sort_arr['field']) {
  // //      } else {
  // //        $sort_arr['field'] = $item_sort_param;
  // //      }

  //       if($item_sort_param == 'inst_entity'){
  //         $sort_string = ', jei.fk_eid' . " " . $sort_arr['sorting_direction'];
  //       }elseif($item_sort_param == 'inst_id'){
  //         $sort_string = ', jei.eiid' . " " . $sort_arr['sorting_direction'];
  //       }elseif($item_sort_param == "jei.eiid"){
  //         $sort_string = ', ' . $item_sort_param . " " . $sort_arr['sorting_direction'];
  //       }elseif($item_sort_param == "cc.title"){
  //         $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'] = protectInjectionWithoutQuote('sorting_direction');
  //       }else{
  //         $sort_arr['sorting_direction']="DESC";
  //       }

  //       if($item_sort_param == 'inst_entity'){
  //         $sort_string = ', jei.fk_eid'. " " . $sort_arr['sorting_direction'];
  //       }elseif($item_sort_param == 'inst_id'. " " . $sort_arr['sorting_direction']){
  //         $sort_string = ', jei.eiid'. " " . $sort_arr['sorting_direction'];
  //       }elseif($item_sort_param == "jei.eiid"){
  //         $sort_string = ', ' . $item_sort_param. " " . $sort_arr['sorting_direction'];
  //       }elseif($item_sort_param == "cc.title"){
  //         $sort_string = ', ' . $item_sort_param . " " . $sort_arr['sorting_direction'];
  //       }
  //       $sort_arr['field'] = $item_sort_param;
  //     }
  //     // var_dump($sort_arr);
  //     $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', ''));
  //     //var_dump($search);
  //     $entity_id = $app->getUserStateFromRequest("entity_id{$option}", 'entity_id', '');
  //     $lang = $app->getUserStateFromRequest("language{$option}", 'language', '*');
  // //    var_dump($lang);
  //     $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 = (count($ent) > 1) ? array_merge($entities, (array)$ent) : $entities;
  //     $entity_list = os_libHtmlInputs::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, "jei.fk_eid ='{$entity_id}'");
  //     }

  //     if ($approved == "appr") {
  //       array_push($where, "jei.approved = 1");
  //     } else if ($approved == "not_appr") {
  //       array_push($where, "jei.approved = 0");
  //     }

  //     if ($pub == "pub") {
  //       array_push($where, "jei.published = 1");
  //     } else if ($pub == "not_pub") {
  //       array_push($where, "jei.published = 0");
  //     }
      
  //     if($userid != 0 && $userid != ''){
  //       array_push($where, "jei.fk_userid = " . $userid);
  //     }

  //     if ($catid > 0) {
  //       array_push($where, "c.fk_cid='$catid'");
  //     }
      
  //     if ($lang != '*') {
  //       array_push($where, "jei.language='$lang'");
  //     }

  //     array_push($where, "cl.type = 'add_instance'");

  //     //pagination?*
  //     $selectstring = "SELECT count(DISTINCT jei.eiid) " .
  //       "\nFROM #__os_cck_entity_instance AS jei" .
  //       "\nLEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
  //       "\nLEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
  //       "\nLEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ";

  //     if($search || $sort_arr['field']){
  //         $select_enteties = "SELECT eid FROM #__os_cck_entity";
  //         $db->setQuery($select_enteties);
  //         $entityEaaray = $db->loadColumn();
  // //        var_dump($entityEaaray);
  //         foreach(array_unique($entityEaaray) as $key => $value){
  //             if($entities_type[$value] == 'joomla_user') continue;
              
  //             $entity = new os_cckEntity($db->_db);
  //             $entity->load($value);

  //             $extra_fields_list = $entity->getFieldList();
              
  //             if(empty($extra_fields_list)) continue;
  //             foreach($extra_fields_list as $Fieldvalue){
  //               if($Fieldvalue->show_in_instance_menu){
  //                 $fieldNames[$value]['ent_name'] = $entity->eid;
  //                 $fieldNames[$value]['field_type'] = $Fieldvalue->field_type;
  //                 $fieldNames[$value]['fields'][] = $Fieldvalue->db_field_name;//need for use in search // [][table_name][column_mname]
  //               }
  //             }
  //           }
  //         //  var_dump($fieldNames);
  // //      $fieldNames = $session->get('field_names');
  // //      $tempfieldNames = $fieldNames;
  //       if(!empty($fieldNames)){
  //           $i = 0;
  //           foreach ($fieldNames as $value){
  //             if($i > 50) continue;
  //             foreach ($value['fields'] as $name) {
  //               if($value['field_type'] == 'categoryfield' && $name == $sort_arr['field']){
  //                 $sort_string = ', cc.title'. " " . $sort_arr['sorting_direction'];
  //                 continue;
  //               }
  //               array_push($where2, '#__os_cck_content_entity_'.$value['ent_name'].'.'.$name." LIKE '%$search%' ");
  //             }
              
  //             $selectstring .= "\nLEFT JOIN #__os_cck_content_entity_".$value['ent_name']." ON #__os_cck_content_entity_".$value['ent_name'].".fk_eiid = jei.eiid ";
  //             $i++;
  //           }
  //       }else{
  //           $sort_string = '';
  //       }
  //       array_push($where2, "jei.eiid LIKE '%$search%' ");
  //     }
      
  //     $selectstring .=  "\nLEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
  //       "\nLEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
  //       "\nLEFT JOIN #__users AS u ON u.id = jei.checked_out " .
  //       (count($where) ? "\nWHERE " . 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();
  //     }

  //     //echo $db->getErrorMsg();
  //     $limit = intval($limit);
      
  //     // $pageNav = new JPagination($total, $limitstart, $limit);
  //     $pageNav = new os_libPagination($total, $limitstart, $limit);

  //     $selectstring = "SELECT jei.*, cl.title as lay_title, cl.type as lay_type, cl.params as lay_params, GROUP_CONCAT(DISTINCT cc.title SEPARATOR ', ') AS category, ce.name AS entity, " .
  //       "\nl.id as rentid, l.rent_from as rent_from, l.rent_return as rent_return,l.rent_until as rent_until,u.name AS editor, jei.language as lang " .
  //       "\nFROM #__os_cck_entity_instance AS jei" .
  //       "\nLEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
  //       "\nLEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
  //       "\nLEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ";

  //       if($search || $sort_arr['field']){
  //         // $fieldNames 
  //         // if($sort_arr['field']){

  //         // }
  //         // $fieldNames = $session->get('field_names');
          
  //         if(!empty($fieldNames)){
  //             $i = 0;  
  //             foreach ($fieldNames as $value) {
  //               $i++;
  //               if($i > 50) continue;
  //               // var_dump($i);
  //               foreach ($value['fields'] as $name) {
                  
  //                 if($value['field_type'] == 'categoryfield' && $name == $sort_arr['field']){
  //                   $sort_string = ', cc.title'. " " . $sort_arr['sorting_direction'];
  //                   continue;
  //                 }
  //                 // var_dump(!isset($sort_string));
  //                 if((!isset($sort_string) || $sort_string == '') && (isset($item_sort_param) && !empty($item_sort_param))){
                    
  //                   if($item_sort_param == $name){
  //                     $sort_string = ', #__os_cck_content_entity_'.$value['ent_name'].'.'.$name." ".$sort_arr['sorting_direction'];
  //                   }
  //                 }
  //                 array_push($where2, '#__os_cck_content_entity_'.$value['ent_name'].'.'.$name." LIKE '%$search%' ");
  //               }
  //               $selectstring .= "\nLEFT JOIN #__os_cck_content_entity_".$value['ent_name']." ON #__os_cck_content_entity_".$value['ent_name'].".fk_eiid = jei.eiid ";
                
  //             }
  //         }else{
  //             $sort_string = '';
  //         }
  //         array_push($where2, "jei.eiid LIKE '%$search%' ");
  //       }

  //     $selectstring .= "\nLEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
  //       "\nLEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
  //       "\nLEFT JOIN #__users AS u ON u.id = jei.checked_out " .
  //       (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");

  //     if($search){
  //       $conditions_connect = count($where) ? 'AND' : 'WHERE';
  //       $selectstring .=  (count($where2) ? "\n".$conditions_connect." (" . implode(' OR ', $where2).')' : "");
  //     }
  //     // var_dump($sort_string);
  //     $selectstring .= "\n GROUP BY jei.eiid " .
  //       "\nORDER BY jei.notreaded desc $sort_string " .
  //       "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
  // // echo $selectstring; exit;
  // //        echo '111111111111111111<br>';
  //       //  var_dump($sort_arr);
  // //        echo '<br>111111111111111111<br>';

  //     $db->setQuery($selectstring);
  //     // echo '111111111111';
  //     try {
  //         $rows = $db->loadObjectList();
  //     }catch(RuntimeException $e) {
  //       echo $selectstring;
  //         echo $e->getMessage();
  //         return false;
  //     }
      
  // // var_dump($rows);
  //     // echo "<pre>";
  //     // print_r($selectstring);
  //     // echo "<pre>";
  //     // exit;

  // //    if ($db->getErrorNum()) {
  // //      echo $db->stderr();
  // //      return false;
  // //    }


  //     $show_fields = $fieldNames = $entityEaaray = array();
  //     if(count($rows)>0){
  //       $date = strtotime(JFactory::getDate()->toSql());
  //       foreach ($rows as $row) {
  //         $check = strtotime($row->checked_out_time);
  //         $remain = 7200 - ($date - $check);
  //         if (($remain <= 0) && ($row->checked_out != 0)) {
  //             $db->setQuery("UPDATE #__os_cck_entity_instance SET checked_out=0,checked_out_time=0");
  //             $db->execute();
  //             $row->checked_out = 0;
  //             $row->checked_out_time = 0;
  //         }
  //         if($row->lay_type != ''){  
  //           $lay_params = unserialize($row->lay_params);
  //           $entityEaaray[] = $row->fk_eid;
  //           $layoutArray[] = $row->fk_lid;
  //         }


  //       }
  //       foreach(array_unique($entityEaaray) as $key => $value){
  //         $entity = new os_cckEntity($db->_db);
  //         $entity->load($value);
  //         $layout = new os_cckLayout($db->_db);
  //         $layout->load($layoutArray[$key]);
  //         $bootstrap_version = $session->get( 'bootstrap','2');
  //         $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
  //         $layout_params = unserialize($layout->params);
  //         $extra_fields_list = $entity->getFieldList();
  //         foreach($extra_fields_list as $Fieldvalue){
  //           if($Fieldvalue->show_in_instance_menu && strpos($layout_html,"{|f-".$Fieldvalue->fid."|}")){
  //             $fieldNames[$key]['ent_name'] = $entity->eid;
  //             $fieldNames[$key]['field_type'] = $Fieldvalue->field_type;
  //             $fieldNames[$key]['fields'][] = $Fieldvalue->db_field_name;//need for use in search // [][table_name][column_mname]
  //             $show_fields[$value][]= $Fieldvalue;
  //           }
  //         }
  //       }
  //       ksort($show_fields);

  //     }
      
  //     $categories[] = os_libHtmlInputs::option('-1', cck_lang_text('COM_OS_CCK_LABEL_SELECT_ALL_CATEGORIES'),'value','text');
  //     //************* begin add for sub category in select in manager houses  *************
  //     $options = $categories;
  //     $id = 0;
  //     $fromSearch=0;
  //     $list = CCK_CAT_Utils::categoryArray('com_os_cck',$fromSearch);
  //     $cat = new os_cckCategory($db->_db);
  //     $cat->load($id);

  //     $this_treename = '';
  //     foreach ($list as $item) {
  //       if ($this_treename) {
  //           if ($item->cid != $cat->cid && strpos($item->title, $this_treename) === false) {
  //               $options[] = os_libHtmlInputs::option($item->cid, $item->title,'value','text');
  //           }
  //       } else {
  //           if ($item->cid != $cat->cid) {
  //               $options[] = os_libHtmlInputs::option($item->cid, $item->title,'value','text');
  //           } else {
  //               $this_treename = "$item->title/";
  //           }
  //       }
  //     }

  //     // print_r($list);exit;
  //     $clist = os_libHtmlInputs::genericlist($options, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid); //new nik edit
      
  //     if (version_compare(JVERSION, "3.7.0", "ge")) {
  //         $install_lang = JLanguageHelper::getKnownLanguages();
  //     }else{
  //         $install_lang = JLanguage::getKnownLanguages();
  //     }

  //     $lang_list = array();
  //     $lang_opt[] = os_libHtmlInputs::option('*',cck_lang_text('COM_OS_CCK_OPTION_ALL_LANGUAGES'));
  //     foreach($install_lang as $key => $item){
  //         $lang_opt[] = os_libHtmlInputs::option($key,$item['name']);
  //     }
  //     $lang_list = os_libHtmlInputs::genericlist($lang_opt, 'language', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $lang); //new nik edit
      
  //     $pubmenu[] = os_libHtmlInputs::option('0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_TO_PUBLIC'),'value','text');
  //     $pubmenu[] = os_libHtmlInputs::option('not_pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_NOT_PUBLIC'),'value','text');
  //     $pubmenu[] = os_libHtmlInputs::option('pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_PUBLIC'),'value','text');
  //     $publist = os_libHtmlInputs::genericlist($pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);

  //     $approvedmenu[] = os_libHtmlInputs::option('0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_TO_PUBLIC'),'value','text');
  //     $approvedmenu[] = os_libHtmlInputs::option('not_appr', cck_lang_text('COM_OS_CCK_LABEL_UNAPPROVED'),'value','text');
  //     $approvedmenu[] = os_libHtmlInputs::option('appr', cck_lang_text('COM_OS_CCK_LABEL_APPROVED'),'value','text');
  //     $approvedlist = os_libHtmlInputs::genericlist($approvedmenu, 'appr', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $approved);

  // //    SELECT DISTINCT fk_userid FROM shop_os_cck_entity_instance as ei INNER JOIN `shop_users` as us ON ei.fk_userid = us.id
  //     $select = "SELECT DISTINCT fk_userid FROM #__os_cck_entity_instance as ei "
  //             . " INNER JOIN `#__users` as us ON ei.fk_userid = us.id";
  //     $db->setQuery($select);
  //     $users = $db->loadObjectList();

  //     $userOpt = array();
  //     $userOpt[] = os_libHtmlInputs::option('', 'All Users','value','text');
  // //    var_dump($users);
  //     foreach ($users as $user => $value) {
  //         if($value->fk_userid == 0) $value->fk_userid = cck_lang_text("COM_OS_CCK_LABEL_ALL_OWNERS");
  //         $userOpt[] = os_libHtmlInputs::option($value->fk_userid, @JFactory::getUser($value->fk_userid)->name,'value','text');
  //     }

  //     $userslist = os_libHtmlInputs::genericlist($userOpt, 'userid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $userid);

  //   }





    AdminViewInstance::showInstances($option, $vars['rows'], $vars['clist'], $vars['publist'], $vars['search'], $vars['pageNav'], $vars['sort_arr'], $vars['show_fields'], $vars['entity_list'], $vars['approvedlist'], $vars['userslist'], $vars['lang_list']);
  }

  static function showInstancesModal($option){
    global $db, $app, $entities_type, $entityFieldLists;

    $db = new os_cckDb();
    $session = JFactory::getSession();
    // var_dump($_REQUEST);
    if($entities_type[$_REQUEST['fk_eid']] == 'os_cck_entity'){
        $where = array();
        array_push($where, "cl.type = 'add_instance'");
        array_push($where, "jei.published = 1");
        array_push($where, "jei.fk_eid = ".$_REQUEST['fk_eid']);

        $selectstring = "SELECT jei.*, cl.title as lay_title, cl.type as lay_type, cl.params as lay_params, cc.title AS category, ce.name AS entity" .
          "\n FROM #__os_cck_entity_instance AS jei" .
          "\n LEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
          "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid ".
          "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ".
          "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
          (count($where) ? "\n WHERE " . implode(' AND ', $where) : "");

        $selectstring .= "\n GROUP BY jei.eiid ORDER BY jei.eiid";


        //var_dump($selectstring); exit;
        $db->setQuery($selectstring);
        //$rows = $db->loadObjectList();
        try {
            $rows = $db->loadObjectList();
        }catch(RuntimeException $e) {
            echo $e->getMessage();
            return false;
        }
    }elseif($entities_type[$_REQUEST['fk_eid']] == 'custom_sql'){
        $entity = new os_cckEntity($db->_db);
        $entity->load($_REQUEST['fk_eid']);
//        var_dump($entity);
        $id_field = new stdClass();
        $title_field = new stdClass();
        foreach($entityFieldLists[$_REQUEST['fk_eid']] as $field){
            if($field->custom_field_type == 'id') $id_field = $field;
            if($field->custom_field_type == 'title') $title_field = $field;
        }
//        var_dump($id_field);
//        var_dump($title_field);
        
        $query = "SELECT t.$id_field->fid as eiid, t.$title_field->fid as title FROM ($entity->sql_select) as t";
//        var_dump($query); exit;
        $db->setQuery($query);
        $rows = $db->loadObjectList();
        
        foreach($rows as $row){
            $row->entity = $entity->name;
        }
        
    }
//    if ($db->getErrorNum()) {
//      echo $db->stderr();
//      return false;
//    }

    $show_fields = $entityEaaray = $layoutArray = $fieldNames = array();
    if($entities_type[$_REQUEST['fk_eid']] == 'os_cck_entity'){
        if(count($rows)>0){
          foreach ($rows as $row) {
            // $lay_params = unserialize($row->lay_params);
            $entityEaaray[] = $row->fk_eid;
            $layoutArray[] = $row->fk_lid;
          }


          $entityEaaray = array_unique($entityEaaray);
          $layoutArray = array_unique($layoutArray);
          foreach( $entityEaaray as $key => $value){
            foreach( $layoutArray as $key2 => $value2){
              $entity = new os_cckEntity($db->_db);
              $entity->load($value);
              $layout = new os_cckLayout($db->_db);
              $layout->load($layoutArray[$key2]);
              $bootstrap_version = $session->get( 'bootstrap','2');
              // $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
              // $layout_params = unserialize($layout->params);
              $extra_fields_list = $entity->getFieldList();
              foreach($extra_fields_list as $Fieldvalue){
                if($Fieldvalue->show_in_instance_menu){
                  // $fieldNames[$key]['ent_name'] = $entity->eid;
                  // $fieldNames[$key]['field_type'] = $Fieldvalue->field_type;
                  // $fieldNames[$key]['fields'][] = $Fieldvalue->db_field_name;//need for use in search // [][table_name][column_mname]
                  $show_fields[$value][]= $Fieldvalue;
                }
              }
            }
          }
          ksort($show_fields);
        }
        $show_fields = array_unique($show_fields);
    }
    
    AdminViewInstance :: showInstancesModal($option, $rows, $clist, $publist, $search, $pageNav, $sort_arr, $show_fields);
  }

  static function showInstanceModalPlg($option){
    global $db, $app, $entities_type, $entityFieldLists;

    $db = new os_cckDb();
    $session = JFactory::getSession();
    $where = array();
    $lid = protectInjectionWithoutQuote('lid','');
    array_push($where, "cl.type = 'add_instance'");
    array_push($where, "jei.published = 1");
    array_push($where, "jei.fk_eid =".$_REQUEST['fk_eid']);

    $selectstring = "SELECT jei.*, cl.title as lay_title, cl.type as lay_type, cl.params as lay_params, cc.title AS category, ce.name AS entity" .
      "\n FROM #__os_cck_entity_instance AS jei" .
      "\n LEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
      "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid ".
      "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ".
      "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
      (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");
    
    $selectstring .= "\nORDER BY jei.eiid";
    $db->setQuery($selectstring);
    //$rows = $db->loadObjectList();
    try {
        $rows = $db->loadObjectList();
    }catch(RuntimeException $e) {
        echo $e->getMessage();
        return false;
    }
//    if ($db->getErrorNum()) {
//      echo $db->stderr();
//      return false;
//    }

    $show_fields = $entityEaaray = $layoutArray = $fieldNames = array();
    if(count($rows)>0){
      foreach ($rows as $row) {
        $lay_params = unserialize($row->lay_params);
        $entityEaaray[] = $row->fk_eid;
        $layoutArray[] = $row->fk_lid;
      }
      $entityEaaray = array_unique($entityEaaray);
      $layoutArray = array_unique($layoutArray);
      foreach( $entityEaaray as $key => $value){
        foreach( $layoutArray as $key2 => $value2){
          $entity = new os_cckEntity($db->_db);
          $entity->load($value);
          $layout = new os_cckLayout($db->_db);
          $layout->load($layoutArray[$key2]);
          $bootstrap_version = $session->get( 'bootstrap','2');
          $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
          $layout_params = unserialize($layout->params);
          $extra_fields_list = $entity->getFieldList();
          foreach($extra_fields_list as $Fieldvalue){
            if($Fieldvalue->show_in_instance_menu && strpos($layout_html,"{|f-".$Fieldvalue->fid."|}")){
              // $fieldNames[$key]['ent_name'] = $entity->eid;
              // $fieldNames[$key]['field_type'] = $Fieldvalue->field_type;
              // $fieldNames[$key]['fields'][] = $Fieldvalue->db_field_name;//need for use in search // [][table_name][column_mname]
              $show_fields[$value][]= $Fieldvalue;
            }
          }
        }
      }
      ksort($show_fields);
    }
    $show_fields = array_unique($show_fields);

    AdminViewInstance :: showInstanceModalPlg($option, $rows, $clist, $publist, $search, $pageNav,
                                               $sort_arr, $show_fields, $lid);
  }

  static function editInstance($option, $eiid){
    global $db, $user,$app, $entityFieldLists, $entities_type, $os_cck_state;

    $db = new os_cckDb();
    
    if (version_compare(JVERSION, "4.0.0-alpha10", "lt")) {

    } else {
      $input = JFactory::getApplication()->input;
      $input->set('hidemainmenu', true);
    }
    $doc = JFactory::getDocument();
    $doc->addStyleSheet(JURI::root() . "components/com_os_cck/assets/css/admin_style.css");
    $doc->addStyleSheet(JURI::root() . "components/com_os_cck/assets/bootstrap/css/bootstrap-grid_OS.css");
    //$doc->addScript(JURI::root() . "components/com_os_cck/assets/bootstrap/js/bootstrapCCK.js");
    $session = JFactory::getSession();
    $select_type = protectInjectionWithoutQuote('lay_type','');
    $task = protectInjectionWithoutQuote('task','');
    $entityInstance = new os_cckEntityInstance($db->_db);
    if($eiid){
        $entityInstance->load(intval($eiid));
    }
    // var_dump($entityInstance);
    if(intval($eiid)){
      $query="UPDATE #__os_cck_entity_instance SET notreaded=0 WHERE eiid=".intval($eiid);
      $db->setQuery($query);
      $db->execute();
    }
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $instance_layout = new os_cckLayout($db->_db);
    $is_new = false;
    if ($eiid === 0) {
      $is_new = true;
    } else {
      $entity = new os_cckEntity($db->_db);
      $entity->load($entityInstance->fk_eid);
      $select_type = $entityInstance->fk_lid; 
    }

    
    $lid = protectInjectionWithoutQuote('lay_type');
    
    $entity_id = protectInjectionWithoutQuote('entity_id', 0, 'INT');
    
    if($lid){
      $select_type = $lid;
    }
    
    $where_and = '';
    if($entityInstance->fk_eid != ''){
        $where_and = "AND c.fk_eid = '" . $entityInstance->fk_eid . "'";
    }else{
      //task add_instance : show all what permited
      $where_and = "";
    }
    $query = "SELECT c.title,c.lid,c.type,c.params,c.fk_eid,ent.name FROM #__os_cck_layout as c"
            ."\n LEFT JOIN #__os_cck_entity as ent ON c.fk_eid = ent.eid WHERE c.type='add_instance' "
            ."\n AND c.published = '1' " . $where_and ;
    $db->setQuery($query);
    $layouts = $db->loadObjectList();
    if(!$layouts){
      $app->enqueueMessage(cck_lang_text('COM_OS_CCK_CREATE_ADD_LAYOUT'));
      $app->redirect("index.php?option=$option&task=show_instance");
      // $app->redirect("index.php?option=$option&task=manage_layout", cck_lang_text('COM_OS_CCK_CREATE_ADD_LAYOUT'));
    }
    
    if(isset($entityInstance->fk_eid)){
        $default_layout = $instance_layout->getDefaultLayout($entityInstance->fk_eid,'add_instance');
    }elseif($entity_id > 0){
        $default_layout = $instance_layout->getDefaultLayout($entity_id,'add_instance');
    }else{
        $default_layout = $instance_layout->getDefaultLayout($entityInstance->fk_eid,'add_instance');
    }

    $lid_array = [];
    foreach($layouts as $key => $value){
      $lid_array[] = $value->lid;
    }
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    if(!in_array($select_type, $lid_array)){
      $select_type = $default_layout;
    }

    foreach($layouts as $key => $value){
      $params = unserialize($value->params);
      $params['views']['instance_type'] = $value->type;
      if($select_type){
        if($select_type == $value->lid){
          $lid = $value->lid;
          $layout_params = $params;  
          $ceid = $value->fk_eid;
        }
      }else{
        if(!$key){//select first option
          $lid = $value->lid;
          $layout_params = $params;
          $ceid = $value->fk_eid;
        }
      }
      $type[]= JHTML::_('select.option',"$value->lid",$value->title.'('.$value->name.')');
    }

    if(isset($type) && is_array($type) && count($type) > 1){
      $layout_type = JHTML::_('select.genericlist',$type, 'lay_type', 
        'class="inputbox" size="1" onchange="swich_task(\''.$task.'\');lay_type_select();"',
         'value', 'text', $select_type);
    }else{
      $layout_type = '';
    }

    $categories = array();
    $db->setQuery("SELECT cid AS value, name AS text FROM #__os_cck_categories" .
                        " ORDER BY ordering");
    $cat = $db->loadObjectList();
    if (count($cat) > 0) $categories = array_merge($categories, $cat);
    $query = "SELECT fk_cid FROM #__os_cck_categories_connect WHERE fk_eiid='" . $entityInstance->eiid . "'";
    $db->setQuery($query);
    $cid = $db->loadResult();
    $clist = os_cck_HTML::categoryList($cid);


    if ($entityInstance->checked_out && $entityInstance->checked_out <> $user->id) {
      $app->enqueueMessage(cck_lang_text('COM_OS_CCK_IS_EDITED'), 'Message');
      $app->redirect("index.php?option=$option&task=show_instance");
    }

    if (!$is_new) {
      $entityInstance->checkout($user->id);
      // $entityInstance->fk_userid = $user->id;
    } else {
      // initialise new record
      $entityInstance->published = 0;
      $entityInstance->approved = 0;
    }

    if ($is_new) $query = 'SELECT eid,name FROM #__os_cck_entity WHERE published="1" ORDER BY name ';
    else $query = 'SELECT eid,name FROM #__os_cck_entity ORDER BY name ';
    $db->setQuery($query);
    $entities_list = $db->loadObjectList();
    if (count($entities_list) < 1) {
        $app->enqueueMessage(cck_lang_text('COM_OS_CCK_CREATE_ENTITY'), 'warning');
        $app->redirect("index.php?option=com_os_cck&task=manage_entities");
    }
    if ($is_new && $ceid != 0) $entityInstance->fk_eid = $ceid;
    if(isset($entityFieldLists[$entityInstance->fk_eid])){
        $extra_fields_list = $entityFieldLists[$entityInstance->fk_eid];
    }else{
        $extra_fields_list = array();
    }


    $layout_params['fields'] = $layout_params['fields'];
    $layout_params['instance_type'] = $layout_params['views']['instance_type'];
    $layout_params['categories_list'] = $clist;
    $layout_params['layout_type'] = $layout_type;
    $layout_params['extra_fields_list'] = $extra_fields_list;
    $instance_layout->load($lid);
    $bootstrap_version = $session->get( 'bootstrap','2');
    $instance_layout->layout_html = $instance_layout->getLayoutHtml($bootstrap_version);

    

    AdminViewInstance::editInstance($option, $entityInstance, $instance_layout, $layout_params);
  }

  static function saveInstance($option){
    global $db, $user,$task, $app, $os_cck_state, $entityFieldLists;

    $db = new os_cckDb();

    $instance = new os_cckEntityInstance($db->_db);
    //A call to the general save function.
    $instance->saveInstance();
//echo '1111111111111111'; exit;
    
//     if(!cck_checkReferer()){
//         $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
//         return;
//     }
//     $session = JFactory::getSession();
//     $post = $_POST;
//     // var_dump($post['eiid']); exit;
//     if(isset($post['eiid'])){
//       unset($post['eiid']);
//       $is_new = true;
//     } else{
//       $is_new = false;
//     }
    
//     // var_dump($_REQUEST); exit;
//     $instance = new os_cckEntityInstance($db->_db);
//     $data = $post;
    
//     //select add clild firlds for sale
//     $select_list = array();
//     $assoc_instancies_list = array();
//     foreach ($data as $key => $value) {
//        if(stripos($key,'fi_text_select_list_') !== false){
//         $select_id = str_ireplace('fi_text_select_list_', '', $key);
//           $select_list[] = $instance->getField($select_id);
//        }
       
//        if(stripos($key,'instanse_assoc_') !== false){
//            $lang = str_replace('instanse_assoc_', '', $key);
//            $assoc_instancies_list[$lang] = $value;
//            if($lang == $data['language']){
//                $assoc_instancies_list[$lang] = $post['id'];
//            }
//        }
//     }
    
//     $assoc_instancies_list_serialize = serialize($assoc_instancies_list);
    
    
//     //select add clild firlds for sale
//     if(!isset($os_cck_state->data) ){
//         echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
//         return ;
//     }
//     $data['fields_data'] = array();
    
//     foreach ($post as $key => $var) {
//       if (strpos($key, 'fi_') === 0) $data['fields_data'][str_replace('fi_', '', $key)] = $var;
//     }

//     if ($post['id'] != 0 && $post['id'] != '') {
//       $instance->load($post['id']);
//       // var_dump($instance); exit;
//       $data['changed'] = get_curent_site_time();
//     } else {
//       $query = "SELECT c.fk_eid FROM #__os_cck_layout as c WHERE c.lid=".$post['lay_type'];
//       $db->setQuery($query);
//       $data['fk_eid'] = $db->loadResult();
//       $data['created'] = get_curent_site_time();
//       $data['changed'] = "0000-00-00 00:00:00";
//       $data['last_review'] = get_curent_site_time();
//     }
//     $data['title'] = protectInjectionWithoutQuote('title','');
//     $data['asset_id'] = 0;
//     if(!isset($post['categories'])){
//       $data['categories'] = array();
//     }
//     //$data['fk_userid'] = $user->id;
//     if(protectInjectionWithoutQuote('lay_type',''))
//       $data['fk_lid'] = protectInjectionWithoutQuote('lay_type');
//     $data['published'] = 1;
//     $data['approved'] = 1;
//     $data['checked_out'] = 0;
//     $data['checked_out_time'] = '0000-00-00 00:00:00';
//     $data['teid'] = 0;
//     $instance->fields_data = '';
//     //calculate price

//     //var_dump($_REQUEST); exit;
    
//     $os_cck_configuration = JComponentHelper::getParams('com_os_cck');
//     $paypal_currency = cck_getCurrency($os_cck_configuration);
//     $instance->instance_currency = $paypal_currency[0]['sign'];
    
//     $instance->instance_price = 0;
    
//     $total_price=0;
//     if(!isset($os_cck_state->data) ){
//         echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
//         return ;
//     }
//     $price_fields = array();
// //    var_dump($data['price_fields']); exit;
//     if(isset($data['price_fields'])){
//         foreach ($data['price_fields'] as $price_field){
            
//             $ordering = protectInjectionWithoutQuote($price_field.'_ordering', array(), 'ARRAY');
// //            var_dump($ordering);
//             $min_price = 0;
//             foreach ($ordering as $key => $val){
                
//                 //var_dump($data[$price_field . '_price_type']); exit;
// //                if(is_array($val)) continue;
//                 if(stripos($price_field, 'pricefield_number_') !== false){
//                     $price_field_type = 'pricefield_number';
//                 }elseif(stripos($price_field, 'pricefield_select_list_') !== false){
//                     $price_field_type = 'pricefield_select_list';
//                 }elseif(stripos($price_field, 'pricefield_radio_buttons_') !== false){
//                     $price_field_type = 'pricefield_radio_buttons';
//                 }
//                 $price_class = new stdClass;
//                 $price_class->fid = '';
//                 //$price_class->price_type = '';
//                 $price_class->price_name = '';
//                 $price_class->price_value = '';
//                 $price_class->quantity = '';
//                 $price_class->ordering = '';
//                 if(isset($data[$price_field . '_fid'])){
//                     $price_class->fid = $data[$price_field . '_fid'];
//                 }
// //                if(isset($data[$price_field . '_price_type'])){
// //                    $price_class->price_type = $data[$price_field . '_price_type'];
// //                }else{
// //                    $price_class->price_type = 'base_price';
// //                }
                    
//                 if(isset($data['fields_data'][$price_field . '_' . $key])){
//                     $price_class->price_value = $data['fields_data'][$price_field . '_' . $key];
//                 }
//                 if(isset($data['fields_data'][$price_field . '_price_name_' . $key])){
//                     $price_class->price_name = $data['fields_data'][$price_field . '_price_name_' . $key];
//                 }else{
//                     $price_class->price_name = $price_class->price_value;
//                 }
//                 if(isset($data['fields_data'][$price_field . '_quantity_' . $key])){
//                     $price_class->quantity = $data['fields_data'][$price_field . '_quantity_' . $key];
//                 }
                
//                 $price_class->ordering = $key;
                
//                 $price_fields[] = $price_class;
                
//                 $field = new os_cckEntityField($db->_db);
//               $field->load($price_class->fid);

//               $layout = new os_cckLayout($db->_db);
//               $layout->load($data['fk_lid']);
//               $layout_params = unserialize($layout->params);

//               //$calculate_ordering = (isset($layout_params['fields'][$field->db_field_name . '_calculation_order'])) ? $layout_params['fields'][$field->db_field_name . '_calculation_order'] : 0;
//               $calculate_type = (isset($layout_params['fields'][$field->db_field_name . '_price_type'])) ? $layout_params['fields'][$field->db_field_name . '_price_type'] : 'base';
              
//               if($calculate_type == 'base_price'){
//                   if($price_class->price_value == '') $price_class->price_value = 0;
//                   if($price_field_type == 'pricefield_number'){
//                     $instance->instance_price = $price_class->price_value;
//                   }else{
//                       if($key == 0){
//                           $min_price = $price_class->price_value;
//                       }else{
//                           if($price_class->price_value < $min_price){
//                               $min_price = $price_class->price_value;
//                           }
//                       }
//                       if(count($ordering) > $key){
//                           $instance->instance_price += $min_price;
//                       }
// //                      var_dump($price_class->price_value);
//                   }
//                   //$instance->quantity = $price_class->quantity;
//               }
//               if($instance->instance_price == ''){
//                   $instance->instance_price = 0;
//               }
              
//             }
//         }
//     }
// //    var_dump($instance->instance_price); exit;
//     foreach ($post as $key => $var) {
//       if (strpos($key, 'child_field_') === 0){ 
//           $data['child_entity_fields'][str_replace('child_field_', '', $key)] = $var;
                  
//       }
//     }

//     $instance->categories = '';
//     if (!$instance->bind($data)) {
//       echo "<script> alert('Entity with this name alredy exist'); window.history.go(-1); </script>\n";
//       exit ();
//     }
    
//     $title = '';
//     foreach($entityFieldLists[$instance->fk_eid] as $old_field){
//         $params = new JRegistry;
//         $params->loadString($old_field->params);
// //        var_dump($params);
//         if($params->get('title_field', '') == 'yes' && isset($data['fi_'.$old_field->db_field_name])){
//             $title = $data['fi_'.$old_field->db_field_name];
//         }
//     }
// //    var_dump($title); exit;
//     //entity_name, entity_tbale_name
//     $entitty->load($instance->fk_eid);
//     $instance->title = $title;
//     $instance->_entity_name = $entitty->name;
//     $instance->associate_instances = $assoc_instancies_list_serialize;
//     $instance->_entity_table_name = "#__os_cck_entity_" . $entitty->name;
//     $layout = new os_cckLayout($db->_db);
//     $layout->load($instance->fk_lid);
//     $layout_params = unserialize($layout->params);
//     $bootstrap_version = $session->get( 'bootstrap','2');
//     $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
//     $instance->_field_list = $entitty->getFieldList($layout->layout_html);
//     $instance->_field_list = array_merge($instance->_field_list, $select_list);
//     $instance->notreaded = 0;
//     $instance->featured_clicks = ($data['featured_clicks'] === '')?-1:$data['featured_clicks'];
//     $instance->featured_shows = ($data['featured_shows'] === '')?-1:$data['featured_shows'];
    
//     $instance->access = isset($data['access']) ? ',' . implode(',', $data['access']) . ',' : ',1,';
    
    
//     $instance->_price_fields = $price_fields;
//     $instance->_child_entity_fields = $data['child_entity_fields'];
//     $instance->fk_userid = ($data['fk_userid'] === '')?JFactory::getUser()->id:$data['fk_userid'];
    
//     $instance->_layout_params = $layout_params['fields'];
//     $instance->fk_lid = $layout->lid;
//     $bootstrap_version = $session->get( 'bootstrap','2');

//     $instance->check(true);

//     //if date field apply data_transform_cck
//     foreach ($instance->_field_list as $field) {
//       if($field->field_type == 'datetime_popup'){
//         $date_format = $layout_params['fields']['datetime_popup_'.$field->fid.'_input_format'];
//         $time_format = $layout_params['fields']['datetime_popup_'.$field->fid.'_input_time_format'];
//         $format = $date_format.' '.$time_format;
//         $date = $instance->fields_data['datetime_popup_'.$field->fid];
//         $instance->fields_data['datetime_popup_'.$field->fid] = data_transform_cck($date, $format);
        
//       }elseif ($field->field_type == 'text_textfield' || $field->field_type == 'text_textarea') {
//           if(isset($layout_params['fields'][$field->db_field_name . '_cut_tags'])
//                   && $layout_params['fields'][$field->db_field_name . '_cut_tags'] == 1){
//                     $instance->fields_data[$field->db_field_name] = strip_tags($instance->fields_data[$field->db_field_name]);
              
//                   }
//       }
//     }

    
//     if (!$instance->require_check()) {
//       echo '<script> alert("' . cck_lang_text("COM_OS_CCK_ADMIN_INFOTEXT_JS_EDIT_REQUIRED") .'"); window.history.go(-1); </script>\n';
//       exit ();
//     }



//     $instance->store();
//     foreach ($assoc_instancies_list as $inst){
//         $query = "UPDATE #__os_cck_entity_instance SET associate_instances='$assoc_instancies_list_serialize' WHERE eiid='$inst'";
//         $db->setQuery($query);
//         $db->execute();
//     }
    // var_dump($option); exit;
    switch ($task) {
      case 'apply_instance':
          $app->redirect("index.php?option={$option}&task=edit_instance&eiid[]=" . $instance->eiid);
          break;
      case 'save_instance':
          $app->redirect("index.php?option={$option}&task=show_instance");
          break;
    }
  }


  static function removeInstances($eiid, $option){
    global $db,$app;

    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    if (!is_array($eiid) || count($eiid) < 1) {
      echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
      exit;
    }
    if (count($eiid)) {
      foreach ($eiid as $id) {
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($id);
        $instance->delete();
      }
    }
    $app->redirect("index.php?option=$option&task=show_instance");
  }

  static function publishInstances($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;
    }
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    foreach($eiids as $eiid){
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($eiid);
        $instance->publishInstance($publish);
    }
//    $eiids = implode(',', $eiids);
//    $db->setQuery("UPDATE #__os_cck_entity_instance SET published='$publish'"
//                    . "\n WHERE eiid IN ($eiids) AND (checked_out=0 OR (checked_out='$user->id'))");
//    try {
//        $db->execute();
//    } catch (RuntimeException $e) {
//        echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
//        exit;
//    }
//
//      if (is_string($eiids) || count($eiids) == 1) {
//      $instance = new os_cckEntityInstance($db->_db);
//      $instance->checkin($eiids[0]);
//    }
    $app->redirect("index.php?option=$option&task=show_instance");
  }

  static function approveInstances($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 ? 'approve' : 'unapprove';
      echo "<script> alert('Select an item to $action'); 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 ;
    }
    foreach($eiids as $eiid){
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($eiid);
        $instance->approvInstance($publish);
    }
//    $eiids = implode(',', $eiids);
//    $db->setQuery("UPDATE #__os_cck_entity_instance SET approved='$publish'"
//                    . "\n WHERE eiid IN ($eiids) AND (checked_out=0 OR (checked_out='$user->id'))");
//    try {
//        $db->execute();
//    } catch (RuntimeException $e) {
//        echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
//        exit;
//        //echo $e->getMessage();
//    }
//    if (is_string($eiids) || count($eiids) == 1) {
//      $instance = new os_cckEntityInstance($db->_db);
//      $instance->checkin($eiids[0]);
//    }
    $app->redirect("index.php?option=$option&task=show_instance");
  }


  /**
   * Cancels an edit operation
   * @param string - The current author option
   */
  static function cancelInstance($option){
    global $db,$app;
    
    $db = new os_cckDb();
    if(protectInjectionWithoutQuote('id','')){
      $row = new os_cckEntityInstance($db->_db);
      $row->load($_REQUEST['id']);
      $row->checkin();
    }
    $app->redirect("index.php?option=$option&task=show_instance");
  }

  static function copyInstance(){
      global $app;
      
      $db = new os_cckDb();
      $eiids = protectInjectionWithoutQuote('eiid', array(),'ARRAY');
      
      if(empty($eiids)){
          $app->enqueueMessage(cck_lang_text('COM_OS_CCK_SELECTED_INSTANCES_ERROR'), 'Error');
          AdminViewInstance::cloneInstance('', '');
      }
      if (count($eiids) > 1) {
        echo "<script> alert('Select only one item to copy'); window.history.go(-1);</script>\n";
        exit;
      }
      
      foreach($eiids as $eiid){
          $html = AdminField::getDatatimeFieldsAjax($eiid);
          AdminViewInstance::cloneInstance($eiid, $html);
      }

  }
  
  static function cloneInstance(){
      global $db, $app;
      
      $db = new os_cckDb();
      $successful_copying = true;
      $eiid = protectInjectionWithoutQuote('eiid', 0, 'INT');
      if($eiid == 0){
          $successful_copying = false;
      }
      $clone_type = protectInjectionWithoutQuote('clone_type', 'normal_copy', 'STRING');
      
          $field_id = protectInjectionWithoutQuote('recursive_field', 0, 'INT');
          $interval = protectInjectionWithoutQuote('time_intervals', '', 'STRING');
          $copies = protectInjectionWithoutQuote('number_of_copies', 1, 'INT');
          
          $db_field_name = '';
          $date_string = '';
          if($field_id > 0){
            $query = "SELECT fk_eid, db_field_name FROM #__os_cck_entity_field WHERE fid=".$field_id;
            $db->setQuery($query);
            $field = $db->loadObjectList();
            $db_field_name = $field[0]->db_field_name;
            $query = "SELECT " . $field[0]->db_field_name . " FROM #__os_cck_content_entity_" . $field[0]->fk_eid . " WHERE fk_eiid=" . $eiid;
            //var_dump($query); exit;
            $db->setQuery($query);
            $field_value = $db->loadResult();
          
            $date = new DateTime($field_value);
            $i = new DateInterval('P1D');
            $i = DateInterval::createFromDateString($interval);
          }
          for($k=0; $k<$copies; $k++){
              if(isset($date)){
                $date->add($i);
                $date_string = $date->format('Y-m-d H:i:s');
              }
              
              $successful_copying = cloneInstance($eiid, $db_field_name, $date_string);
          }
      if($successful_copying){
          $app->enqueueMessage(cck_lang_text('COM_OS_CCK_INSTANCE_CLONE'), 'Message');
      }else{
          $app->enqueueMessage(cck_lang_text('COM_OS_CCK_INSTANCE_CLONE_ERROR'), 'Error');
      }
      $app->redirect(JRoute::_('index.php?option=com_os_cck&view=show_instance', false) );
  }

}

