<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * classified classified Controller
 *
 * This class handles only classified related functionality
 *
 * @package		Admin
 * @subpackage	classified
 * @author		webhelios
 * @link		http://webhelios.com
 */


class Content_core extends MX_Controller {

	var $per_page = 10;

	public function __construct()
	{

		parent::__construct();
		is_installed(); #defined in auth helper

		checksavedlogin(); #defined in auth helper

		if(!is_admin() && !is_agent())
		{
			if(count($_POST)<=0)
			$this->session->set_userdata('req_url',current_url());
			redirect(site_url('admin/auth'));
		}

		$this->per_page = get_per_page_value();#defined in auth helper
		$this->load->helper('text');
		// $this->load->model('admin/classified_model');
		$this->load->model('admin/content_model');
		$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
	}

	#****************** post function start *********************#
	public function index()
	{
		if(is_admin())
		{
			redirect(site_url('admin'));
		}
		else
		{
			redirect(site_url('admin/content/allnews'));
		}
	}

	/*public function allposts($start='0')
	{
		$value 				= array();
        $data['title'] 		= lang_key('all_posts');
		$data['content'] 	= load_admin_view('classified/all_posts_view',$value,TRUE);
		load_admin_view('template/template_view',$data);
	}

	public function allposts_ajax($start='0')
	{
		$value['posts']  	= $this->classified_model->get_all_post_based_on_user_type($start,$this->per_page,'create_time','desc');
		$total  			= $this->classified_model->get_all_post_based_on_user_type('total',$this->per_page,'create_time','desc');
		$value['pages']		= configPagination('admin/classified/allposts_ajax',$total,5,$this->per_page);
		load_admin_view('classified/all_posts_ajax_view',$value);
	}*/

