<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of item_page_model
 *
 * @author Igor Ratsun
 */
class item_page_model extends CI_Model implements items {

    protected $resource = array();
    protected $is_clone = FALSE;

    public function init($ids = array()) {
        if (!empty($ids)) {
            if (count($ids) == 1) {
                $this->db->where('id_resource_type_page', intval(reset($ids)));
            } else {
                $this->db->where_in('id_resource_type_page', array_map('intval', $ids));
            }
        }
        $rs = $this->db->
                        select('id_resource_type_page, name')->
                        get('resource_type_page')->result_array();

        // Prepare folders
        foreach ($rs as $key => $value) {
            $this->resource[$value['id_resource_type_page']] = $rs[$key];
        }
    }

    public function get_name($id = 0) {

        return (!empty($this->resource[$id]['name'])) ? $this->resource[$id]['name'] : '';
    }

    public function get_alias($id = 0) {

        return '';
    }

    public function create($name) {
        // Get languages
        $lan = $this->db->
                        select('id_lan')->
                        where('active', TRUE)->
                        get('lan')->result_array();

        // Create main
        $this->db->
                insert('resource_type_page', array('name' => $name, 'alias' => url_title($name)));

        $main_id = $this->db->insert_id();

        if (empty($main_id)) {

            return FALSE;
        }

        // Create translate
        $data = array();
        foreach ($lan as $v) {
            $data[] = array(
                'id_resource_type_page' => $main_id,
                'id_lan' => $v['id_lan']
            );
        }

        if (!empty($data)) {
            $this->db->insert_batch('resource_type_page_data', $data);
        }

        return $main_id;
    }

    public function delete($ids = array()) {
        if (empty($ids)) {

            return FALSE;
        }

        // Clear page data
        $this->db->
                where_in('id_resource_type_page', $ids)->
                delete('resource_type_page_data');

        // Clear main
        $this->db->
                where_in('id_resource_type_page', $ids)->
                delete('resource_type_page');

        return ($this->db->affected_rows() > 0);
    }

    protected function _get_page_data($id) {
        $page = $this->db->
                        select('rtp.id_resource_type_page_template, rtp.alias, rtp.route, rtp.active, IF (rtp.cache, \'checked="checked"\', \'\') cache, IF (rtp.active, \'checked="checked"\', \'\') checked', FALSE)->
                        where('rtp.id_resource_type_page', $id)->
                        get('resource_type_page rtp')->row_array();

        return $page;
    }

    protected function _get_page_seo_data($id) {
        $page_data = $this->db->
                        select('lan.id_lan, lan.name lan_name, rtpd.seo_title, rtpd.seo_keywords, rtpd.seo_description')->
                        join('resource_type_page_data rtpd', 'lan.id_lan = rtpd.id_lan AND rtpd.id_resource_type_page=' . $id, 'left')->
                        where('lan.active', TRUE)->
                        order_by('lan_name', 'ASC')->
                        get('lan')->result_array();

        // prepare data
        foreach ($page_data as &$v) {
            $v['seo_title'] = htmlspecialchars($v['seo_title']);
            $v['seo_keywords'] = htmlspecialchars($v['seo_keywords']);
            $v['seo_description'] = htmlspecialchars($v['seo_description']);
        }
        unset($v);

        return $page_data;
    }

    public function get_content($id = 0) {
        // Acceess check
        if (!$this->rt_user->isAllowed('resmng', 'edit_page_content')) {
            return FALSE;
        }

        // Get page
        $page = $this->_get_page_data($id);

        // Get page seo data
        $page_seo_data = $this->_get_page_seo_data($id);

        if (empty($page) && empty($page_seo_data)) {

            return FALSE;
        }

        // Prepare data
        $page_template = $this->get_page_templates();
        foreach ($page_template as $v) {
            $v['selected'] = ($v['id_resource_type_page_template'] == $page['id_resource_type_page_template']) ? 'selected="selected"' : '';
            $content['rpt_options'][] = $v;
        }
        $content['seo_lang_title'] = $page_seo_data;
        $content['seo_lang_data'] = $page_seo_data;
        $content['seo_id'] = $id;
        $content = array_merge($content, $page);

        return $this->parser->parse('resmng/item_page_content', array_merge($content, $this->lang->load('resmng/item_page')), TRUE);
    }

