<?php
/**
* @package OrdaSoft 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 Joomla CCK - Content Construction Kit
*/

defined('_JEXEC') or die;

////////////////////////GLOBAL VARIABLES DECLARATION///////////////////////
// $mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path'] = JPATH_SITE;
//$mosConfig_live_site = $GLOBALS['mosConfig_live_site'] = JURI::root(); 

require_once(JPATH_SITE . "/components/com_os_cck/functions.php");

global $option,
        $Itemid,
        $doc,
        $user,
        $db,
        $os_cck_configuration,
        $limit,
        $limitstart,
        $app,
        $task,
        $session,
        $jConf,
        $input;

//include ordasoft library api  classes
$path = JPATH_ROOT. '/libraries/os_lib/src/os_libMain.php';
if (!file_exists($path)){
  echo "To display the Joomla CCK Component, you need install OrdaSoft Library first <br />"; exit;
} else{
    if (version_compare(JVERSION, "4.0.0", "lt")) {
      auto_include(JPATH_ROOT. '/libraries/os_lib/src');
    }
}
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 CCK Package!");
    }
}
//turn on language files from library
$language = JFactory::getApplication()->getLanguage();
$language->load('os_lib',JPATH_ROOT );


$app = JFactory::getApplication();
$input = $app->input;
$user = JFactory::getUser();
$doc = JFactory::getDocument();
// $db = JFactory::getDBO();
    
$session = JFactory::getSession();
$os_cck_configuration = JComponentHelper::getParams('com_os_cck');
$jConf = JFactory::getConfig();


$Itemid = $input->get('Itemid', 0, 'INT');;
$option = $input->get('option', '', 'STRING');
$lid = $input->get('lid', 0,'INT');
$fid = $input->get('fid', 0,'INT');
$task = $input->get('task', '', 'STRING');
$view = $input->get('view', '', 'STRING');
$type = $input->get('type', '', 'STRING');
$catid = $input->get('catid', 0, 'INT');
$eiids = $input->get('eiid', array(0), 'ARRAY');
$cid = $input->get('cid', array(0), 'ARRAY');
$cb = $input->get('cb', array(0), 'ARRAY');

///////////END GLOBAL VARIABLES DECLARATIONS///////////////////////
JHtml::_('jquery.framework');

// if(checkJavaScriptIncludedCCK("font-awesome/6.7.2/css/all.min.css") === false ) {
//    $doc->addScript(JUri::root() . "components/com_os_cck/assets/js/swiper-os.js");
// }
// if(checkStylesIncludedCCK("lightbox.css") === false ) {
//    $doc->addStyleSheet( JUri::root().'components/com_os_cck/assets/lightbox/css/lightbox.css');
// }
includeStylesCCK("//cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css");
includeStylesCCK("components/com_os_cck/assets/css/admin_style.css");
includeStylesCCK("components/com_os_cck/assets/css/table_api.css");
if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
    includeStylesCCK("components/com_os_cck/assets/css/admin_style-j4.css");
}else{
    includeStylesCCK("components/com_os_cck/assets/css/admin_style-j3.css");
}
includeStylesCCK("//cdn.jsdelivr.net/npm/sceditor@3/minified/themes/default.min.css");
includeJavaScriptCCK("//cdn.ckeditor.com/ckeditor5/38.1.1/classic/ckeditor.js");
$is_added_before = includeJavaScriptCCK("components/com_os_cck/assets/js/jQuerOs-2.2.4.min.js",true);
if( !$is_added_before ) $doc->addScriptDeclaration('jQuerOs=jQuerOs.noConflict();');

includeStylesCCK("components/com_os_cck/assets/css/jquerOs-ui.min.css");
includeJavaScriptCCK("components/com_os_cck/assets/js/jquerOs-ui.min.js");
includeJavaScriptCCK("components/com_os_cck/assets/js/functions.js");

// $doc->addScript(JUri::root().'components/com_os_cck/assets/js/jquery.raty.js');
// $doc->addStyleSheet( JUri::root().'/components/com_os_cck/assets/lightbox/css/lightbox.css');
// $doc->addScript(JURI::root() . '/components/com_os_cck/assets/lightbox/js/lightbox-2.6.min.js');