	#delete a post
	public function deletepost($page='0',$id='',$confirmation='')
	{
		if(!is_admin() && !is_agent())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		if($confirmation=='')
		{
			$data['content'] = load_admin_view('confirmation_view',array('id'=>$id,'url'=>site_url('admin/classified/deletepost/'.$page)),TRUE);
			load_admin_view('template/template_view',$data);
		}
		else
		{
			if($confirmation=='yes')
			{
				if(constant("ENVIRONMENT")=='demo')
				{
					$this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
				}
				else
				{
					if(is_agent())
					{
						$post = $this->classified_model->get_post_by_id($id);
						if($post->created_by != $this->session->userdata('user_id')){

							$this->session->set_flashdata('msg', '<div class="alert alert-danger">'.lang_key('invalid_post_id').'</div>');
						}
						else
						{
							$this->classified_model->delete_post_by_id($id);
							$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('post_deleted').'</div>');

						}

					}
					else
					{
						$this->classified_model->delete_post_by_id($id);
						$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('post_deleted').'</div>');

					}
				}
			}
			redirect(site_url('admin/classified/allposts/'.$page));		
		}		
	}

	#approve a post
	public function approvepost($page='0',$id='',$confirmation='')
	{
		if(!is_admin())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		if(constant("ENVIRONMENT")=='demo')
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
		}
		else
		{
			$this->load->helper('date');
			$format = 'DATE_RFC822';
			$time = time();

			$activation_date = mdate($datestring, $time);
			$expirtion_date  = strtotime('+'.$package->expiration_time.' days',$time);
			$expirtion_date = mdate($datestring, $expirtion_date);

			$data = array();

			$data['publish_time'] 		= $time;
			$data['last_update_time'] 	= $time;
			$data['status'] 			= 1;

			$this->classified_model->update_post_by_id($data,$id);
			$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('post_approved').'</div>');
		}
		redirect(site_url('admin/classified/allposts/'.$page));
	}


	#****************** post functions end *********************#

	public function allsources()
	{
		if(!is_admin())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		$value 				= array();
		$value['posts']     = $this->content_model->get_all_sources();
        $value['title'] 	= lang_key('all_sources');
        $data['title'] 		= lang_key('all_sources');
		$data['content'] 	= load_admin_view('content/allsources_view',$value,TRUE);
		load_admin_view('template/template_view',$data);
	}
	

	public function addsource($id="")
	{
		if(!is_admin())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		$value 				= array();
		$value['action']    = ($id=='')?'new':'edit';
		$value['id']		= $id;
		if($id!='')
		{

			$value['post'] = $this->content_model->get_source_data_by_id($id);
		}

        $value['title'] 		= ($id=='')?lang_key('addsource'):lang_key('edit_source');
        $data['title'] 		= ($id=='')?lang_key('addsource'):lang_key('edit_source');
		$data['content'] 	= load_admin_view('content/addsource_view',$value,TRUE);
		load_admin_view('template/template_view',$data);
	}

	public function savesource()
	{
		if(!is_admin())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		$this->form_validation->set_rules('source_name',lang_key('source_name'),'required|xss_clean');
		$this->form_validation->set_rules('source_type',lang_key('source_type'),'required|xss_clean');
		if($this->input->post('source_type')=='feed')
		$this->form_validation->set_rules('rss_url',lang_key('rss_url'),'required|xss_clean');
		$this->form_validation->set_rules('parent_category',lang_key('parent_category'),'required|xss_clean');
		$this->form_validation->set_rules('auto_grabbing',lang_key('auto_grabbing'),'required|xss_clean');

		if($this->input->post('auto_grabbing')==1)
		{
			$this->form_validation->set_rules('start_on',lang_key('start_on'),'required|xss_clean');
			$this->form_validation->set_rules('grab_duration',lang_key('grab_duration'),'required|xss_clean');
			$this->form_validation->set_rules('item_per_grab',lang_key('item_per_grab'),'required|xss_clean');

		}

		$action = $this->input->post('action');
		$id = $this->input->post('id');

		if ($this->form_validation->run() == FALSE)
		{
			$this->addsource($id);	
		}
		else
		{
			if(constant("ENVIRONMENT")=='demo')
			{
				$this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
				redirect(site_url('admin/content/addsource/'.$id));	
			}
			else
			{
				$data = array();
				$data['source_name'] 	 = $this->input->post('source_name');
				$data['rss_url'] 		 = $this->input->post('rss_url');
				$data['parent_category'] = $this->input->post('parent_category');
				$data['sub_category'] 	 = $this->input->post('sub_category');
				$data['auto_grabbing']   = $this->input->post('auto_grabbing');
				$data['start_on'] 		 = $this->input->post('start_on');
				$data['grab_duration']   = $this->input->post('grab_duration');
				$data['item_per_grab']   = $this->input->post('item_per_grab');

				$time = time();

				$data['last_update_time']   = $time;
				$data['created_by']   		= $this->session->userdata('user_id');
				$data['status']   			= 1;

				if($id=='')
				{
					$data['create_time']   = $time;
					$id = $this->content_model->insert_source_data($data);
					$this->session->set_flashdata('msg','<div class="alert alert-success">'.lang_key('source_added').'</div>');
				}
				else
				{
					$data['create_time']   = $time;
					$this->content_model->update_source_data($data,$id);	
					$this->session->set_flashdata('msg','<div class="alert alert-success">'.lang_key('source_updated').'</div>');				
				}

				redirect(site_url('admin/content/addsource/'.$id));	
			}
		}
	}

	#delete a post
	public function deletesource($page='0',$id='',$confirmation='')
	{
		if(!is_admin())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		if($confirmation=='')
		{
			$data['content'] = load_admin_view('confirmation_view',array('id'=>$id,'url'=>site_url('admin/content/deletesource/'.$page)),TRUE);
			load_admin_view('template/template_view',$data);
		}
		else
		{
			if($confirmation=='yes')
			{
				if(constant("ENVIRONMENT")=='demo')
				{
					$this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
				}
				else
				{
					$this->content_model->delete_source_data_by_id($id);
					$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('source_deleted').'</div>');
				}
			}
			redirect(site_url('admin/content/allsources/'.$page));		
		}		
	}



    public function uploadfeaturedimage()
    {
    	// print_r($_FILES);
    	// die;
        $dir_name 					= 'images/';
        $config['upload_path'] 		= './uploads/'.$dir_name;
        $config['allowed_types'] 	= 'gif|jpg|png|jpeg';
        $config['max_size'] 		= '5120';
        $config['min_width'] 		= '300';
        $config['min_height'] 		= '256';

        $this->load->library('dbcupload', $config);
        $this->dbcupload->display_errors('', '');

        if($this->dbcupload->do_upload('photoimg'))
        {
            $data = $this->dbcupload->data();
            $this->load->helper('date');

            $format = 'DATE_RFC822';
            $time = time();
            #create_rectangle_thumb('./uploads/'.$dir_name.$data['file_name'],'./uploads/thumbs/');

            $media['media_name'] 		= $data['file_name'];
            $media['media_url']  		= base_url().'uploads/'.$dir_name.$data['file_name'];
            $media['create_time'] 		= standard_date($format, $time);
            $media['status']			= 1;

            $status['error'] 	= 0;
            $status['name']	= $data['file_name'];
        }

        else

        {

            $errors = $this->dbcupload->display_errors();

            $errors = str_replace('<p>','',$errors);

            $errors = str_replace('</p>','',$errors);

            $status = array('error'=>$errors,'name'=>'');

        }



        echo json_encode($status);

        die;

    }

    public function featuredimguploader()

    {

        load_admin_view('content/featured_img_uploader_view');

    }

    public function createnews($id="")
    {

        $value 				= array();
        $value['action']    = ($id=='')?'new':'edit';
        $value['id']		= $id;
        if($id!='')
        {

            $value['post'] = $this->content_model->get_news_data_by_id($id);
        }

        $value['title'] 	= ($id=='')?lang_key('create_news'):lang_key('edit_news');
        $data['title'] 		= ($id=='')?lang_key('create_news'):lang_key('edit_news');
        $data['content'] 	= load_admin_view('content/create_news_view',$value,TRUE);
        load_admin_view('template/template_view',$data);



        /*$value 				= array();
        $data['title'] 		= lang_key('create_news');
        $data['content'] 	= load_admin_view('classified/create_news_view',$value,TRUE);
        load_admin_view('template/template_view',$data);*/

    }

    public function addnews()
    {
//        echo '<pre>';print_r($_POST);die;

        $this->form_validation->set_rules('title',lang_key('title'),'required|xss_clean');

        $action = $this->input->post('action');
        $id = $this->input->post('id');

        if ($this->form_validation->run() == FALSE)
        {
            $this->createnews($id);
        }
        else
        {
            if(constant("ENVIRONMENT")=='demo')
            {
                $this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
                redirect(site_url('admin/content/createnews/'.$id));
            }
            else
            {
                $data = array();
                $time = time();
                $data['source_id']      = $this->input->post('source_id');
                $data['category']       = $this->input->post('category');
                $data['sub_category']   = $this->input->post('sub_category');
                $data['title']          = $this->input->post('title');
                $data['description']    = $this->input->post('description');
                $data['link']           = $this->input->post('link');
                $data['media']          = $this->input->post('media');

                $data['manual_creation']= 1;
                $data['grab_action']	= 'none';
                $data['tags']   		= $this->input->post('tags');
                $data['grab_time']   	= $time;
                $data['publish_time']   = $time;
                $data['author']   		= $this->session->userdata('user_id');
                $data['status']   		= 1;
                $data['search_meta'] 	= $data['title'].' '.$data['description'].' '.$data['tags'];

                if($id=='')
                {
                    $data['publish_time']   = $time;
                    $id = $this->content_model->insert_news_data($data);
                    $this->session->set_flashdata('msg','<div class="alert alert-success">'.lang_key('news_added').'</div>');
                }
                else
                {
                    $data['publish_time']   = $time;
                    $this->content_model->update_news_data($data,$id);
                    $this->session->set_flashdata('msg','<div class="alert alert-success">'.lang_key('news_updated').'</div>');
                }

                redirect(site_url('admin/content/createnews/'.$id));

            }
        }
    }

    public function allnews($start='0')
    {
        $value 				= array();
        $data['title'] 		= lang_key('all_posts');
        $data['content'] 	= load_admin_view('content/all_posts_view',$value,TRUE);
        load_admin_view('template/template_view',$data);
    }

    public function allposts_ajax($start='0')
    {
        $value['posts']  	= $this->content_model->get_all_post_based_on_user_type($start,$this->per_page,'create_time','desc');
        $total  			= $this->content_model->get_all_post_based_on_user_type('total',$this->per_page,'create_time','desc');
        $value['pages']		= configPagination('admin/content/allposts_ajax',$total,4,$this->per_page);
        load_admin_view('content/all_posts_ajax_view',$value);
    }

    public function deletenews($page='0',$id='',$confirmation='')
    {

        if($confirmation=='')
        {
            $data['content'] = load_admin_view('confirmation_view',array('id'=>$id,'url'=>site_url('admin/content/deletenews/'.$page)),TRUE);
            load_admin_view('template/template_view',$data);
        }
        else
        {
            if($confirmation=='yes')
            {
                if(constant("ENVIRONMENT")=='demo')
                {
                    $this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
                }
                else
                {
                    $this->content_model->delete_news_data_by_id($id);
                    $this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('news_deleted').'</div>');
                }
            }
            redirect(site_url('admin/content/allnews/'.$page));
        }
    }


    #load  settings , settings are saved as json data
	public function settings($key='global_settings')
	{
		if(!is_admin())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		$this->load->model('options_model');
		
		$settings = $this->options_model->getvalues($key);
		if($settings=='')
		{
			$settings = array();
		}
		$settings = json_encode($settings);		
		$value['settings'] = $settings;
        $data['title'] = lang_key('site_settings');
        $data['content'] = load_admin_view('content/settings_view',$value,TRUE);
		load_admin_view('template/template_view',$data);			
	}
	
	#save webadmin settings
	public function savesettings($key='global_settings')
	{
		if(!is_admin())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		$this->load->model('admin/system_model');
		$this->load->model('options_model');

		foreach($_POST as $k=>$value)
		{
			$rules = $this->input->post($k.'_rules');
			if($rules!='')
			$this->form_validation->set_rules($k,$k,$rules);
		}

		if ($this->form_validation->run() == FALSE)
		{
			$this->businesssettings($key);
		}
		else
		{	
			if(constant("ENVIRONMENT")=='demo')
			{
				$this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
			}
			else
			{
				$data['values'] 	= json_encode($_POST);		
				$res = $this->options_model->getvalues($key);

				if($res=='')
				{
					$data['key']	= $key;			
					$this->options_model->addvalues($data);
				}
				else
					$this->options_model->updatevalues($key,$data);
				$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('data_updated').'</div>');
			}
			redirect(site_url('admin/content/settings/'.$key));
		}	
	}

	public function clearoldnews()
	{
		$value = array();
        $data['title'] = lang_key('clear_old_news');
        $data['content'] = load_admin_view('content/clear_oldnews_view',$value,TRUE);
		load_admin_view('template/template_view',$data);			
	}

	public function clearnews()
	{
		$this->content_model->clearnews();
		if(constant("ENVIRONMENT")=='demo')
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
		}
		else
		{
			$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('news_deleted').'</div>');
		}

		redirect(site_url('admin/content/clearoldnews'));
	}

	public function makefeatured($id='')
	{
		$data = array('featured'=>1);
		$this->content_model->update_news_data($data,$id);
		$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('news_featured').'</div>');
		redirect(site_url('admin/content/allnews'));
	}

	public function removefeatured($id='')
	{
		$data = array('featured'=>0);
		$this->content_model->update_news_data($data,$id);
		$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('news_un_featured').'</div>');
		redirect(site_url('admin/content/allnews'));
	}
	

	public function bulkdeletenews()
    {

        $ids = (isset($_POST['id']))?$_POST['id']:array();

        foreach ($ids as $id) {
        	$this->content_model->delete_news_data_by_id($id);
        }

        echo 'done';
    }

    public function updateoldmedia($key='global_settings')
    {
		if(!is_admin())
		{
			echo lang_key('dont_have_permission');
			die;
		}

		$this->load->model('admin/system_model');
		$this->load->model('options_model');

		foreach($_POST as $k=>$value)
		{
			$rules = $this->input->post($k.'_rules');
			if($rules!='')
			$this->form_validation->set_rules($k,$k,$rules);
		}

		if ($this->form_validation->run() == FALSE)
		{
			$this->businesssettings($key);
		}
		else
		{	
			if(constant("ENVIRONMENT")=='demo')
			{
				$this->session->set_flashdata('msg', '<div class="alert alert-success">Data updated.[NOT AVAILABLE ON DEMO]</div>');
			}
			else
			{
				$old_base_url = $this->input->post('old_base_url');
				$new_base_url = $this->input->post('new_base_url');
				$this->content_model->replace_old_media_url($old_base_url,$new_base_url);
				$this->session->set_flashdata('msg', '<div class="alert alert-success">'.lang_key('data_updated').'</div>');
			}
			redirect(site_url('admin/content/settings/'.$key));
		}
    }
}

/* End of file classified_core.php */
/* Location: ./application/modules/admin/controllers/classified_core.php */