<?php

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

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

    protected $page_templates = array();

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

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

    public function get_name($id = 0) {

        return (!empty($this->page_templates[$id]['name'])) ? $this->page_templates[$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_template', array('name' => $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_template' => $main_id,
                'id_lan' => $v['id_lan']
            );
        }

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

        return $main_id;
    }

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

            return FALSE;
        }
        
        // Clear translate
        $this->db->
                where_in('id_resource_type_page_template', $ids)->
                delete('resource_type_page_template_translate');

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

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

    protected function _get_data($id = 0) {
        $sql = $this->db->
                select('lan.id_lan, lan.name, rpt.content')->
                join('resource_type_page_template_translate rpt', 'rpt.id_lan = lan.id_lan AND rpt.id_resource_type_page_template = ' . $id, 'left')->
                where('active', TRUE)->
                get('lan')->result_array();
        
        // prepare data
        foreach ($sql as &$v) {
            $v['content'] = htmlspecialchars($v['content']);
        }
        unset($v);
        
        return $sql;
    }


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

        $content = array(
            'item'          => $this->_get_data($id),
            'mime_types' => $this->get_prepared_mime_types($id)
        );

        return $this->parser->parse('resmng/item_page_template_content', $content, TRUE);
    }

    public function set_name($id = 0, $name = '') {
        // Update name
        $this->db->
                where('id_resource_type_page_template', intval($id))->
                update('resource_type_page_template', 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_template')) {
            return FALSE;
        }
        
        $id = (int) $id;
        $content = $this->input->post('content');
        $mime_type = $this->input->post('mime_type');
        
        // Prepare data
        $insert = array();
        foreach ($content as $id_lan => $data) {
            $insert[] = array(
                'id_resource_type_page_template' => $id,
                'id_lan' => intval($id_lan),
                'content' => $data,
                
            );
        }
        if (empty($insert)) {
            return FALSE;
        }

        // Update mime type
        $this->db
            ->where('id_resource_type_page_template', $id)
            ->update('resource_type_page_template', ['mime_type' => $mime_type]);
        
        // Clear old data
        $this->db->where('id_resource_type_page_template', $id)->delete('resource_type_page_template_translate');
        
        $this->db->insert_batch('resource_type_page_template_translate', $insert); 

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

    public function clone_item($id, $parent_id = NULL) {
        $name = $this->get_name($id);
        if (is_null($parent_id)) {
            $this->load->helper('string');
            $name = increment_string($name, '_');
        }
        $new_id = $this->create($name);
        $data = $this->_get_data($id);
        
        if (!empty($new_id) && !empty($data)) {
            foreach ($data as $row) {
                $_POST['content'][$row['id_lan']] = htmlspecialchars_decode($row['content']);
            }
            $this->set_content($new_id);
            
            return $new_id;
        }
        
        return FALSE;
    }

    /**
     *  Get prepared mime types
     *
     * @param integer $id
     * @return array
     */
    public function get_prepared_mime_types($id = 0) {
        // get current mime type
        $current_mime_type = $this->get_template_mime_type_id($id);

        // prepare result
        $result = [];
        foreach ($this->get_mime_types() as $id => $mime_type){
            $result[] = [
               'value'  => $id,
               'label'  => $mime_type['name'],
               'active' => ($id == $current_mime_type),
            ];
        }

        return $result;
    }

    /**
     *  Get mime types
     *
     * @return array
     */
    public function get_mime_types() {
        // load config
        $this->config->load('resmng/mime_type');

        return $this->config->item('mime_type');
    }

    /**
     * Get template mime type
     *
     * @param int $id
     * @return int
     */
    public function get_template_mime_type_id($id) {
        
        $response = $this->db
            ->select('mime_type')
            ->where('id_resource_type_page_template', (int) $id)
            ->get('resource_type_page_template')
            ->row_array();

        return (empty($response['mime_type'])) ? 1 : $response['mime_type'];
    }
}

