<?php if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Posts extends MY_Controller
{
    public function __construct()
    {
        define("HOOSK_ADMIN", 1);
        parent::__construct();
        $this->load->model('Cmap_model');
        $this->load->helper(array('admincontrol', 'url', 'hoosk_admin', 'file', 'form'));
        $this->load->library('session');
        define('LANG', $this->data['settings']->siteLang);
        $this->lang->load('admin', LANG);
        //Define what page we are on for nav
        $this->data['current'] = $this->uri->segment(2);
        //check session exists
        Admincontrol_helper::is_logged_in($this->session->userdata('userName'));
        $this->load->helper('general');
    }

    public function index()
    {
        $this->load->library('pagination');
        $result_per_page = 15;  // the number of result per page
        $config['base_url'] = BASE_URL . '/admin/posts/';
        $config['total_rows'] = $this->Cmap_model->countPosts();
        $config['per_page'] = $result_per_page;
        $config['last_link'] = false;
        $config['first_link'] = false;
        $config['suffix'] = '?term=' . getSearchTerm();

        $this->pagination->initialize($config);

        //Get posts from database
        $this->data['posts'] = $this->post->getPosts($result_per_page, $this->uri->segment(3))
            ->select("p.*, if(u.userName = '', if(u.nickname='', u.userID, u.nickname), u.userName) userName, '' as categoryTitle, c.categorySlug, '' as pageTitle")->get()->result_array();
        $this->category->getTableCategoryTitle($this->data['posts']);
        $this->page->getTablePageTitle($this->data['posts']);
        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);
        $this->load->view('admin/posts', $this->data);
    }

    public function addPost()
    {
        $this->data['categories'] = array_merge([['categoryID' => 0, 'categoryTitle' => 'Select category']], $this->Cmap_model->getCategories());
        $this->data['pages'] = array_merge([['pageID' => 0, 'pageTitle' => 'Select page']], $this->Cmap_model->getPagesAll());
        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);
        $this->load->view('admin/post_new', $this->data);
    }

    public function confirm()
    {
        //Load the form validation library
        $this->load->library('form_validation');
        //Set validation rules
        // $this->form_validation->set_rules('postURL', 'post URL', 'trim|alpha_dash|required|is_unique[cm_post.postURL]');
        $this->form_validation->set_rules('postTitle', 'post title', 'trim|required');
        $this->form_validation->set_rules('postExcerpt', 'post excerpt', 'trim|required');

        if ($this->form_validation->run() == false) {

            //Validation failed
            $this->addPost();
        } else {
            //Validation passed
            if ($this->input->post('postImage')) {
                //path to save the image
                $path_upload = $_SERVER["DOCUMENT_ROOT"] . '/uploads/';
                $path_images = $_SERVER["DOCUMENT_ROOT"] . '/images/' . date('Y/m/d/');

                if (!file_exists($path_images) && !mkdir($path_images, 0775, true)) {
                    die('Failed to create folders...');
                }
                //moving temporary file to images folder
                rename($path_upload . $this->input->post('postImage'), $path_images . $this->input->post('postImage'));
            }

            if ($this->input->post('postThumb') || $this->input->post('postImageExternal')) {
                //path to save the image
                $path_upload = $_SERVER["DOCUMENT_ROOT"] . '/uploads/';
                $path_images = $_SERVER["DOCUMENT_ROOT"] . '/thumbs/' . date('Y/m/d/');

                if (!file_exists($path_images) && !mkdir($path_images, 0775, true)) {
                    die('Failed to create folders...');
                }
                //moving temporary file to images folder
                if ($this->input->post('postImageExternal')) {
                    $this->load->helper('string');
                    $_POST['postThumb'] = random_string() . '.' . pathinfo(parse_url($this->input->post('postImageExternal'))['path'], PATHINFO_EXTENSION);
                    file_put_contents(
                        $path_images . $this->input->post('postThumb'),
                        file_get_contents($this->input->post('postImageExternal'))
                    );
                } else {
                    rename($path_upload . $this->input->post('postThumb'), $path_images . $this->input->post('postThumb'));
                }
            }

            //Add the post
            $this->load->library('Sioen');
            $this->post->save();
            //Return to post list
            redirect(BASE_URL . '/admin/posts', 'refresh');
        }
    }

    public function editPost()
    {
        $this->data['categories'] = array_merge([['categoryID' => 0, 'categoryTitle' => 'Select category']], $this->Cmap_model->getCategories());
        $this->data['pages'] = array_merge([['pageID' => 0, 'pageTitle' => 'Select page']], $this->Cmap_model->getPagesAll());
        //Get post details from database
        $this->data['posts'] = $this->post->getPost($this->uri->segment(4))->get()->result_array();
        $this->data['posts'][0]['postTag'] = json_encode($this->post->getPostTag($this->uri->segment(4))['tag']);
        $this->category->getTableCategoryTitle($this->data['posts']);
        $this->page->getTablePageTitle($this->data['posts']);

        $this->load->model('user_model', 'user');
        $this->data['users'] = $this->user->getAdminSiteUsers();
        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);
        $this->data['video'] = 0;
        if ($video = $this->post->getPostVideo($this->uri->segment(4))) {
            $this->data['video'] = 1;
            $this->data['posts'][0]['postContentHTML'] .= $this->load->view('admin/youtube-iframe', $video, true);
        }
        $this->data['posts'][0]['articleURL'] = getPostLink($this->data['posts'][0], 'church');
        $this->load->view('admin/post_edit', $this->data);
    }

    public function edited()
    {
        //Load the form validation library
        $this->load->library('form_validation');
        //Set validation rules
        // $this->form_validation->set_rules('postURL', 'post URL', 'trim|alpha_dash|required|is_unique[cm_post.postURL.postID.'.$this->uri->segment(4).']');
        $this->form_validation->set_rules('postTitle', 'post title', 'trim|required');

        if ($this->form_validation->run() == false) {
            //Validation failed
            $this->editPost();
        } else {
            //Validation passed
            if ($this->input->post('postImage')) {
                //path to save the image
                $path_upload = $_SERVER["DOCUMENT_ROOT"] . '/uploads/';
                $path_images = $_SERVER["DOCUMENT_ROOT"] . '/images/' . date('Y/m/d/');
                //moving temporary file to images folder
                if (file_exists($path_images) || mkdir($path_images, 0775, true)) {
                    rename($path_upload . $this->input->post('postImage'), $path_images . $this->input->post('postImage'));
                }
            }

            if ($this->input->post('postThumb')) {
                //path to save the image
                $path_upload = $_SERVER["DOCUMENT_ROOT"] . '/uploads/';
                $path_images = $_SERVER["DOCUMENT_ROOT"] . '/thumbs/' . date('Y/m/d/');
                //moving temporary file to images folder
                if (file_exists($path_images) || mkdir($path_images, 0775, true)) {
                    rename($path_upload . $this->input->post('postThumb'), $path_images . $this->input->post('postThumb'));
                }
            }
            //Update the post
            $this->load->library('Sioen');
            if($this->input->post('published') == '0') {
                $this->schedule([
                    'postID' => $this->uri->segment(4),
                    'run_at'  => date('Y-m-d H:i:s', strtotime($this->input->post('dateReserved'))),
                    'userID'  => $this->session->userdata('userID')
                ]);
            }            
            $this->post->update($this->uri->segment(4));
            //Return to post list
            redirect(BASE_URL . '/admin/posts', 'refresh');
        }
    }


    public function delete()
    {
        if ($this->input->post('deleteid')) :
            $this->Cmap_model->removePost($this->input->post('deleteid'));
            redirect(BASE_URL . '/admin/posts');
        else :
            $this->data['form'] = $this->Cmap_model->getPost($this->uri->segment(4));
            $this->load->view('admin/post_delete.php', $this->data);
        endif;
    }

    public function postSearch()
    {
        $this->Cmap_model->postSearch($this->input->post('term'));
    }

    public function schedule($edit = null)
    {
        $data = is_null($edit) ? array(
            'postID' => $this->input->post('postID'),
            'run_at'  => $this->input->post('run_at'),
            'userID'  => $this->session->userdata('userID')
        ) : $edit;

        $this->db->where('postID', $data['postID'])->delete('cm_post_schedule');
        $this->db->insert('cm_post_schedule', $data);
        if(!$edit) {
            $this->output
            ->set_status_header(200)
            ->set_content_type('application/json')
            ->set_output(json_encode(array('code' => 200)));
        }        
    }
}
