<?php

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

// Load simple types
require_once __DIR__ . '/rtgrid_simple_types.php';

/**
 * Description of rtgrid_edit_model
 *
 * @author Igor Ratsun
 */
class rtgrid_edit_model extends CI_Model implements SplSubject {

    /**
     * Current action
     * @var string
     */
    public $current_action = '';

    /**
     * Callback of action
     * @var mixed
     */
    public $current_action_return;

    /**
     * Primery key
     * @var string
     */
    public $_primery_key;

    /**
     * Primery key value
     * @var int
     */
    public $_primery_key_value = 0;

    /**
     * Data from $_POST
     * @var array
     */
    public $post = array();
    protected $_table;
    protected $_unique;
    protected $_fields;
    protected $_fields_array = array();
    protected $_display_as;
    protected $_callback_field;
    protected $_callback_before_edit = NULL;
    protected $_callback_after_edit = NULL;
    protected $_where = array();
    protected $_where_in = array();
    protected $_join = array();
    protected $_actions = array();
    protected $observers = array();
    protected $_multilang = array();
    protected $_tabs = array();
    protected $_readonly = array();
    protected $_image_uploads = array();
    protected $_required_fields = array();

    public function __construct() {
        // Load lang
        $this->lang->load('rtgrid/rtgrid_edit');

        // Load default field callbacks
        $this->load->model('rtgrid/rtgrid_field_callback');

        // Add default actions
        $this->load->model('rtgrid/rtgrid_edit_action_model');
        $this->add_action(new rtgrid_edit_action('save', $this->lang->line('edit_action_save'), array($this->rtgrid_edit_action_model, 'save'), '', '<input type="submit" class="btn btn-success" name="{action_name}" value="{action_text}" />'));
        $this->add_action(new rtgrid_edit_action('cancel', $this->lang->line('edit_action_cancel')));
    }

    public function set_table($table = '') {

        $this->_table = $table;
        $this->_unique = substr(md5($table . $this->config->item('encryption_key')), 0, 8);
    }

    public function set_primery_key($primery_key = '') {

        $this->_primery_key = $primery_key;
    }

    public function set_primery_key_value($primery_key_value = 0) {

        $this->_primery_key_value = intval($primery_key_value);
    }

    public function fields($fields = '') {
        $this->_fields_array = array();

        foreach (explode(',', $fields) as $value) {
            $value = trim($value);
            $key = $this->_field_alias($value);
            $this->_fields_array[$key] = preg_replace('/(.*\sas\s)?(.*\.)?/', '', $value);
        }

        $this->_fields = $fields;
    }

    public function display_as($field, $value) {

        $this->_display_as[$field] = $value;
    }

    public function callback_field($field, $callback) {

        $this->_callback_field[$field] = $callback;
    }

    public function callback_before_edit($callback) {

        $this->_callback_before_edit[] = $callback;
    }

    public function callback_after_edit($callback) {

        $this->_callback_after_edit[] = $callback;
    }

    public function where($key, $value = NULL, $escape = TRUE) {
        $where = new stdClass();
        $where->key = $key;
        $where->value = $value;
        $where->escape = $escape;

        $this->_where[] = $where;
    }

    public function where_in($key, $value = NULL, $escape = TRUE) {
        $where_in = new stdClass();
        $where_in->key = $key;
        $where_in->value = $value;
        $where_in->escape = $escape;

        $this->_where_in[] = $where_in;
    }

    public function join($table, $cond, $type = '') {
        $join = new stdClass();
        $join->table = $table;
        $join->cond = $cond;
        $join->type = $type;

        $this->_join[] = $join;
    }

    public function add_action(rtgrid_edit_action $rtgrid_edit_action) {

        $this->_actions[$rtgrid_edit_action->get_name()] = $rtgrid_edit_action;
    }

    public function unset_action($name) {
        $data = new rtgrid_edit_action($name);

        unset($this->_actions[$data->get_name()]);
    }

    /**
     * Add observer
     * @param SplObserver $obs
     */
    public function attach(SplObserver $obs) {
        $id = spl_object_hash($obs);
        $this->observers[$id] = $obs;
    }

    /**
     * Remove observer
     * @param SplObserver $obs
     */
    public function detach(SplObserver $obs) {
        $id = spl_object_hash($obs);
        unset($this->observers[$id]);
    }