//swiper slider js and css
//$doc->addStylesheet(JUri::root() . "components/com_os_cck/assets/css/swiper.css");
//$doc->addScript(JUri::root() . "components/com_os_cck/assets/js/swiper-os.js");

// <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sceditor@3/minified/themes/default.min.css" />
// <script src="https://cdn.jsdelivr.net/npm/sceditor@3/minified/sceditor.min.js"></script>
	
require_once(JPATH_SITE . "/administrator/components/com_os_cck/toolbar.os_cck.php");
JHtmlBehavior::core();
require_once(JPATH_SITE . "/administrator/components/com_os_cck/os_cck.html.php");

jimport('joomla.html.pagination');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.application.component.helper');

$GLOBALS['os_cck_state'] = $os_cck_state = checkOsCckActivation() ;
//if(!function_exists("auto_include")){
//    function auto_include($path_to_files)
//    {
//        //for absolut path
//        $component_path = JPath::clean( $path_to_files);
//        if (is_dir($component_path) && ($files_in_folder = JFolder::files($component_path, '^[^-]*\.php$', false, true))) {
//            foreach ($files_in_folder as $i => $file) {
//                require_once($file);
//            }
//        }else{
//            //for relative path
//            $component_path = JPath::clean(JPATH_SITE . $path_to_files);
//            if (is_dir($component_path) && ($files_in_folder = JFolder::files($component_path, '^[^-]*\.php$', false, true))) {
//                foreach ($files_in_folder as $i => $file) {
//                    require_once($file);
//                }
//            }            
//        }
//    }
//}
//
//if(!function_exists("auto_include_with_global")){
//    function auto_include_with_global($path_to_files)
//    {
//        $component_path = JPath::clean(JPATH_SITE . $path_to_files);
//        if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path, '^[^-]*\.php$', false, true))) {
//            foreach ($component_layouts as $i => $file) {
//                require_once($file);
//                $file_name = substr($file, strrpos($file, '/')+1);
//                $file_name = explode('.', $file_name);
//                $pos = strripos($file_name[1], '_');
//                $entity_id = substr($file_name[1], $pos+1);
//                
//                if($entity_id != '' && isset(${"cck_entity_configuration_$entity_id"})){
//                    $GLOBALS['cck_entity_configuration'][$entity_id] = ${"cck_entity_configuration_$entity_id"};
//                }
//            }
//        }
//    }
//}
if (version_compare(JVERSION, "4.0.0", "lt")) {
    auto_include('/libraries/os_lib/src');
}
auto_include('/administrator/components/com_os_cck/adminphp');
auto_include('/administrator/components/com_os_cck/adminhtml');
auto_include('/components/com_os_cck/classes');

auto_include_with_global('/administrator/components/com_os_cck/entities_conf');
$db = new os_cckDb();
$GLOBALS['db'] = $db;
os_cck_initialization();

