<?php

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

class photo_item {

    protected $photo_id = NULL;
    protected $photo = NULL;
    protected $strings = array();
    protected $lang_strings = array();
    protected $main_db_data_length;
    protected $lang_db_data_length;

    public function __construct() {
        $CI = & get_instance();
        $this->main_db_data_length = $CI->config->item('main_db_data_length');
        $this->lang_db_data_length = $CI->config->item('lang_db_data_length');
    }

    public function set_id($id) {

        $this->photo_id = intval($id);
    }

    public function set_photo($name) {
        if (!empty($this->main_db_data_length[$name])) {
            $name = mb_substr($name, 0, $this->main_db_data_length[$name]);
        }

        $this->photo = $name;
    }

    public function set_string($key, $value, $escape = TRUE) {
        if (!empty($this->main_db_data_length[$key])) {
            $value = mb_substr($value, 0, $this->main_db_data_length[$key]);
        }

        $str = new stdClass();
        $str->key = $key;
        $str->value = ($escape) ? $value : $value;

        $this->strings[] = $str;
    }

    public function set_lang_string($key, $value, $id_lan, $escape = TRUE) {
        if (!empty($this->lang_db_data_length[$key])) {
            $value = mb_substr($value, 0, $this->lang_db_data_length[$key]);
        }

        $str = new stdClass();
        $str->key = $key;
        $str->value = ($escape) ? $value : $value;
        $str->id_lan = intval($id_lan);

        if (empty($str->key) || empty($str->id_lan)) {
            $error = 'alphagallery_admin_model. $str->key and $str->id_lan can\'t be empty. $str->id_lan=' . $str->id_lan . ' $str->key=' . $str->key;
            log_message('error', $error);

            return FALSE;
        } else {
            $this->lang_strings[] = $str;
        }

        return TRUE;
    }

    public function get_id() {

        return $this->photo_id;
    }

    public function get_photo() {

        return $this->photo;
    }

    public function get_string($key) {
        foreach ($this->strings as $value) {
            if ($value->key == $key) {

                return $value->value;
            }
        }

        return FALSE;
    }

    public function get_lang_string($key, $id_lan) {
        foreach ($this->lang_strings as $value) {
            if ($value->key == $key && $value->id_lan == $id_lan) {

                return $value->value;
            }
        }

        return FALSE;
    }

    public function get_strings() {

        return $this->strings;
    }

    public function get_lang_strings() {

        return $this->lang_strings;
    }

}

/**
 * Description of alphagallery_admin_model
 *
 * @author Igor Ratsun
 */
class alphagallery_admin_model extends CI_Model {

    protected $table = NULL;
    protected $lang_table = NULL;
    protected $primery_key = NULL;

    public function __construct() {
        $this->load->config('alphagallery/config');
    }

    public function set_pkey($pkey) {

        $this->primery_key = $pkey;
    }

    public function set_table($table) {

        $this->table = $table;
    }

    public function set_lang_table($table) {

        $this->lang_table = $table;
    }

    public function save(photo_item $item) {
        // Save main data
        $main_data = array(
            'photo' => $item->get_photo()
        );
        foreach ($item->get_strings() as $str) {
            $main_data[$str->key] = $str->value;
        }
        if (is_null($item->get_id())) {
            // Insert new
            $this->db->insert($this->table, $main_data);
            $item->set_id($this->db->insert_id());
        } else {
            // Update
            $this->db->
                    where($this->primery_key, $item->get_id())->
                    update($this->table, $main_data);
        }

        // Save lang data
        $lang_strings = $item->get_lang_strings();
        if (!empty($lang_strings)) {
            $lang_data = array();
            foreach ($lang_strings as $value) {
                $lang_data[$value->id_lan][$value->key] = $value->value;
                $lang_data[$value->id_lan]['id_lan'] = $value->id_lan;
                $lang_data[$value->id_lan][$this->primery_key] = $item->get_id();
            }
            // Clear old data
            $this->db->
                    where($this->primery_key, $item->get_id())->
                    delete($this->lang_table);
            // Save new data
            foreach ($lang_data as $data) {
                $this->db->insert($this->lang_table, $data);
            }
        }

        return $item->get_id();
    }

