<?php

require __DIR__ . '/Hoosk_model.php';

class Cmap_model extends Hoosk_model
{
    public function __construct()
    {
        parent::__construct();
    }

    /*     * *************************** */
    /*     * ** Setting Role Querys ************ */
    /*     * *************************** */
    public function countRoles()
    {
        return $this->db->count_all('cm_setting_roles');
    }

    public function getRoles($limit, $offset = 0)
    {
        // Get a list of all user accounts
        $query = $this->db->order_by("created_at", "desc")
            ->limit($limit, $offset)->get('cm_setting_roles');
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
        return array();
    }

    public function getRole($id)
    {
        // Get the user details
        $query = $this->db->where("roleID", $id)->get('cm_setting_roles');
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
        return array();
    }

    public function createRole()
    {
        // Create the user account
        $data = array(
            'name' => $this->input->post('name'),
            'slug' => $this->input->post('slug')
        );
        $this->db->insert('cm_setting_roles', $data);
    }

    public function updateRole($id)
    {
        // update the user account
        $data = array(
            'name' => $this->input->post('name'),
            'slug' => $this->input->post('slug')
        );
        $this->db->where('roleID', $id);
        $this->db->update('cm_setting_roles', $data);
    }

    public function removeRole($id)
    {
        // Delete a user account
        $this->db->delete('cm_setting_roles', array('roleID' => $id));
    }

    function roleSearch($term)
    {
        $this->db->select("*");
        $this->db->like("name", $term);
        // $this->db->limit($limit, $offset);
        $query = $this->db->get('cm_setting_roles');
        if ($term == "") {
            $this->db->limit(15);
        }
        if ($query->num_rows() > 0) {
            $results = $query->result_array();
            foreach ($results as $r) :
                echo '<tr>';
                echo '<td>' . $r['name'] . '</td>';
                echo '<td>' . $r['slug'] . '</td>';
                echo '<td>' . $r['created_at'] . '</td>';
                echo '<td class="td-actions"><a href="' . BASE_URL . '/admin/settings/roles/edit/' . $r['roleID']
                    . '" class="btn btn-small btn-success"><i class="fa fa-pencil"> '
                    . '</i></a> <a data-toggle="modal" data-target="#ajaxModal" class="btn btn-danger btn-small" href="'
                    . BASE_URL . '/admin/settings/roles/delete/' . $r['roleID'] . '"><i class="fa fa-remove"> </i></a></td>';
                echo '</tr>';
                echo '</tr>';
            endforeach;
        } else {
            echo "<tr><td colspan='5'><p>" . $this->lang->line('no_results') . "</p></td></tr>";
        }
    }

    public function categorySearch($term)
    {
        $this->load->helper('sql_search');
        $this->db->from('cm_category');
        $this->db->select("*");
        $this->db->like("categoryTitle", $term);
        $query = $this->db->query($this->db->get_compiled_select() . ' or ' . getSqlCho('categoryTitle', $term));
        if ($term == "") {
            $this->db->limit(15);
        }
        if ($query->num_rows() > 0) {
            $results = $query->result_array();
            foreach ($results as $p) :
                echo '<tr>';
                echo '<td>' . $p['categoryTitle'] . '</td>';
                echo '<td class="td-actions"><a href="' . BASE_URL . '/admin/posts/categories/edit/' . $p['categoryID'] . '" class="btn btn-small btn-success"><i class="fa fa-pencil"> </i></a> <a data-toggle="modal" data-target="#ajaxModal" class="btn btn-danger btn-small" href="' . BASE_URL . '/admin/posts/categories/delete/' . $p['categoryID'] . '"><i class="fa fa-remove"></i></a></td>';
                echo '</tr>';
            endforeach;
        } else {
            echo "<tr><td colspan='5'><p>" . $this->lang->line('no_results') . "</p></td></tr>";
        }
    }

    public function countUsers()
    {
        $term = getSearchTerm();
        return $this->db->from('cm_user u')->select("userName, r.name groupName, email, userID")
            ->join('cm_setting_roles r', 'u.roleID = r.roleID', 'left')
            ->like("userName", $term)
            ->or_like('r.name', $term)->count_all_results();
    }