// var_dump($task); exit;
//print_r($task); exit;
switch ($task) {
/* FIELD ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
    case "show_in_ins":
        ob_start();
            AdminField::show_in_ins(1, $option);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;

    case "not_show_in_ins":
        ob_start();
            AdminField::show_in_ins(0, $option);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;
    case "set_title_field":
        ob_start();
            AdminField::setTitleField(1, $option);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;
    case "set_show_in_orders":
    case "set_show_in_requests":
    case "set_show_in_rent":
    case "set_show_in_rent_requests":    
    case "set_show_in_buy_requests":    
    case "set_show_in_reviews":    
        
        ob_start();
            AdminField::setShowField($task, $option);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;

    case "saveLayoutField":
        ob_start();
            AdminField::saveLayoutField($fid);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;
    case "saveLayoutFieldName":
        ob_start();
            AdminField::saveLayoutFieldName($option);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;

    case "publish_fields":
        ob_start();
            AdminField::publishFields(1, $option);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;

    case "unpublish_fields":
        ob_start();
            AdminField::publishFields(0, $option);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;

    case "deleteLayoutField":
        ob_start();
            AdminField::deleteField($option);
            $html = ob_get_contents();
        ob_end_clean();
        
        $response = array('html' => $html);
        echo json_encode($response);
        break;

    case "showFieldList":
        ob_start();
            AdminField::showLayoutFields($option);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;

    case "addLayoutField":
    case "editLayoutField":
 
        ob_start();

            AdminField::addLayoutField($option,$fid);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;

    case "addOptionForLayout":
        global $cck_entity_configuration, $entity_type;
        $lid = $input->get("lid",0,"INT");
        $key = $input->get("key",'',"STRING");
        $layout_type = $input->get("layout_type",'',"STRING");
        $layout_type.='_layout';
        $layout = new os_cckLayout($db->_db);
        $layout->load($lid);
        $layout_params = unserialize($layout->params);
        ob_start();
            require getLayoutPathCCK::getAdminLayoutViewPath('com_os_cck', $layout_type, 'layoutOptions');
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;
/* END FIELD ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

/* LAYOUT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
    case "addFieldOptions":
        global $cck_entity_configuration, $entityFieldLists;
        $lid = $input->get("lid",0,"INT");
        $layout_type = $input->get("layout_type",'',"STRING");
        if($layout_type == 'add_instance' || $layout_type == 'request_instance'
            || $layout_type == 'rent_request_instance' || $layout_type == 'buy_request_instance'
            || $layout_type == 'review_instance'){
            $viewType = 'add';
        }else{
            $viewType = 'show';
        }

        $type = $input->get('type', '', 'STRING');
        if($type == 'unique'){
            $viewType = 'unique';
        }
        $fName = $input->get("fieldName",'',"STRING");
        if($fName && $layout_type && $lid && $viewType != 'unique'){
            $query = "SELECT *".
                    "\n FROM #__os_cck_entity_field WHERE db_field_name=".$db->Quote($fName);
            $db->setQuery($query);
            $field = $db->loadObjectList();
            $field = $field[0];
            $layout = new os_cckLayout($db->_db);
            $layout->load($lid);
            $layout_params = unserialize($layout->params);
            $fields_from_params = (isset($layout_params['fields']))?$layout_params['fields']:array();

            ob_start();
                show_edite_add_form_field_layout($field, $viewType, $fields_from_params,$layout_type,$layout);
                $html = ob_get_contents();
            ob_end_clean();

            $response = array('html' => $html);
            echo json_encode($response);
        }elseif($fName && $layout_type && $lid && $viewType == 'unique'){

            $temp_fName = $fName;
            $fName = substr($temp_fName, 0, strripos($temp_fName, '_'));
            $fName = str_replace('cck_', '', $fName);
            $key = substr($temp_fName, strripos($temp_fName, '_') +1);
// var_dump($key);
            $layout = new os_cckLayout($db->_db);
            $layout->load($lid);
            $layout_params = unserialize($layout->params);
            $fields_from_params = (isset($layout_params['fields']))?$layout_params['fields']:array();

            $field = new os_cckEntityField($db->_db);
            $field->db_field_name = $temp_fName;

            ob_start();
                require getAdminFiledSettingsViewPath('com_os_cck', 'unique', $fName);
                $html = ob_get_contents();
            ob_end_clean();

            $response = array('html' => $html);
            echo json_encode($response);
            // var_dump($fName);
        }else{
            $response = array('html' => "Error while creating option.Please refresh page.");
            echo json_encode($response);
        }
        break;

    case "updateLayoutFieldList":
        ob_start();
            AdminLayout::updateLayoutFieldList($option, $lid[0]);
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;        
/* END LAYOUT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

    case "is_readed":
        setReaded($eiids);
    break;

    case "is_readed_orders":
        setReadedOrders();
    break;

    case "settings":
        $app->redirect("index.php?option=com_config&view=component&component=com_os_cck");
        break;

    case "new_instance":
        AdminInstance::editInstance($option, 0);
        break;
    
    case "getContent":
        require_once(JPATH_SITE . "/administrator/components/com_os_cck/helpers/uploader.php");
        break;
    
    case "orders":
        AdminOrders::showOrders();
        break;

    case "order_details":
        AdminOrders::showOrderDetails();
        break;     

    case "deleteOrder":
        AdminOrders::deleteOrder($cb, $option);
        break;

    case "changeOrderStatus":
        AdminOrders::changeOrderStatus();
        break; 
    case "updateOrderStatus":
        AdminOrders::updateOrderStatus();
        break; 

    case "edit_instance" :
    
        AdminInstance::editInstance($option, array_pop($eiids));
        break;

    case "save_instance" :
    case "apply_instance" :
        AdminInstance::saveInstance($option);
        break;

    case "remove_instances" :
        AdminInstance::removeInstances($eiids, $option);
        break;

    case "publish_instances" :
        AdminInstance::publishInstances($eiids, 1, $option);
        break;

    case "unpublish_instances" :
        AdminInstance::publishInstances($eiids, 0, $option);
        break;

    case "approve_instances" :
        AdminInstance::approveInstances($eiids, 1, $option);
        break;

    case "unapprove_instances" :
        AdminInstance::approveInstances($eiids, 0, $option);
        break;

    case "cancel_instance" :
        AdminInstance::cancelInstance($option);
        break;
/* END INSTANCE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
/* CATEGORY     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
    case "show_categories" :
        AdminCategory::showCategories();
        break;

    case "edit_category" :
        AdminCategory::editCategory($option, $cid[0]);
        break;

    case "add_category":
        AdminCategory::editCategory($option, 0);
        break;

    case "cancel_category":
        AdminCategory::cancelCategory();
        break;

    case "save_category":
        AdminCategory::saveCategory();
        break;

    case "remove_categories":
        AdminCategory::removeCategories($option, $cid);
        break;

    case "publish_categories":
        AdminCategory::publishCategories("com_os_cck", $id, $cid, 1);
        break;

    case "unpublish_categories":
        AdminCategory::publishCategories("com_os_cck", $id, $cid, 0);
        break;

    case "orderup_category":
        AdminCategory::orderCategory($cid[0], -1);
        break;

    case "orderdown_category":
        AdminCategory::orderCategory($cid[0], 1);
        break;

    case "accesspublic_category":
        AdminCategory::accessCategory($cid[0], 0);
        break;

    case "accessregistered_category":
        AdminCategory::accessCategory($cid[0], 1);
        break;

    case "accessspecial_category":
        AdminCategory::accessCategory($cid[0], 2);
        break;

/* ENDCATEGORY ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

/* REVIEW ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

    case "manage_review" :
        AdminReview:: showReviews($option, "");
        break;

    case "edit_review" :
        AdminReview:: editReview($option, array_pop($eiids));
        break;

    case "delete_review" :
        AdminReview::removeReviews($eiids, $option);
        break;

    case "save_review" :
    case "cancel_review" :
        AdminReview::saveReview($option);
        break;

    case "publish_reviews" :
        AdminReview::publishReviews($eiids, 1, $option);
        break;

    case "unpublish_reviews" :
        AdminReview::publishReviews($eiids, 0, $option);
        break;

    case "approve_reviews" :
        AdminReview::approveReviews($eiids, 1, $option);
        break;

    case "unapprove_reviews" :
        AdminReview::approveReviews($eiids, 0, $option);
        break;

/* END REVIEW ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

/* ENTITY ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

    case "publish_entities":
        AdminEntity::publishEntities(1, $option);
        break;
    case "unpublish_entities":
        AdminEntity::publishEntities(0, $option);
        break;

    case "manage_entities":
        AdminEntity::showEntities($option);
        break;

    case "add_entity":
        AdminEntity::addEntity($option);
        //AdminEntity::editEntity($option, '');
        break;

    case "edit_entity":
        
        $post = $_POST;
        
        if (array_key_exists('name', $post)) {
            $entity_type_name = $post['name'];
            AdminEntity::editEntity($option, $entity_type_name[0]);
        } else AdminEntity::editEntity($option, "");
        

        break;

    case "save_entity":
        AdminEntity::saveEntity($option);
        break;

    case "delete_entity":
        AdminEntity::deleteEntity($option);
        break;

    case "cancel_edit_entity":
        AdminEntity::cancelEditEntity();
        break;

/* END ENTITY ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

/* SETTINGS ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
    case "config" :
        AdminSettings::configure($option);
        break;

    case "config_save" :
        AdminSettings::configure_save_frontend($option);
        AdminSettings::configure_save_backend($option);
        AdminSettings::configure($option);
        break;

/*END SETTINGS ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

/* LAYOUTS ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/

    case "manage_layout" :
        AdminLayout::showLayouts($option);
        break;

    case "showLayoutsModalPlg":
        AdminLayout::showLayoutsModalPlg($option);
        break;

    case "select_data_for_editor_button":
        AdminLayout::showModalCckButton($option);
        break;

    case "showInstanceModalPlg";
        AdminInstance::showInstanceModalPlg($option);
        break;

    case "showCategoryModalPlg":
        AdminCategory::showCategoryModalPlg($option);
        break;

    case "new_layout" :
        AdminLayout::newLayout($option);
        break;

    case "add_new_layout" :
        AdminLayout::addNewLayout($option);
        break;

    case "edit_layout" :
        
        AdminLayout::editLayout($option, $lid[0]);
        break;

    case "copy_layout" :
        AdminLayout::copyLayout($option, $lid);
        break;

    case "save_layout" :
    case "apply_layout" :
    case "cancel_layout" :
        AdminLayout::saveLayout($option);
        break;

    case "publish_layouts" :
        AdminLayout::publishLayouts($lid, 1, $option);
        break;

    case "unpublish_layouts" :
        AdminLayout::publishLayouts($lid, 0, $option);
        break;

    case "approve_layouts" :
        AdminLayout::approveLayouts($lid, 1, $option);
        break;

    case "unapprove_layouts" :
        AdminLayout::approveLayouts($lid, 0, $option);
        break;

    case "remove_layouts" :
        AdminLayout::removeLayouts($lid, $option);
        break;
/* END LAYOUTS ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
    case "edit_rent" :
        AdminRent::edit_rent($option, $eiids);
        break;

//    case "rent" :
//        AdminRent::rent_instance($option, $eiids);
//        break;

    case "add_rent" :
        AdminRent::rent_instance($option, $eiids);
        break;

    case "add_rent_confirm" :
        AdminRent::add_rent_confirm($option, array_pop($eiids),$task);
        break;

    case "save_rent" :
        AdminRent::saveRent($option, array_pop($eiids),$task);
        break;

    case "rent_return" :
        AdminRent::rent_return($option, $eiids);
        break;

    case "rent_return_confirm" :
        $eiid = $input->get('return_id','');
        AdminRent::rent_return_confirm($option, $eiid);
        break;

    case "show_rent_request_instances" :
        AdminRent_request::showRentRequestInstances($option);
        break;

    case "edit_rent_request_instance" :
        AdminRent_request::editRentRequestInstance($option, array_pop($eiids));
        break;

    case "accept_rent_requests" :
        AdminRent_request::accept_rent_requests($option, $eiids);
        break;

    case "decline_rent_requests" :
        AdminRent_request::decline_rent_requests($option, $eiids);
        break;

    case "delete_rent_requests" :
        AdminRent_request::delete_rent_requests($option, $eiids);
        break;

    case "accept_buying_requests" :
        AdminBuy_request::accept_buying_requests($option, $eiids);
    break;

    case "users_rent_history" :
        AdminRent_history::users_rent_history($option, $eiids);
        break;     

    case "show_rent_request_from_history" :
        AdminRent_history::showRentRequestFromHistory($option, array_pop($eiids) );
        break;        

    case "show_buy_request_instances" :
        AdminBuy_request::showBuyRequestInstances($option);
        break;

    case "edit_buy_request_instance" :
        AdminBuy_request::editBuyRequestInstance($option, array_pop($eiids));
        break;

    case "delete_buying_requests" :
        AdminBuy_request::delete_buying_requests($option, $eiids);
        break;

    case "change_status":
        AdminBuy_request::change_status($option);
        break;

    case "import" :
        AdminImportExport::import();
        break;

    case "about" :
        cckAbout();
        break;

    case "delete_review" :
        $ids = explode(',', $eiids[0]);
        delete_review($option, $ids[1]);
        editEntityInstance($option, $ids[0], $entity_type);
        break;

    case "edit_review" :
        $ids = explode(',', $eiids[0]);
        edit_review($option, $ids[1], $ids[0]);
        break;

    case "update_review" :
        $title = mosGetParam($_POST, 'title');
        $comment = mosGetParam($_POST, 'comment');
        $rating = mosGetParam($_POST, 'rating');
        $item_id = mosGetParam($_POST, 'house_id');
        $review_id = mosGetParam($_POST, 'review_id');

        update_review($title, $comment, $rating, $review_id);
        editEntityInstance($option, $item_id, $entity_type);
        break;

    case "cancel_review_edit" :
        $item_id = mosGetParam($_POST, 'house_id');
        editEntityInstance($option, $item_id, $entity_type);
        break;

//******  begin add for button print in Manager houses  ***********

    case "show_requests":
        AdminRequest::showRequests($option);
        break;

    case "show_request_item":
        AdminRequest::showRequestItem($option, array_pop($eiids));
        break;

    case "remove_request_item" :
        AdminRequest::removeRequestItem($eiids, $option);
        break;

    case "show_instance_modal" :
        AdminInstance::showInstancesModal($option);
        break;

    case "show_categories_modal" :
        AdminCategory::showCategoriesModal($option);
        break;

    case "manage_layout_modal" :
        AdminLayout::showLayoutsModal($option);
        break;

    case "checkFile":
        checkFile($option);
        break;
    
    case "getEntityFieldsAjax":
        ob_start();
            AdminField::getEntityFieldsAjax();
            $html = ob_get_contents();
        ob_end_clean();
//        ob_start();
//            require getAdminFiledSettingsViewPath('com_os_cck', 'unique', 'select_child');
//            $settings = ob_get_contents();
//        ob_end_clean();
        $response = array('html' => $html);
        echo json_encode($response);
        break;
    
    case "getChildEntitySettingsAjax":
        $layout_type = $input->get("layout_type", 'add_instance', 'STRING');
        if($layout_type == 'add_instance'){
            $unique_id = $input->get("unique_id",'',"STRING");
            $child_entity = new stdClass();
            $child_entity->data_field_name = 'e-p-ch-' . $unique_id;
            $child_entity->entity_alias = $input->get("entityAlias",'',"STRING");
            $gtree = get_group_children_tree_cck();
            $entityId = $input->get("entityId",'',"STRING");
            global $os_cck_configuration, $cck_entity_configuration;
            ob_start();
                require getAdminFiledSettingsViewPath('com_os_cck', 'unique', 'select_child');
                $settings = ob_get_contents();
            ob_end_clean();
        } else {
            $settings = AdminField::getFieldSettingsForChildEnteties($layout_type);
        }
        $response = array('settings' => $settings);
        echo json_encode($response);
        break;
    
    case "getNameEntityFieldsAjax":
        ob_start();
            AdminField::getNameEntityFieldsAjax();
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;
    
    case "addOptionForOrderByInParentChildLayout":
        $lid = $input->get("lid",0,"INT");
        $child_lid = $input->get("key",'',"STRING");
        
        $layout = new os_cckLayout($db->_db);
        $layout->load($lid);
        //$layout_params = unserialize($layout->params);
        ob_start();
            require getAdminFiledSettingsViewPath('com_os_cck', 'unique', 'order_by');
            $html = ob_get_contents();
        ob_end_clean();

        $response = array('html' => $html);
        echo json_encode($response);
        break;
    
    case "addFieldMaskForSqlWhereLayoutOptionByInParentChildLayout":
        AdminField::addFieldMaskForSqlWhereLayoutOptionByInParentChildLayoutAjax();
        
        break;
    
/*COUPONS*/
    case "coupons":
        AdminCoupons::showCoupons($option);
        break;
    
    case "publish_coupons" :
    case "publish_coupon" :
        AdminCoupons::publishCoupons($input->get('coup_id', array(0), 'ARRAY'), 1, $option);
        break;

    case "unpublish_coupons" :
    case "unpublish_coupon" :
        AdminCoupons::publishCoupons($input->get('coup_id', array(0), 'ARRAY'), 0, $option);
        break;
    
    case "add_coupon" :
    case "edit_coupon" :
    case "new_coupon" :
        AdminCoupons::editCoupon($option);
        break;
    
    case "save_coupon":
        AdminCoupons::saveCoupon($option);
        break;
        
    case "remove_coupon":
        AdminCoupons::removeCoupon($option);
        break;
    
    case "check_package_state":
        //var_dump($state);
        $state = checkOsCckState();
        print_r($state);exit();
        break ;

    case "update_package":
        updateOsCck();
        break ;

    case "set_package_license":
        $data = protectInjectionWithoutQuote('data', '', 'string');
        //echo '1111111111111';
        setOsCckLicense($data);
        break;
    
    case "copy_instance":
        AdminInstance::copyInstance();
        break ;
        
    case "clone_instance":
        AdminInstance::cloneInstance();
        break ;
        
    case "getDatatimeFieldsAjax":
        AdminField::getDatatimeFieldsAjax();
        break;
    
    case "getChildEntityFieldsAutocomplite":
        AdminField::getChildEntityFieldsAutocomplite();
        break;
    
    case "check_custom_query":
        AdminEntity::check_custom_query();
        break;
    
    case 'load_fields_form_custom_sql':
        AdminEntity::loadCustomFields();
        break;
    
    case 'export':
        AdminImportExport::export();
        break;
    
    case 'getNewAvalibleTimeSelect':
        AdminLayout::getNewAvalibleTimeSelect();
        break;

    case "decline_buying_requests" :
        AdminBuy_request::decline_buying_requests($option, $eiids);
        break;

    case "importJsLibrary":
        AdminImportExport::importJsLibrary();
        break ;

    case "csv_import" :
        AdminImportExport::csv_import();
        break;

    case 'csv_export':
        AdminImportExport::csv_export();
        break;
        
    case "removeGalleryImage":
        removeGalleryImageCck();
        break;

    case "show_instance":
    default :
        //$avaibleUpdate must be comented in free version
        $avaibleUpdate = avaibleUpdateCCK();
        AdminInstance::showInstances($option, $avaibleUpdate);
        break;


//******  end add for Entity Manager  *************
}

