<?php

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

/**
 * Description of alphagellery_admin
 *
 * @author Igor Ratsun
 */
class alphagallery_admin extends MX_Controller
{

    public function __construct()
    {
        $this->load->model('alphagallery/alphagallery_admin_model', 'alphagalmod');
        $this->load->helper('form');
        $this->load->config('alphagallery/config');
        $this->load->library('gettext_language');
        $this->gettext_language->load(__DIR__ . '/../language/' . $this->config->item('language') . '.po');
    }

    public function create_tables($config)
    {
        // Prepare data
        if (empty($config['main_table'])) {
            show_error('Empty main_table', 500);
        }

        $this->alphagalmod->set_gallery_config($config);

        // Create table
        $query = '
            CREATE TABLE IF NOT EXISTS `' . $this->db->dbprefix . $this->config->item('main_table') . '` (
                `' . $this->config->item('alphagallery_photo_pkey') . '` int(11) NOT NULL AUTO_INCREMENT,
                `' . $this->config->item('foreign_key') . '` int(11) NOT NULL,
                `photo` varchar(16) NOT NULL,
                `name` varchar(32) NOT NULL,
                `view_order` int(11) NOT NULL DEFAULT \'0\',
                `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                `active` tinyint(1) NOT NULL DEFAULT \'1\',
                PRIMARY KEY (`' . $this->config->item('alphagallery_photo_pkey') . '`)
              ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
              
              CREATE TABLE IF NOT EXISTS `' . $this->db->dbprefix . $this->config->item('lang_table') . '` (
                `id_' . $this->config->item('lang_table') . '` int(11) NOT NULL AUTO_INCREMENT,
                `' . $this->config->item('alphagallery_photo_pkey') . '` int(11) NOT NULL,
                `name` varchar(64) NOT NULL,
                `description` text NOT NULL,
                `id_lan` tinyint(4) NOT NULL,
                PRIMARY KEY (`id_' . $this->config->item('lang_table') . '`)
              ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
        ';
        foreach (explode(';', trim($query)) as $table) {
            if (!empty($table)) {
                $this->db->query($table);
            }
        }

        return 'Done';
    }

    public function drop_tables($config)
    {
        // Prepare data
        if (empty($config['main_table'])) {
            show_error('Empty main_table', 500);
        }

        $this->alphagalmod->set_gallery_config($config);

        // Create table
        $query = 'DROP TABLE IF EXISTS `' . $this->db->dbprefix . $this->config->item('main_table') . '` ; DROP TABLE IF EXISTS `' . $this->db->dbprefix . $this->config->item('lang_table') . '`;';
        foreach (explode(';', trim($query)) as $table) {
            if (!empty($table)) {
                $this->db->query($table);
            }
        }

        return 'Done';
    }

    public function empty_gallery($config = array())
    {
        // Prepare data
        $id_gallery = (!empty($config['foreign_key_value'])) ? $config['foreign_key_value'] : 0;

        if (empty($id_gallery)) {

            return FALSE;
        }

        // Configurate
        if (!empty($config)) {
            $this->alphagalmod->set_gallery_config($config);
        }

        $this->alphagalmod->set_table($this->config->item('main_table'));
        $this->alphagalmod->set_pkey($this->config->item('alphagallery_photo_pkey'));
        $this->alphagalmod->set_lang_table($this->config->item('lang_table'));

        $items = $this->alphagalmod->fetch_by_fields(array($this->config->item('foreign_key') => $id_gallery));

        if (!empty($items)) {
            foreach ($items as $item) {
                $this->alphagalmod->delete($item->get_id());
            }
        }

        return TRUE;
    }

    public function render($config = array())
    {
        // Prepare data
        $id_gallery = (!empty($config['foreign_key_value'])) ? $config['foreign_key_value'] : 0;
        $action = $this->input->post('ag_action');

        // Configurate
        if (!empty($config)) {
            $this->alphagalmod->set_gallery_config($config);
        }
        $this->alphagalmod->set_table($this->config->item('main_table'));
        $this->alphagalmod->set_pkey($this->config->item('alphagallery_photo_pkey'));
        $this->alphagalmod->set_lang_table($this->config->item('lang_table'));

        switch ($action) {
            case 'get_photos':
                die($this->alphagalmod->get_photos_list($id_gallery));
                break;
            case 'get_photo':
                $id = intval($this->input->post('id_photo'));
                if ($id == 0) {

                    die($this->lang->line('Photo not found'));
                }

                $photo = $this->alphagalmod->fetch_by_id($id);
                $this->load->library('db_lang_lib');
                $languages = $this->db_lang_lib->get_lang_by_id();

                $content = array(
                    'ln_photo_path' => $this->lang->line('File'),
                    'photo'         => $photo->get_photo(),
                    'id_photo'      => $photo->get_id()
                );

                foreach ($this->config->item('lang_db_data') as $str) {
                    $lang_data = array();
                    foreach ($languages as $lan) {
                        $lang_data[] = array(
                            'lan_name' => $lan->name,
                            'name'     => $str,
                            'value'    => $photo->get_lang_string($str, $lan->id_lan),
                            'id_lan'   => $lan->id_lan
                        );
                    }
                    $content['block_data'][] = array(
                        'block_name' => $this->lang->line(ucfirst($str)),
                        'lang_data'  => $lang_data
                    );
                }
                die($this->parser->parse('alphagallery/photo_edit', $content, TRUE));
                break;
            case 'add_photo':

                $this->prepare_photo_arr();
                $hash = $this->input->post('hash');
                if (!empty($_FILES) && $hash == $this->alphagalmod->make_hash($this->input->post('user'))) {
                    $rs = ['success' => 'true'];
                    foreach ($_FILES as $file) {
                        $res_t = $this->alphagalmod->save_file($file);
                        $rs['success'] = $rs['success'] & $res_t['success'];
                    }
                } else {
                    $rs = ['success' => 'false'];
                }
                die(json_encode($rs));
                break;
            case 'edit_photo':
                $rs = array(
                    'success' => 0
                );
                // Prepare data
                $id_photo = intval($this->input->post('id_photo'));
                if (!empty($id_photo) && ($photo = $this->alphagalmod->fetch_by_id($id_photo))) {
                    $photo_langs = $photo->get_lang_strings();
                    if ($photo_langs !== FALSE) {
                        foreach ($photo_langs as $lang_str) {
                            $post = $this->input->post($lang_str->key);
                            $value = (isset($post[$lang_str->id_lan])) ? $post[$lang_str->id_lan] : FALSE;
                            if ($value !== FALSE) {
                                $photo->set_lang_string($lang_str->key, $value, $lang_str->id_lan);
                            }
                        }
                        $rs['success'] = $this->alphagalmod->save($photo);
                    }
                }
                die(json_encode($rs));
                break;
            case 'del_photo':
                $hash = $this->input->post('hash');
                $rs = array(
                    'success' => 0
                );
                if ($hash == $this->alphagalmod->make_hash($this->rt_user->id_user)) {
                    $rs['success'] = intval($this->alphagalmod->delete(intval($this->input->post('id'))));
                }
                die(json_encode($rs));
                break;
            case 'sort':
                $hash = $this->input->post('hash');
                $rs = array(
                    'success' => 0
                );
                if ($hash == $this->alphagalmod->make_hash($this->rt_user->id_user)) {
                    $rs['success'] = intval($this->alphagalmod->sort(array_map('intval', $this->input->post('photo'))));
                }
                die(json_encode($rs));
                break;

            default :
                return $this->get_gallery($id_gallery);
                break;
        }
    }

    protected function get_gallery($gallery)
    {
        $this->ciext->load_bootstrap();
        $this->ciext->load_jquery_ui();

        $this->js_css->parse_js('alphagallery/js/main.js', array(
            'actions_link' => '/' . $this->uri->uri_string(),
            'session_name' => $this->session->session_id,
            'session_data' => base64_encode(json_encode($this->session->all_userdata()))
        ));
        $this->js_css->parse_css('alphagallery/css/style.css');

        // Load fancybox
        $this->js_css->add_js('/' . $this->config->item('assets_folder') . '/plugins/fancybox/js/jquery.fancybox-1.3.4.js');
        $this->js_css->add_css('/' . $this->config->item('assets_folder') . '/plugins/fancybox/css/jquery.fancybox.css');

        $content = array(
            'ln_save'        => $this->lang->line('Save'),
            'ln_close'       => $this->lang->line('Close'),
            'add_btn'        => '<a data-toggle="modal" href="#add_dialog" class="btn"><i class="icon-plus"></i> ' . $this->lang->line('Add') . '</a>',
            'msg_edit_photo' => $this->lang->line('Edit photo'),
            'msg_add_photo'  => $this->lang->line('Add photo'),
            'ln_img_size'    => ''
        );

        if ($this->config->item('photo_width') && $this->config->item('photo_height')) {
            $content['ln_img_size'] = $this->lang->line('Photo size') . ': ' . $this->config->item('photo_width') . 'px X ' . $this->config->item('photo_height') . 'px';
        }

        // Get photos
        $content['photos'] = ''; //$this->alphagalmod->get_photos_list($gallery);
        // Add photo dialog
        $this->ciext->load_jquery();
        $link = '/' . $this->config->item('assets_folder') . '/plugins';
        $this->js_css->add_js_string('var ln_btn_upload="' . $this->lang->line('Upload') . '";');
        $this->js_css->add_js_string('var ln_del="' . $this->lang->line('Delete') . '";');
        $this->js_css->add_js_string('var item_fileTypeDesc="' . $this->config->item('file_type_desc') . '";');
        $ext_name = '';
        foreach ($this->config->item('file_types') as $v) {
            $ext_name .= '*.' . $v . ';';
        }
        $this->js_css->add_js_string('var item_fileTypeExts="' . $ext_name . '";');
        $content['photogallery'] = (!empty($gallery)) ? $gallery : '0';
        $content['id_user'] = $this->rt_user->id_user;
        $content['hash'] = $this->alphagalmod->make_hash($content['id_user']);
        $this->load->library('db_lang_lib');
        $languages = $this->db_lang_lib->get_lang_by_id();
        foreach ($this->config->item('lang_db_data') as $str) {
            $lang_data = array();
            foreach ($languages as $lan) {
                $lang_data[] = array(
                    'lan_name' => $lan->name,
                    'name'     => $str,
                    'id_lan'   => $lan->id_lan
                );
            }
            $content['block_data'][] = array(
                'block_name' => $this->lang->line(ucfirst($str)),
                'lang_data'  => $lang_data
            );
        }

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

    protected function prepare_photo_arr()
    {
        $photo_arr = [];
        if (!empty($_FILES)) {
            $files = $_FILES;
            unset($_FILES);
            //prepare FILES array for inserting
            for ($i = 0; $i < count($files['photo_files']['name']); $i++) {
                $_FILES['img' . ($i + 1)] = [
                    'name'     => $files['photo_files']['name'][$i],
                    'type'     => $files['photo_files']['type'][$i],
                    'tmp_name' => $files['photo_files']['tmp_name'][$i],
                    'error'    => $files['photo_files']['error'][$i],
                    'size'     => $files['photo_files']['size'][$i]
                ];
            }

            return $photo_arr;
        }
    }

}