    public function delete($id) {
        $item = $this->fetch_by_id($id);
        if ($item == FALSE) {

            return FALSE;
        }

        $photo = trim($this->config->item('photo_path'), '/') . '/' . $item->get_photo();
        $exists = file_exists($photo);
        if (!$exists || ($exists && is_dir($photo)) || ($exists && unlink($photo))) {
            // Delete lang
            $this->db->
                    where($this->primery_key, $item->get_id())->
                    delete($this->lang_table);
            // Delete main
            $this->db->
                    where($this->primery_key, $item->get_id())->
                    delete($this->table);

            return TRUE;
        }

        return FALSE;
    }

    protected function _make_alias($table, $field) {

        return substr('fil_' . md5($table . $field), 0, 8);
    }

    protected function _fetch_data() {
        $items = array();

        // Prepare select
        $main_db_data = $this->config->item('main_db_data');
        array_push($main_db_data, $this->primery_key);
        array_push($main_db_data, 'photo');
        foreach ($main_db_data as &$v) {
            $v = $this->table . '.' . $v . ' ' . $this->_make_alias($this->table, $v);
        }
        unset($v);
        $lang_db_data = $this->config->item('lang_db_data');
        array_push($lang_db_data, 'id_lan');
        foreach ($lang_db_data as &$v) {
            $v = $this->lang_table . '.' . $v . ' ' . $this->_make_alias($this->lang_table, $v);
        }
        unset($v);

        $data = $this->db->
                        select(array_merge($main_db_data, $lang_db_data))->
                        join($this->lang_table, $this->lang_table . '.' . $this->primery_key . '=' . $this->table . '.' . $this->primery_key, 'left')->
                        order_by('view_order', 'ASC')->
                        get($this->table)->result_array();

        if (!empty($data)) {
            $main_data_id = array();
            foreach ($data as $record) {
                // Set main data
                if (!in_array($record[$this->_make_alias($this->table, $this->primery_key)], $main_data_id)) {
                    $item = new photo_item();
                    $item->set_id($record[$this->_make_alias($this->table, $this->primery_key)]);
                    $item->set_photo($record[$this->_make_alias($this->table, 'photo')]);
                    foreach ($this->config->item('main_db_data') as $m_col) {
                        $item->set_string($m_col, $record[$this->_make_alias($this->table, $m_col)]);
                    }
                }

                // Set lang data
                foreach ($this->config->item('lang_db_data') as $m_col) {
                    $value = $record[$this->_make_alias($this->lang_table, $m_col)];
                    $id_lan = $record[$this->_make_alias($this->lang_table, 'id_lan')];
                    if (!empty($m_col) && !empty($id_lan)) {
                        $item->set_lang_string($m_col, $value, $id_lan);
                    }
                }

                // Add item to conteiner
                if (!in_array($record[$this->_make_alias($this->table, $this->primery_key)], $main_data_id)) {
                    $items[] = $item;
                    $main_data_id[] = $record[$this->_make_alias($this->table, $this->primery_key)];
                }
            }
        }

        return $items;
    }

    public function fetch_by_id($id = 0) {
        $this->db->where($this->table . '.' . $this->primery_key, $id);

        $item = reset($this->_fetch_data());

        return (!empty($item)) ? $item : FALSE;
    }

    public function fetch_by_fields($fields = array()) {
        foreach ($fields as $key => $value) {
            $this->db->where($this->table . '.' . $key, $value);
        }

        $item = $this->_fetch_data();

        return (!empty($item)) ? $item : FALSE;
    }

    public function make_hash($str = '') {

        return substr(md5($str . $this->config->item('encryption_key')), 0, 8);
    }