    /**
     * Notify observers
     */
    public function notify() {
        foreach ($this->observers as $obs) {
            $obs->update($this);
        }
    }

    /**
     * Add multilang field
     * @param multilang $multilang
     * @return boolean
     */
    public function multilang(multilang $multilang) {
        // Remove multilang fields from fields list if any
        $this->fields(preg_replace('/' . $multilang->get_data('field') . '\s*\,?/', '', $this->_fields));

        $this->_multilang[$multilang->get_data('lang_table')][] = $multilang;
    }

    public function add_tab($name = '', $data = '') {
        if (!empty($name)) {
            $this->_tabs[$name] = $data;

            return FALSE;
        }

        return TRUE;
    }

    public function set_relation($field_name, $related_table, $related_title_field, $where, $order_by) {
        if (!is_null($where)) {
            $this->db->where($where);
        }

        if (!is_null($order_by)) {
            $this->db->order_by($related_title_field, $order_by);
        }

        $data = $this->db->
                        select($field_name . ', ' . $related_title_field)->
                        get($related_table)->result_array();

        if (!empty($data)) {
            $this->load->model('rtgrid/rtgrid_field_callback');
            $key = $this->_field_alias($field_name);
            $this->rtgrid_field_callback->buffer[$key][0] = '---';
            foreach ($data as $v) {
                $this->rtgrid_field_callback->buffer[$key][$v[$field_name]] = $v[$related_title_field];
            }

            $this->callback_field($field_name, array($this->rtgrid_field_callback, 'dropdown'));
        }
    }

    public function add_photogallery(photogallery $photogallery) {
        $this->load->module('alphagallery/alphagallery_admin');

        $config['main_table'] = $photogallery->get_table();
        $config['foreign_key'] = $this->_primery_key;
        $config['foreign_key_value'] = $this->_primery_key_value;
        $config['photo_path'] = $photogallery->get_photo_path();
        $config['photo_width'] = $photogallery->get_photo_width();
        $config['photo_height'] = $photogallery->get_photo_height();

        if ($photogallery->create_tables_when_run) {
            $this->alphagallery_admin->create_tables($config);
        }

        if (empty($this->_primery_key_value)) {
            $pk = $this->_primery_key;
            $table = $photogallery->get_table();
            $this->callback_after_edit(function($post, $pkey) use ($pk, $table) {
                $CI = & get_instance();
                $CI->db->
                        where($pk, 0)->
                        update($table, array($pk => $pkey));
            });
        }

        $this->add_tab($this->lang->line('photos'), $this->alphagallery_admin->render($config));
    }

    public function readonly($field) {

        $this->_readonly[] = $field;
        $this->callback_field($field, array($this->rtgrid_field_callback, 'readonly'));
    }

    public function required_fields($array = array()) {

        $this->_required_fields = $array;
    }