    public function getUsers($limit, $offset = 0)
    {
        // Get a list of all user accounts
        $term = getSearchTerm();
        $this->load->helper('sql_search');
        $query = $this->db->from('cm_user u')->select("userName, if(r.name is Null, 'None', r.name) groupName, email, userID")
            ->join('cm_setting_roles r', 'u.roleID = r.roleID', 'left')
            ->like("userName", $term)
            ->or_like('r.name', $term);
        $query = $this->db->query($this->db->get_compiled_select() . ($term ? ' or ' . getSqlCho('userName', $term) : '') . ' order by u.dateUpdated desc');
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
        return array();
    }

    public function userSearch($term)
    {
        $this->load->helper('sql_search');
        $query = $this->db->from('cm_user u')->select("userName, r.name groupName, email, userID")
            ->join('cm_setting_roles r', 'u.roleID = r.roleID', 'left')
            ->like("userName", $term)
            ->or_like('r.name', $term);
        $query = $this->db->query($this->db->get_compiled_select() . ($term ? ' or ' . getSqlCho('userName', $term) : '') . ' order by u.dateUpdated desc');
        if ($term == "") {
            $this->db->limit(15);
        }
        if ($query->num_rows() > 0) {
            $results = $query->result_array();
            foreach ($results as $u) :
                echo '<tr>';
                echo '<td>' . $u['userName'] . '</td>';
                echo '<td>' . $u['groupName'] . '</td>';
                echo '<td>' . $u['email'] . '</td>';
                echo '<td class="td-actions"><a href="' . BASE_URL . '/admin/users/edit/' . $u['userID'] . '" class="btn btn-small btn-success"><i class="fa fa-pencil"> </i></a> <a data-toggle="modal" data-target="#ajaxModal" class="btn btn-danger btn-small" href="' . BASE_URL . '/admin/users/delete/' . $u['userID'] . '"><i class="fa fa-remove"> </i></a></td>';
                echo '</tr>';
            endforeach;
        } else {
            echo "<tr><td colspan='5'><p>" . $this->lang->line('no_results') . "</p></td></tr>";
        }
    }

    protected function addPostCategory($postID, $categories)
    {
        $tmp = [];
        $this->db->where('postID', $postID)->delete('cm_post_category');
        if (count($categories)) {
            return $this->db->insert_batch('cm_post_category', array_filter(array_map(function ($category) use ($postID) {
                return ['postID' => $postID, 'categoryID' => $category];
            }, $categories), function ($c) use (&$tmp) {
                $isDup = $c['categoryID'] ? false : true;
                if (!$isDup) {
                    foreach ($tmp as $t) {
                        if ($t['categoryID'] == $c['categoryID']) {
                            $isDup = true;
                            break;
                        }
                    }
                }
                array_push($tmp, $c);
                if (!$isDup) {
                    return $c;
                }
            }));
        }
    }

    protected function addPostPage($postID, $pages)
    {
        $tmp = [];
        $this->db->where('postID', $postID)->delete('cm_post_page');
        if (count($pages)) {
            return $this->db->insert_batch('cm_post_page', array_filter(array_map(function ($page) use ($postID) {
                return ['postID' => $postID, 'pageID' => $page];
            }, $pages), function ($c) use (&$tmp) {
                $isDup = $c['pageID'] ? false : true;
                if (!$isDup) {
                    foreach ($tmp as $t) {
                        if ($t['pageID'] == $c['pageID']) {
                            $isDup = true;
                            break;
                        }
                    }
                }
                array_push($tmp, $c);
                if (!$isDup) {
                    return $c;
                }
            }));
        }
    }

    public function getPostByCategoryId($categoryID, $limit = 15, $offset = 0)
    {
        $rows = [];
        $this->db->select("cm_post.*, cm_category.categoryTitle");
        $this->db->where("cm_category.categoryID", $categoryID);
        $this->db->join('cm_category', 'cm_category.categoryID = cm_post.categoryID or cm_post.categoryID = 0', 'left');
        $this->db->order_by("cm_post.postID", "desc");
        $this->db->limit($limit, $offset);
        return $this->db->get('cm_post')->result();
    }