    public function get_photos_list($id = 0) {
        $p_content = array(
            'ln_del' => $this->lang->line('Delete'),
            'ln_edit' => $this->lang->line('Edit'),
            'photos' => array()
        );
        $photos = $this->fetch_by_fields(
                array(
                    $this->config->item('foreign_key') => $id
                )
        );
        if ($photos !== FALSE) {
            foreach ($photos as $photo) {
                $photo_name = $photo->get_string('name');
                $photo_name = ($photo_name) ? $photo_name : $photo->get_photo();
                if (strlen($photo_name) > 12) {
                    $photo_name = mb_substr($photo_name, 0, 12) . '...';
                }
                $p_content['photos'][] = array(
                    'photo' => $this->config->item('photo_path') . '/' . $photo->get_photo(),
                    'name' => $photo_name,
                    'id_photo' => $photo->get_id()
                );
            }
        }

        return $this->parser->parse('alphagallery/photo_template', $p_content, TRUE);
    }

    public function set_gallery_config($config) {
        // Set default values
        $config['foreign_key'] = (!empty($config['foreign_key'])) ? $config['foreign_key'] : 'id_foreign_key';
        $config['main_table'] = (!empty($config['main_table'])) ? $config['main_table'] : 'alphagallery_photo';
        $config['alphagallery_photo_pkey'] = (!empty($config['alphagallery_photo_pkey'])) ? $config['alphagallery_photo_pkey'] : 'id_' . $config['main_table'];
        $config['lang_table'] = (!empty($config['lang_table'])) ? $config['lang_table'] : $config['main_table'] . '_translate';
        $config['main_db_data'] = (!empty($config['main_db_data'])) ? $config['main_db_data'] : array($config['foreign_key'], 'photo', 'name', 'active');

        foreach ($config as $item => $value) {
            $this->config->set_item($item, $value);
        }
    }

    public function save_file() {
        $result = array(
            'success' => 'false',
            'session_data' => $this->session->get_js_session()
        );
        $targetFolder = $this->config->item('photo_path'); // Relative to the root
        $tempFile = $_FILES['Filedata']['tmp_name'];
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;

        // Make dir if not exists
        if (!file_exists($targetPath)) {
            mkdir($targetPath, 775, true);
        }

        // Validate the file type
        $fileTypes = $this->config->item('file_types'); // File extensions
        $fileParts = pathinfo($_FILES['Filedata']['name']);

        $realname = substr(md5($_FILES['Filedata']['name'] . md5(mktime())), 0, 8);
        $extension = strtolower($fileParts['extension']);
        $targetFile = rtrim($targetPath, '/') . '/' . $realname . '.' . $extension;

        if (in_array($extension, $fileTypes) && move_uploaded_file($tempFile, $targetFile)) {
            // Resize photo if needed
            if ($this->config->item('photo_width') && $this->config->item('photo_height')) {
                $image = $this->load->library('image_change', $targetFile);
                $image->resize($this->config->item('photo_width'), $this->config->item('photo_height'));
                $image->save($targetFile);
            }

            $result['success'] = 'true';
            $result['file_name'] = $_FILES['Filedata']['name'];
            $result['img_name'] = $realname . '.' . $extension;
            $result['img_path'] = $targetFolder . '/' . $realname . '.' . $extension;

            // Save data to db
            $this->load->library('db_lang_lib');
            $photo = new photo_item();
            // Set main data
            $photo->set_string($this->config->item('foreign_key'), intval($this->input->post('photogallery')));
            $photo->set_string('name', $result['file_name']);
            foreach ($this->config->item('lang_db_data') as $field) {
                foreach ($this->db_lang_lib->get_lang_by_id() as $lang) {
                    if (!empty($lang->id_lan)) {
                        $post = $this->input->post($field);
                        $value = (empty($post[$lang->id_lan])) ? '' : $post[$lang->id_lan];
                        $photo->set_lang_string($field, $value, $lang->id_lan);
                    }
                }
            }
            $photo->set_photo($result['img_name']);
            $this->save($photo);
        } else {
            $result['msg'] = 'Invalid file type.';
        }

        return $result;
    }

    public function sort($photos = array()) {
        $view_order = 0;
        foreach ($photos as $id) {
            $view_order += 10;
            $this->db
                    ->where($this->primery_key, $id)
                    ->update($this->table, array('view_order' => $view_order));
        }
        
        return ($view_order > 0);
    }
}