    public function render() {
        $fields = array();
        $content = array(
            'message' => '',
            'tabs_control' => array(),
            'tabs' => array()
        );

        // If action
        if (!empty($_POST)) {
            foreach ($this->_actions as $action_name => $callback) {
                if (isset($_POST[$action_name])) {
                    $this->current_action = $action_name;
                    $this->post = array();
                    foreach ($this->_fields_array as $alies => $field) {
                        $this->post[$field] = $this->input->post($alies);
                    }

                    // Required check
                    $required = '';
                    foreach ($this->_required_fields as $r_field) {
                        $required .= (empty($this->post[$r_field])) ? ' - ' . $this->_get_display_as($r_field) . '<br />' : '';
                    }
                    if (!empty($required)) {
                        $content['message'] = $this->_alert($this->lang->line('msg_error') . '<br />' . $this->lang->line('msg_required_fields') . $required, 'error');
                        break;
                    }

                    if (!empty($this->_readonly)) {

                        foreach ($this->_readonly as $readonly_field) {
                            if (isset($this->post[$readonly_field])) {
                                unset($this->post[$readonly_field]);
                            }
                        }
                    }

                    if (!is_null($this->_callback_before_edit)) {

                        foreach ($this->_callback_before_edit as $item) {
                            $this->post = call_user_func($item, $this->post, $this->_primery_key_value);
                        }
                    }
                    $func = $callback->get_callback();
                    if (!empty($func)) {
                        $this->current_action_return = call_user_func($func, $this->_table, $this->_primery_key, $this->_primery_key_value, $this->post);

                        // Update primery key value if saved
                        if ($this->current_action == 'rtgrid_action_save' && $this->current_action_return && empty($this->_primery_key_value)) {
                            $this->_primery_key_value = $this->db->insert_id();
                            $clear_fields = TRUE;
                        }

                        // If action 'save' and is multilang then update multilang
                        if ($this->current_action == 'rtgrid_action_save' && !empty($this->_multilang)) {
                            $rs = $this->_multilang_save($this->_primery_key_value);
                            $this->current_action_return = ($this->current_action_return) ? $this->current_action_return : $rs;
                        }

                        // Clear $_POST if saved
                        if ($this->current_action == 'rtgrid_action_save' && $this->current_action_return) {
                            $_POST = array();
                        }

                        // Set message
                        $content['message'] = ($this->current_action_return) ? $this->_alert($this->lang->line('msg_saved'), 'success') : $this->_alert($this->lang->line('msg_error'), 'error');
                    }

                    if (!is_null($this->_callback_after_edit) && !empty($this->_primery_key_value)) {
                        foreach ($this->_callback_after_edit as $item) {
                            call_user_func($item, $this->post, $this->_primery_key_value);
                        }
                    }
                    
                    // Redirect to list if was add method
                    if (!empty($clear_fields)) {
                        $this->load->helper('url');
                        
                        redirect(str_replace('/edit/add', '', $this->uri->uri_string()));
                    }
                    
                    break;
                }
            }
        }

        // Select data
        if (!empty($this->_where)) {
            foreach ($this->_where as $where) {
                $this->db->where($where->key, $where->value, $where->escape);
            }
        }
        if (!empty($this->_where_in)) {
            foreach ($this->_where_in as $where_in) {
                $this->db->where_in($where_in->key, $where_in->value, $where_in->escape);
            }
        }
        if (!empty($this->_join)) {
            foreach ($this->_join as $join) {
                $this->db->join($join->table, $join->cond, $join->type);
            }
        }

        // If add new then empty fields
        $id = (!empty($clear_fields)) ? 0 : $this->_primery_key_value;

        $data = $this->db->
                        select($this->_fields)->
                        where($this->_table . '.' . $this->_primery_key, $id)->
                        get($this->_table)->row();

        // Check
        if (empty($data) && $id != 0) {
            show_404();
        }

        foreach (explode(',', $this->_fields) as $field) {
            $field = trim($field);
            $field_alias = $this->_field_alias($field);
            $field_value = htmlspecialchars((isset($data->{$this->_fields_array[$field_alias]})) ? $data->{$this->_fields_array[$field_alias]} : $this->input->post($field_alias));
            $callback = !empty($this->_callback_field[$this->_fields_array[$field_alias]]) ?
                    $this->_callback_field[$this->_fields_array[$field_alias]] :
                    array($this->rtgrid_field_callback, 'default_field');
            $fields['field'][] = array(
                'name' => $this->_get_display_as($this->_fields_array[$field_alias]) . (in_array($this->_fields_array[$field_alias], $this->_required_fields) ? '*' : ''),
                'value' => call_user_func($callback, $field_alias, $field_value)
            );
        }

        // add multilang if any
        if (!empty($this->_multilang)) {
            $this->_multilang_build_tabs();
        }

        // Add home tab
        $this->add_tab($this->lang->line('Attributes'), $this->parser->parse('rtgrid/edit/fields_item', $fields, TRUE));

        // Build tabs
        if (!empty($this->_tabs)) {
            foreach ($this->_tabs as $name => $data) {
                $id = 'id_' . substr(md5($name), 0, 6);
                $content['tabs_control'][] = array(
                    'id' => $id,
                    'name' => $name,
                    'active' => (empty($content['tabs_control'])) ? 'class="active"' : ''
                );
                $content['tabs'][] = array(
                    'id' => $id,
                    'data' => $data,
                    'active' => (empty($content['tabs'])) ? 'active' : ''
                );
            }
        }

        $content['actions'] = $this->_get_actions_html();

        $this->load->helper('form');
        $content['form_open'] = form_open('', array('class' => 'form-horizontal'));
        $content['form_close'] = form_close();

        // Notify observers
        $this->notify();

        return $this->parser->parse('rtgrid/edit/template', $content, TRUE);
    }