    public function getPostByPageId($pageID, $limit = 15, $offset = 0)
    {
        $rows = [];
        $this->db->select("cm_post.*, cm_category.categoryTitle");
        if (is_array($pageID)) {
            $this->db->where_in('cm_post.pageID', $pageID);
        } else {
            $this->db->where('cm_post.pageID', $pageID);
        }
        $this->db->join('cm_category', 'cm_category.categoryID = cm_post.categoryID or cm_post.categoryID = 0', 'left');
        $this->db->order_by("cm_post.postID", "desc");
        $this->db->group_by("cm_post.postID");
        $this->db->limit($limit, $offset);
        return $this->db->get('cm_post')->result();
    }

    public function createUser()
    {
        // Create the user account
        $data = array(
            'userName' => $this->input->post('username'),
            'email' => $this->input->post('email'),
            'password' => md5($this->input->post('password') . SALT),
            'roleID' => $this->input->post('role'),
            'name' => $this->input->post('name'),
            'gender' => $this->input->post('gender'),
            'mobile' => $this->input->post('mobile')
        );
        $this->db->insert('cm_user', $data);
    }

    public function updateUser($id)
    {
        // update the user account
        $data = array(
            'email' => $this->input->post('email'),
            'email' => $this->input->post('email'),
            'roleID' => $this->input->post('role'),
            'name' => $this->input->post('name'),
            'gender' => $this->input->post('gender'),
            'mobile' => $this->input->post('mobile')
        );

        if ($this->input->post('password')) {
            $data['password'] = md5($this->input->post('password') . SALT);
        }

        $this->db->where('userID', $id);
        $this->db->update('cm_user', $data);
    }

    public function createPost()
    {
        $categoryID = 0;
        $data = array(
            'postTitle' => $this->input->post('postTitle'),
            'categoryID' => $categoryID,
            // 'postURL' => $this->input->post('postURL'),
            // 'postContent' => $this->input->post('content'),
            'postContentHTML' => $this->input->post('content'),
            'postExcerpt' => $this->input->post('postExcerpt'),
            'published' => $this->input->post('published'),
            'datePosted' => date('Y-m-d H:i:s', strtotime($this->input->post('datePosted'))),
            'dateUpdated' => date('Y-m-d H:i:s'),
            'unixStamp' => $this->input->post('unixStamp'),
        );
        if ($this->input->post('postImage') != "") {
            $data['postImage'] = $this->input->post('postImage');
        }
        $this->db->insert('cm_post', $data);
        $insertID = $this->db->insert_id();

        $this->addPostCategory($insertID, $this->input->post('categories') ? explode(',', $this->input->post('categories')) : []);
        $this->addPostPage($insertID, $this->input->post('pages') ? explode(',', $this->input->post('pages')) : []);
        $this->db->where('postID', $insertID)->update('cm_post', array('postURL' => $insertID));
    }


    public function updatePost($id)
    {
        $categoryID = 0;
        $this->addPostCategory($id, $this->input->post('categories') ? explode(',', $this->input->post('categories')) : []);
        $this->addPostPage($id, $this->input->post('pages') ? explode(',', $this->input->post('pages')) : []);

        $data = array(
            'postTitle' => $this->input->post('postTitle'),
            'categoryID' => $categoryID,
            // 'postURL' => $this->input->post('postURL'),
            'postContentHTML' => $this->input->post('content'),
            'postExcerpt' => $this->input->post('postExcerpt'),
            'published' => $this->input->post('published'),
            'datePosted' => date('Y-m-d H:i:s', strtotime($this->input->post('datePosted'))),
            'dateUpdated' => date('Y-m-d H:i:s'),
            'unixStamp' => $this->input->post('unixStamp'),
        );
        if ($this->input->post('postImage') != "") {
            $data['postImage'] = $this->input->post('postImage');
        }
        $this->db->where("postID", $id);
        $this->db->update('cm_post', $data);
    }
}
