<?php defined('SYSPATH') OR die('No Direct Script Access');
    
    class Controller_Feed extends Controller_Website
    {
        public function action_index()
        {
            $view = View::factory('input_feed');
            $this->template->content = $view;
        }
        
        public function action_show()
        {
            $company_content = array();
            $user_content = array();
            
            $user_id = plato::get_user();
            $users = ORM::factory("User")->find($user_id);
            $feeds = $users->feeds->find_all();
            $company = $users->company;
            
            $feedCompanyTrue = ORM::factory("Feed")->where("to_company", "=", true)->find_all();
            
            foreach($feedCompanyTrue as $fct)
            {
                $companyIdUser = $fct->publisher;            
                if ($companyIdUser->company_id == $company->id)
                {
                    $eTime = date("d/m/Y H:i:s", strtotime($fct->event_time));
                    $company_content[] = array("publisher" => $companyIdUser->username, "message" => $fct->message, "event_time" => $eTime);
                }
            }
            
            foreach($feeds as $fiid)
            {
                $eTime = date('d/m/Y H:i:s', strtotime($fiid->event_time));
                $user_content[] = array("publisher" => $fiid->publisher, "message" => $fiid->message, "event_time" => $eTime);
            }
            
            $view = View::factory("feed");
            $view->company_content = $company_content;
            $view->user_content = $user_content;
            
            $this->template->content = View::factory('input_feed') . $view;
        }
        
        public function action_input()
        {            
            if(isset($_POST["submit"]))
            {                
                $pt = "PublishCompany";
                $readers_arr = NULL;
                
                if (isset($_POST["publish_type"]) && $_POST["publish_type"] == 1)
                {
                    $pt = "PublishUserList";
                    $feed_readers = $_POST["feed_readers"];
                    
                    if(!empty($feed_readers))
                    {
                        $readers_arr = array_map('trim',explode(",",$feed_readers));
                    }
                }
                
                PublishEvent::publish(Enum::get($pt), plato::get_user(), $_POST["message"], $readers_arr);
                $this->request->redirect("feed/show");
            }
            else
            {
                $this->request->redirect("feed/show");
            }            
        }
    }
?>