    protected function _alert($msg = '', $type_class = 'success') {
        $template = '<div class="alert alert-%s"><a class="close" data-dismiss="alert">×</a>%s</div>';

        return sprintf($template, $type_class, $msg);
    }

    protected function _get_actions_html() {
        $rs = array();
        foreach ($this->_actions as $action) {
            $rs[] = array(
                'action' => $action->get_template()
            );
        }

        return $rs;
    }

    protected function _field_alias($field_name) {

        return 'f' . substr(md5($this->_unique . $field_name), 0, 8);
    }

    protected function _get_display_as($field_name = '') {

        return !empty($this->_display_as[$field_name]) ? $this->_display_as[$field_name] : ucfirst(preg_replace('/[\_\-]/', ' ', $field_name));
    }

    protected function _multilang_build_tabs() {
        $select = '';
        $join = array();
        $callbacks = array();
        foreach ($this->_multilang as $value) {
            foreach ($value as $obj) {
                $select .= $obj->get_data('lang_table') . '.' . $obj->get_data('lang_table_field') . ' as ' . $obj->get_data('field') . ', ';
                if (!in_array($obj->get_data('lang_table'), $join)) {
                    $join[] = $obj->get_data('lang_table');
                    $this->db->join($obj->get_data('lang_table'), $obj->get_data('lang_table') . '.id_lan=lan.id_lan AND ' . $obj->get_data('lang_table') . '.' . $this->_primery_key . '=' . $this->_primery_key_value, 'left');
                }
                $callbacks[$obj->get_data('field')] = $obj->get_data('callback_field');
            }
        }

        $q = $this->db->
                        select($select . ', lan.name as lan_name, lan.id_lan as lan_id_lan')->
                        where('lan.active', TRUE)->
                        order_by('lan.name', 'ASC')->
                        get('lan')->result_array();

        foreach ($q as $row) {
            $content = array();
            foreach ($row as $field => $value) {
                $value = htmlspecialchars($value);
                if ($field == 'lan_name' || $field == 'lan_id_lan') {
                    continue;
                }
                $field_alias = $this->_field_alias($field) . '[' . $row['lan_id_lan'] . ']';
                $content['field'][] = array(
                    'name' => $this->_get_display_as($field),
                    'value' => (!empty($callbacks[$field])) ? call_user_func($callbacks[$field], $field_alias, $value) : $this->rtgrid_field_callback->default_field($field_alias, $value)
                );
            }
            $this->add_tab($row['lan_name'], $this->parser->parse('rtgrid/edit/fields_item', $content, TRUE));
        }
    }

    protected function _multilang_save($reletad_id = 0) {
        if (empty($reletad_id)) {

            return FALSE;
        }

        // Prepare data
        $save_arr = array();
        foreach ($this->_multilang as $items) {
            foreach ($items as $item) {
                // Get data from post
                $post = $this->input->post($this->_field_alias($item->get_data('field')));
                if (!empty($post)) {
                    foreach ($post as $id_lan => $value) {
                        $id_lan = intval($id_lan);
                        if (!empty($id_lan)) {
                            $save_arr[$item->get_data('lang_table')][$id_lan][$item->get_data('lang_table_field')] = $value;
                        }
                    }
                }
            }
        }
        // Save data
        foreach ($save_arr as $table => $data) {
            foreach ($data as $id_lan => $row) {
                $row[$this->_primery_key] = $reletad_id;
                $row['id_lan'] = $id_lan;
                // Save data
                $exists = $this->db->
                                select(array_keys($row))->
                                where(array(
                                    $this->_primery_key => $reletad_id,
                                    'id_lan' => $id_lan
                                ))->
                                get($table)->row_array();
                // Update or insert
                if (!empty($exists)) {
                    $this->db->
                            where(array(
                                $this->_primery_key => $reletad_id,
                                'id_lan' => $id_lan
                            ))->
                            update($table, $row);
                } else {
                    $this->db->insert($table, $row);
                }
            }
        }

        return TRUE;
    }