function setReaded($eiids){
    global $db, $app;
    $eiids = implode(",",$eiids);
    $query = "UPDATE #__os_cck_entity_instance SET notreaded=0 WHERE eiid IN($eiids)";
    $db->setQuery($query);
    $db->execute();
    
    $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
}

function setReadedOrders(){
    global $db, $app;
    $orderIds = $_POST['cb'];
    $orderIds = implode(",",$orderIds);
    $query = "UPDATE #__os_cck_orders  SET notreaded=0 WHERE id IN($orderIds)";
    $db->setQuery($query);
    $db->execute();

    $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
}

function checkFile() {
    $path = $_GET["path"];
    $filename = basename($_GET["file"]);
    $file = $path . $filename;
    if (file_exists($file)) {
        echo "The file with such name already is!";
    } else {
        echo "";
    }
}

function cckAbout(){
    //check update
    $avaibleUpdate = avaibleUpdateCCK();
    HTML_os_cck :: about($avaibleUpdate);
}



function edit_review($option, $review_id, $item_id)
{
    global $db;
    $db->setQuery("SELECT * FROM #__os_cck_review WHERE id=" . $review_id . " ");
    $review = $db->loadObjectList();
    echo $db->getErrorMsg();
    HTML_os_cck :: edit_review($option, $item_id, $review);
}


function delete_review($option, $id)
{
    global $db;
    //delete review where id =.. ;
    $db->setQuery("DELETE FROM #__os_cck_review WHERE #__os_cck_review.id=" . $id . ";");
    $db->execute();
    echo $db->getErrorMsg();
}

function getDeepLevel($catid, $cat_all,$deep = 0) {
  global $moduleId,$max_dip;
  $deep++;
  for ($i = 0; $i < count($cat_all); $i++) {
    if (($catid == $cat_all[$i]->parent_id)){
      if($max_dip < $deep-1){
        $max_dip = $deep-1;
      }
      getDeepLevel($cat_all[$i]->cid, $cat_all,$deep,$max_dip);
    }//end if
  }//end for
  return $max_dip;
}//end fn
