<?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!");
//     }
// }

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

class AdminEntity
{


    static function publishEntities($publish, $option)
    {
        global $db, $user,$app;
        $db = new os_cckDb();
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
        //$post = JRequest::get('post');
        $post = $_POST;
        $post = protectInjectionWithoutQuote($post, '', 'STRING', true);
        if (array_key_exists('eid', $post)) {
            $eid = $post['eid'];
        } else "Please select some entity";


        if (!is_array($eid) || count($eid) < 1) {
            $action = $publish ? 'publish' : 'unpublish';
            echo "<script> alert('Select an item to " . addslashes($action) . "'); window.history.go(-1);</script>\n";
            exit;
        }

        $eid = implode(',', $eid);

        $db->setQuery("UPDATE #__os_cck_entity SET published='$publish'" .
        "\nWHERE eid IN ($eid) ");
        
        try {
            $db->execute();
        } catch (RuntimeException $e) {
            echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
            exit ();
        }
        

        $app->redirect("index.php?option=com_os_cck&task=manage_entities");

    }


    static function showEntities($option){
        global $db, $app, $jConf;
        $db = new os_cckDb();
        if(!JFactory::getUser()->authorise('access_to_entities', 'com_os_cck')){
            $app->enqueueMessage("Access denied", 'error');
            return;
        }
        $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
        $limitstart = $app->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);

        $query = "select count(*) from #__os_cck_entity ;";
        $db->setQuery($query);
        $total = $db->loadResult();
        $limit = intval($limit);
        // $pageNav = new JPagination($total, $limitstart, $limit);
        $language = JFactory::getApplication()->getLanguage();
        $language->load('os_lib',JPATH_ROOT);
        $pageNav = new os_libPagination($total, $limitstart, $limit);

        $query = "select * from #__os_cck_entity order by name  LIMIT $pageNav->limitstart,$pageNav->limit;";
        $db->setQuery($query);
        $extraentity_list = $db->loadObjectList();

        AdminViewEntity :: showEntities($option, $extraentity_list, $pageNav);
    }


    static function editEntity($option, $name)
    {
        global $db, $doc, $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->addStyleSheet("https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");
        
        $entity = new os_cckEntity($db->_db);
        
        $entity_type = protectInjectionWithoutQuote('entity_type', 'os_cck_entity');
        $entity_list = array();
        //$post = JRequest::get('post');
        $post = $_POST;
        $post = JFactory::getApplication()->input->post->getArray(array(), null, 'raw'); 
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        $eid = 0;
        if(isset($post['eid'])){
            $eid = $post['eid'];
        }
//        var_dump($_REQUEST);
        $fields = array();
        if(is_array($eid)){
            $entity->load($eid[0]);
        }else{
            $entity->load($eid);
        }
        
        if($eid != 0){
            $entity_type = $entity->type;
        }
        
        if($entity_type == 'custom_sql'){
//            var_dump($entity->sql_select); exit;
            $query = "SELECT eid, name FROM #__os_cck_entity WHERE eid != '$entity->eid'";
            $db->setQuery($query);
            $entity_list = $db->loadObjectList();
            
            if($entity->sql_select){
                $query = "SELECT * FROM ($entity->sql_select) as q LIMIT 1";
                $db->setQuery($query);
                $res = $db->loadObjectList();
                $fields = array();
                                
                if(!empty($res)){
                    if(is_object($res[0])){
                        foreach($res[0] as $key => $val){
                            $fields[] = $key;
                        }
                        $entity->fields = $fields;
                    }
                }else{
                    if($entity->custom_fields != ''){
                        $custom_fields = unserialize($entity->custom_fields);
                        if(!empty($custom_fields)){
                            foreach($custom_fields as $key => $val){
                                $fields[] = $key;
                            }
                            $entity->fields = $fields;
                        }
                    }
                }
            }
            
        }
                
        AdminViewEntity :: editEntity($option, $entity, $entity_type, $entity_list);
    }


    static function saveEntity($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;
        }
        //$post = JRequest::get('post');
        $post = $_POST;
        $post = JFactory::getApplication()->input->post->getArray(array(), null, 'raw'); 
        
        $entity_name = $post['name'];
        if (os_cckEntity::is_entity_name_exist($entity_name) && $post['eid'] == "") {
            echo "<script> alert('Entity with this name alredy exist'); window.history.go(-1); </script>\n";
            exit ();
        }
        $entity = new os_cckEntity($db->_db);
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        $data = $post;
//        var_dump($data); exit;
        $data['asset_id'] = 0;
        $data['fk_userid'] = $user->id;
        $data['published'] = 1;
        $data['approved'] = 1;
        $data['created'] = get_curent_site_time();
        $data['changed'] = get_curent_site_time();
        $data['checked_out'] = 0;
        $data['checked_out_time'] = '0000-00-00 00:00:00';