    public function set_image_upload(image_upload $data) {

        if (!is_dir(FCPATH . $data->get_path())) {
            show_error(sprintf($this->lang->line('folder_error'), FCPATH . $data->get_path(), $data->get_field()));
        }

        $this->_image_uploads[$this->_field_alias($data->get_field())] = $data;
        $this->callback_field($data->get_field(), array($this, 'processing_image_upload'));
    }

    public function processing_image_upload($field, $value) {

        $this->load->config('rtgrid/config');

        $this->ciext->load_jquery();
        $this->js_css->add_js('/' . $this->config->item('assets_folder') . '/plugins/uploadify3.2/jquery.uploadify.min.js');
        $this->js_css->add_js('/' . $this->config->item('assets_folder') . '/plugins/fancybox/js/jquery.fancybox-1.3.4.js');

        $this->js_css->parse_js('rtgrid/edit/image_upload/js/main.js', array(
            'actions_link' => '/' . $this->uri->uri_string(),
            'confirm_del' => $this->lang->line('confirm_del')
        ));

        $this->js_css->add_css('/' . $this->config->item('assets_folder') . '/plugins/uploadify3.2/uploadify.css');
        $this->js_css->add_css('/' . $this->config->item('assets_folder') . '/plugins/fancybox/css/jquery.fancybox.css');
        $this->js_css->parse_css('rtgrid/edit/image_upload/css/fileuploader.css');

        if ($this->_image_uploads[$field]->get_crop()) {
            $this->js_css->add_css('/' . $this->config->item('assets_folder') . '/plugins/crop/css/jquery.Jcrop.min.css');
            $this->js_css->add_js('/' . $this->config->item('assets_folder') . '/plugins/crop/js/jquery.Jcrop.min.js');
            $this->js_css->parse_js('rtgrid/edit/image_upload/js/init_crop.js', array(
                'title_crop_dialog' => sprintf($this->lang->line('title_crop_dialog'), $this->_image_uploads[$field]->get_width(), $this->_image_uploads[$field]->get_height()),
                'btn_cancel' => $this->lang->line('btn_cancel'),
                'ln_crop' => $this->lang->line('ln_crop'),
                'ln_del_image' => $this->lang->line('ln_del_image')
            ));
            $this->ciext->load_jquery_ui();
        }

        $action = $this->input->post('upload_action');

        if ($action == 'add_image') {

            die(json_encode($this->save_image($this->input->post('field'))));
        } elseif ($action == 'delete_image') {

            die(json_encode($this->delete_image($this->input->post('field'), $this->input->post('img_delete'))));
        } elseif ($action == 'crop') {

            die(json_encode($this->crop_image()));
        } else {

            $this->js_css->add_js_string($this->parser->parse('rtgrid/edit/image_upload/js/upload.js', array(
                        'session_name' => $this->session->get_js_session(TRUE),
                        'session_data' => $this->session->get_js_session(),
                        'field' => $field,
                        'actions_link' => '/' . $this->uri->uri_string(),
                        'ln_btn_upload' => $this->lang->line('ln_select_photos'),
                        'item_fileTypeDesc' => $this->config->item('file_type_desc'),
                        'item_fileTypeExts' => $this->config->item('allow_types'),
                        'auto_open' => ($this->_image_uploads[$field]->get_auto_open()) ? 't' : 'f'
                            ), TRUE));

            $content = array(
                'crop' => $this->get_crop_template($field, $value),
                'field' => $field,
                'value' => $value
            );

            if (empty($value)) {

                $content['style'] = '';
                $addition = '';
            } else {

                $content['style'] = ' style="display:none;"';
                $addition = $this->get_img_block($field, $value);
            }

            return $this->parser->parse('rtgrid/edit/image_upload/upload_template', $content, TRUE) . $addition;
        }
    }

    public function get_crop_template($field, $src) {

        return (!$this->_image_uploads[$field]->get_crop()) ? '' : $this->parser->parse('rtgrid/edit/image_upload/crop', array(
                    'field' => $field,
                    'ln_crop' => $this->lang->line('ln_crop'),
                    'w' => $this->_image_uploads[$field]->get_width(),
                    'h' => $this->_image_uploads[$field]->get_height(),
                    'src' => $this->_image_uploads[$field]->get_path() . '/' . $src,
                    'title_crop_dialog' => $this->lang->line('title_crop_dialog')
                        ), TRUE);
    }