    protected function get_page_templates() {
        if (!$this->rt_user->isAllowed('resmng', 'private')) {
            $this->db->where('r.private', 0);
        }
        $q = $this->db->
                        select('rpt.id_resource_type_page_template, rpt.name')->
                        where('rpt.id_resource_type_page_template = r.id_item')->
                        where('r.id_resource_type', 2)->
                        where('r.deleted', FALSE)->
                        get('resource_type_page_template rpt, resource r')->result_array();
        // Prepare data
        $rs = array();
        foreach ($q as $v) {
            $rs[$v['id_resource_type_page_template']] = $v;
        }
        
        return $rs;
    }

    public function set_name($id = 0, $name = '') {
        // Update name
        $this->db->
                where('id_resource_type_page', intval($id))->
                update('resource_type_page', array('name' => $name));

        return ($this->db->affected_rows() > 0);
    }

    public function set_content($id = 0) {
        // Acceess check
        if (!$this->rt_user->isAllowed('resmng', 'edit_page_content')) {
            return FALSE;
        }

        // Update main data
        $this->load->helper('url');
        $data = array(
            'alias' => url_title($this->input->post('alias'), 'dash', TRUE),
            'cache' => ($this->input->post('cache')) ? 1 : 0,
            'active' => ($this->input->post('active')) ? 1 : 0
        );

        $page_templates = $this->get_page_templates();
        if (isset($page_templates[$this->input->post('id_resource_type_page_template')])) {
            $data['id_resource_type_page_template'] = intval($this->input->post('id_resource_type_page_template'));
        }
        if ($this->is_clone || $this->rt_user->isAllowed('resmng', 'private')) {
            $data['route'] = $this->input->post('route');
        }

        $this->db->
                where('id_resource_type_page', $id)->
                update('resource_type_page', $data);

        // Clear cache
        $dir = ($this->config->item('cache_path')) ? : APPPATH . 'cache';
        foreach (scandir($dir) as $item) {
            if (preg_match('/' . $this->input->post('alias') . '_.*/', $item)) {
                @unlink($dir . DIRECTORY_SEPARATOR . $item);
            }
        }

        $seo_title = $this->input->post('seo_title');
        $seo_keywords = $this->input->post('seo_keywords');
        $seo_description = $this->input->post('seo_description');

        // Prepare data
        $insert = array();
        foreach ($seo_title as $id_lan => $data) {
            $insert[] = array(
                'id_resource_type_page' => $id,
                'id_lan' => intval($id_lan),
                'seo_title' => $data,
                'seo_keywords' => $seo_keywords[$id_lan],
                'seo_description' => $seo_description[$id_lan]
            );
        }
        if (empty($insert)) {
            return FALSE;
        }

        // Clear old data
        $this->db->where('id_resource_type_page', $id)->delete('resource_type_page_data');

        $this->db->insert_batch('resource_type_page_data', $insert);

        return $this->db->insert_id();
    }

    public function clone_item($id, $parent_id = NULL) {
        $this->is_clone = TRUE;
        $name = $this->get_name($id);
        if (is_null($parent_id)) {
            $this->load->helper('string');
            $name = increment_string($name, '_');
        }
        $new_id = $this->create($name);
        $page_data = $this->_get_page_data($id);
        $page_seo_data = $this->_get_page_seo_data($id);

        if (!empty($new_id) && !empty($page_data) && !empty($page_seo_data)) {
            // Prepare data
            $this->load->helper('string');
            $_POST['alias'] = increment_string($page_data['alias'], '_');
            $_POST['id_resource_type_page_template'] = $page_data['id_resource_type_page_template'];
            $_POST['route'] = $page_data['route'];
            $_POST['cache'] = $page_data['cache'];
            $_POST['active'] = $page_data['active'];
            foreach ($page_seo_data as $row) {
                $_POST['seo_title'][$row['id_lan']] = htmlspecialchars_decode($row['seo_title']);
                $_POST['seo_keywords'][$row['id_lan']] = htmlspecialchars_decode($row['seo_keywords']);
                $_POST['seo_description'][$row['id_lan']] = htmlspecialchars_decode($row['seo_description']);
            }

            $this->set_content($new_id);

            return $new_id;
        }

        return FALSE;
    }

}