//        $data['sql_select'] = '';
//        var_dump($data); exit;
        if(isset($data['child_id'])){
            $child_id = $data['child_id'];
        }
//        if(isset($data['child_id']) && isset($data['custom_fields'])){
////            $query = "SELECT COUNT(*) FROM #__os_cck_child_parent_connect WHERE fid_parent = "
////            var_dump($data['child_id']); exit;
//            $data['custom_fields']['custom_child_ids'] = serialize($data['child_id']);
//        }
        if(isset($data['custom_fields'])){
            $data['custom_fields'] = serialize($data['custom_fields']);
        }
        if(isset($data['user_fields'])){
            $data['custom_fields'] = serialize($data['user_fields']);
        }
//        if(isset($data['child_id'])){
//            var_dump($data['child_id']);
//            $data['child_id'] = serialize($data['custom_fields']);
//        }
        
        
        if (!$entity->bind($data)) {
            echo "<script> alert('" . addslashes($entity->getError()) . "'); window.history.go(-1); </script>\n";
            exit ();
        }
//        if($entity->eid === ''){
//            $entity->eid = null;
//        }

        try {
            $entity->store();
        } catch (RuntimeException $e) {
            echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
            exit ();
        }
//        var_dump($child_id); exit;
//        if(isset($child_id)){
//            foreach($child_id as $cid){
//                $query = "SELECT COUNT(*) FROM #__os_cck_child_parent_connect WHERE fid_parent = $entity->eid AND fid_child = $cid AND media_type='sql_entity'";
//                $db->setQuery($query);
//                $count = $db->loadResult();
////                var_dump($count); exit;
//                if($count == 0){
//                    $query = "INSERT INTO #__os_cck_child_parent_connect(fid_parent,fid_child,media_type) VALUE('".$entity->eid."','$cid','sql_entity')";
//                    $db->setQuery($query);
//                    $db->execute();
//                }
//            }
//
////            $data['custom_fields']['custom_child_ids'] = serialize($data['child_id']);
//        }
//        var_dump($data['delete_child_ids']); exit;
        if(isset($data['delete_child_ids']) && !empty($data['delete_child_ids'])){
            foreach ($data['delete_child_ids'] as $delete_child_id){
                if($delete_child_id == '') continue;
                $query = "DELETE FROM #__os_cck_child_parent_connect WHERE fid_parent = $entity->eid AND fid_child = $delete_child_id AND media_type='sql_entity'";
//                var_dump($query); exit;
                $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 ;
        }
        
        self::setEntitySettings($data, $entity);
        
        if (!$entity->checkin()) {
            echo "<script> alert('" . addslashes($entity->getError()) . "'); window.history.go(-1); </script>\n";
            exit ();
        }
        $app->enqueueMessage('Entity successfuly saved');
        $app->redirect('index.php?option=com_os_cck&task=manage_entities');

    }

    static function deleteEntity($option)
    {
        global $db,$app, $entities_type;
        $db = new os_cckDb();
        //$post = JRequest::get('post');
        $post = $_POST;
//        var_dump($post);
        $post = protectInjectionWithoutQuote($post, '', 'STRING', true);
//        var_dump($post); exit;
        if (array_key_exists('eid', $post)) {
            $eids = $post['eid'];
            foreach ($eids as $entity) {
                $row = new os_cckEntity($db->_db);
                $row->load($entity);
                
                if($entities_type[$row->eid] != 'joomla_user'){
                    //check if exists binding layout or instance 
                    $query = "SELECT count(ceid) FROM #__os_cck_content_entity_".$row->eid;
                    $db->setQuery($query);
                    $content_entity_count = $db->loadResult();
                }
                
                $query = "SELECT count(cid) FROM #__os_cck_categories WHERE fk_eid = '".$row->eid."'";
                $db->setQuery($query);
                $category_count = $db->loadResult();

                $query = "SELECT count(lid) FROM #__os_cck_layout WHERE fk_eid = '".$row->eid."'";
                $db->setQuery($query);
                $layout_count = $db->loadResult();

                if(isset($content_entity_count) && $content_entity_count > 0){
                     echo "<script> alert('Please remove all content related with this entity'); window.history.go(-1); </script>\n";
                    exit();
                }
                
                if($category_count > 0){
                     echo "<script> alert('Please remove or unbind all categories related with this entity'); window.history.go(-1); </script>\n";
                    exit();
                }

                if($layout_count > 0){
                    echo "<script> alert('Please remove all layouts related with this entity'); window.history.go(-1); </script>\n";
                    exit();
                }

                $query = "SELECT count(eid) FROM #__os_cck_entity";
                $db->setQuery($query);
                $entity_count = $db->loadResult();

                if($entity_count == 1){
                    $query = "DELETE FROM #__os_cck_child_parent_connect";
                    $db->setQuery($query);
                    $db->execute();
                }
              
                if (!$row->delete()) {
                    echo "<script> alert('" . addslashes($row->getError()) . "'); window.history.go(-1); </script>\n";
                    exit();
                }
            }
        }
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_ENTITY_DELETED"));
        $app->redirect('index.php?option=com_os_cck&task=manage_entities');
    }


    static function cancelEditEntity()
    {
        global $db, $app;
        $db = new os_cckDb();
        if(isset($_POST['eid'])){
            $row = new os_cckEntity($db->_db);
            $row->bind($_POST);
            $row->checkin();
        }
        $app->redirect('index.php?option=com_os_cck&task=manage_entities');
    }
    
    static function setEntitySettings($data, $entity){
        $version = checkOsCckVersionProFree();
        if($version == 'free'){
            $data['check_access_instances'] = 0;
            $data['check_access_fields'] = 0;
            $data['check_access_categories'] = 0;
        }
        // Prepare settings
        // Using single quotes is easier because you don't have to escape them. For every setting, add a line.
        $settings = "<?php\n";
        //var_dump($data['check_access_instances']); exit;
        $settings .= "// Do not edit this file. Generated by admin script.\n";
        $settings .= "// CCK Entity Configuration file\n";
        $settings .= "// General Informations \n";
        $settings .= "\$cck_entity_configuration_$entity->eid['check_access_instances']='" .
                $data['check_access_instances'] . "';\n";
        $settings .= "\$cck_entity_configuration_$entity->eid['check_access_fields']='" .
                $data['check_access_fields'] . "';\n";
        $settings .= "\$cck_entity_configuration_$entity->eid['check_access_categories']='" .
                $data['check_access_categories'] . "';\n";
        $settings .= "\$cck_entity_configuration_$entity->eid['max_product_download']='" .
                $data['max_product_download'] . "';\n";
        $settings .= "\$cck_entity_configuration_$entity->eid['days_for_product_download']='" .
                $data['days_for_product_download'] . "';\n";
        if(isset($data['redirect_missing_instance'])){
            $settings .= "\$cck_entity_configuration_$entity->eid['redirect_missing_instance']='" .
                    $data['redirect_missing_instance'] . "';\n";
        }else{
            $settings .= "\$cck_entity_configuration_$entity->eid['redirect_missing_instance']='';\n";
        }
        if(isset($data['redirect_missing_category'])){
            $settings .= "\$cck_entity_configuration_$entity->eid['redirect_missing_category']='" .
                    $data['redirect_missing_category'] . "';\n";
        }else{
            $settings .= "\$cck_entity_configuration_$entity->eid['redirect_missing_category']='';\n";
        }
        if(isset($data['max_items'])){
            foreach ($data['max_items'] as $key => $value){
                $settings .= "\$cck_entity_configuration_$entity->eid['max_items'][$key]='" .
                    $value . "';\n";
            }
        }
        if(isset($data['meta_title_source'])){
            $settings .= "\$cck_entity_configuration_$entity->eid['meta_title_source']='" .
                    $data['meta_title_source'] . "';\n";
        }else{
            $settings .= "\$cck_entity_configuration_$entity->eid['meta_title_source']='1';\n";
        }
        if(isset($data['meta_description_source'])){
            $settings .= "\$cck_entity_configuration_$entity->eid['meta_description_source']='" .
                    $data['meta_description_source'] . "';\n";
        }else{
            $settings .= "\$cck_entity_configuration_$entity->eid['meta_description_source']='1';\n";
        }
        if(isset($data['meta_keywords_source'])){
            $settings .= "\$cck_entity_configuration_$entity->eid['meta_keywords_source']='" .
                    $data['meta_keywords_source'] . "';\n";
        }else{
            $settings .= "\$cck_entity_configuration_$entity->eid['meta_keywords_source']='1';\n";
        }
        
        $settings .= "?>";
        
        // Write out new initialization file
        //if (file_exists("./components/com_os_cck/entities_conf/admin.entity_id_$entity->eid.class.conf.php")) {
            $fd = fopen("./components/com_os_cck/entities_conf/admin.entity_id_$entity->eid.class.conf.php", "w")
                or die("Cannot create configuration file.");
        //}
        fwrite($fd, $settings);
        fclose($fd);
    }
    
    static function addEntity($option){
        $type_options = array();
        $type_options[] = JHTML::_('select.option','', cck_lang_text('COM_OS_CCK_LABEL_SELECT_ALL_ENTITY_TYPE'));
        $type_options[] = JHTML::_('select.option','os_cck_entity', 'CCK Entity');
        if( checkOsCckVersionProFree() == "pro" ) $type_options[] = JHTML::_('select.option','joomla_user', 'Joomla User Entity');
        if( checkOsCckVersionProFree() == "pro" ) $type_options[] = JHTML::_('select.option','custom_sql', 'Custom SQL Entity');
        
        $type_list = JHTML::_('select.genericlist',$type_options, 'entity_type',
                                       'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', '');
        
        AdminViewEntity :: addEntity($option, $type_list);
    }
    
    static function check_custom_query() {
        global $app, $db, $input;
        $db = new os_cckDb();
        $query = $input->get('query', '', 'STRING');
        
        try {
            $db->setQuery($query);
            $db->loadObjectList();
        } catch (Exception $ex) {
            echo json_encode(array('success' => false, 'errorMsg' => $ex->getMessage()));
            return;
//            var_dump($ex->getMessage() );
        }
        echo json_encode(array('success' => true));
//        var_dump($query);
        
    }
    
    static function loadCustomFields() {
        global $app, $db, $input;
        $db = new os_cckDb();
        $query = $input->get('query', '', 'STRING');
        $query = "SELECT * FROM ($query) as t LIMIT 1";
        
        try {
            $db->setQuery($query);
            $result = $db->loadObjectList();
        } catch (Exception $ex) {
            echo json_encode(array('success' => false, 'errorMsg' => $ex->getMessage()));
            return;
        }
        
        echo json_encode(array('success' => true, 'fields' => $result[0]));
//        var_dump($result);
    }

}