    public function get_img_block($field, $src) {

        return $this->parser->parse('rtgrid/edit/image_upload/image_block', array(
                    'field' => $field,
                    'ln_del' => $this->lang->line('ln_del'),
                    'preview_block' => $this->parser->parse('rtgrid/edit/image_upload/preview_block', array('link' => $this->_image_uploads[$field]->get_path() . '/' . $src), TRUE),
                    'crop' => $this->get_crop_template($field, $src),
                    'ln_del_image' => $this->lang->line('ln_del_image')
                        ), TRUE);
    }

    public function save_image($field) {

        $targetFolder = $this->_image_uploads[$field]->get_path();
        $result = array('success' => 'false');
        $tempFile = $_FILES['Filedata']['tmp_name'];
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
        $fileTypes = $this->config->item('file_types');
        $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
            $width = $this->_image_uploads[$field]->get_width();
            $height = $this->_image_uploads[$field]->get_height();

            if (!$this->_image_uploads[$field]->get_crop() && !empty($width) && !empty($height)) {

                $image = $this->load->library('image_change', $targetFile);
                $image->resize($width, $height);
                $image->save($targetFile);
            }


            $result['success'] = 'true';
            $result['field'] = $field;
            $result['img_name'] = $realname . '.' . $extension;
            $result['img_path'] = $targetFolder . '/' . $realname . '.' . $extension;
            $result['img_block'] = $this->get_img_block($field, $realname . '.' . $extension);
        } else {
            $result['msg'] = 'Invalid file type.';
        }

        $result['session'] = $this->session->get_js_session();

        return $result;
    }

    public function delete_image($field, $value) {

        $photo = ltrim($this->_image_uploads[$field]->get_path() . '/' . $value, '/');
        $exists = file_exists($photo);
        if (!$exists || ($exists && unlink($photo))) {
            $this->db->update($this->_table, array($this->_fields_array[$field] => ''), array($this->_primery_key => $this->_primery_key_value));

            return TRUE;
        }

        return FALSE;
    }

    public function crop_image() {

        if (!isset($_POST['field']) || !isset($_POST['src']) ||
                !isset($_POST['top_x']) || !isset($_POST['top_y']) ||
                !isset($_POST['bottom_x']) || !isset($_POST['bottom_y']) ||
                !isset($_POST['width']) || !isset($_POST['height']) ||
                empty($this->_image_uploads[$this->input->post('field')])) {

            return 'Error parameters';
        }

        $path = '';
        $source = str_replace(base_url(), '', $this->input->post('src'));
        $source = explode('/', $source);

        //prepare path
        foreach ($source as $value) {

            if (empty($value)) {
                continue;
            }

            if (!empty($path)) {
                $path .= '/';
            }

            $path .= $value;
        }

        $lib = $this->_image_uploads[$this->input->post('field')]->get_library();

        if ($lib == 'image_change') {

            $image = $this->load->library('image_change', $path);
            $image->crop($this->input->post('top_x'), $this->input->post('top_y'), $this->input->post('bottom_x'), $this->input->post('bottom_y'));
            $image->save($path);
        } else {

            $this->load->library('image_lib');

            $config['source_image'] = $path;
            $config['width'] = $this->input->post('bottom_x') - $this->input->post('top_x');
            $config['height'] = $this->input->post('bottom_y') - $this->input->post('top_y');
            $config['x_axis'] = $this->input->post('top_x');
            $config['y_axis'] = $this->input->post('top_y');
            $config['maintain_ratio'] = FALSE;

            $this->image_lib->initialize($config);

            if (!$this->image_lib->crop()) {

                return $this->image_lib->display_errors();
            } elseif ($this->_image_uploads[$this->input->post('field')]->get_resize_after_crop()) {

                $this->image_lib->clear();

                $config['source_image'] = $path;
                $config['width'] = intval($_POST['width']);
                $config['height'] = intval($_POST['height']);

                $this->image_lib->initialize($config);

                if (!$this->image_lib->resize()) {
                    return $this->image_lib->display_errors();
                }
            }
        }

        return 'Successful cropped';
    }

}
