<?php

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

/* * *****************Slider.php**********************************
 * @product name    : CMS Management System
 * @type            : Class
 * @class name      : Slider
 * @description     : Manage Slider frontend website. 
 * @author          : South Bangla IT Zone Team
 * @url             : http://cms.sbitzone.com
 * @support         : rabibd.it@gmail.com
 * @copyright       : South Bangla IT Zone Team
 * ********************************************************** */

class Slider extends MY_Controller {

    public $data = array();

    function __construct() {
        parent::__construct();
        $this->load->model('Slider_Model', 'slider', true);
    }

    /*****************Function index**********************************
     * @type            : Function
     * @function name   : index
     * @description     : Load "Slider List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function index() {

        check_permission(VIEW);

        $keyword = $this->input->get('keyword');
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($keyword) {
            $config['base_url'] = site_url('frontend/slider/?keyword=' . $keyword);
        } else {
            $config['base_url'] = current_url();
        }
        if ($this->input->get('page')) {
            $sgm = (int) trim($this->input->get('page'));
            $offset = $config['per_page'] * ($sgm - 1);
        } else {
            $offset = 0;
        }

        $config['total_rows'] = $this->slider->get_slider_list($config['per_page'], $offset, $keyword, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['sliders'] = $this->slider->get_slider_list($config['per_page'], $offset, $keyword, $count = FALSE);
        $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        $this->data['keyword'] = $keyword;

        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_slider') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('slider/index', $this->data);
    }

    /*****************Function add**********************************
     * @type            : Function
     * @function name   : add
     * @description     : Load "Add new Slider" user interface
     *                    and process to store "Slider" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function add() {

        check_permission(ADD);

        if ($_POST) {
            $this->_prepare_slider_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_slider_data();
                $insert_id = $this->slider->insert('sliders', $data);
                if ($insert_id) {
                    create_log('Has been upload slider image : ' . $data['title']);
                    success($this->lang->line('insert_success'));
                    redirect('frontend/slider');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('frontend/slider/add');
                }
            } else {
                $this->data = $_POST;
            }
        }

        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('slider') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('slider/add', $this->data);
    }

    /*****************Function edit**********************************
     * @type            : Function
     * @function name   : edit
     * @description     : Load Update "Slider" user interface
     *                    with populate "Slider" value
     *                    and process to update "Slider" into database
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function edit($id = null) {

        check_permission(EDIT);

        if ($_POST) {
            $this->_prepare_slider_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_slider_data();
                $updated = $this->slider->update('sliders', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated uploaded slider image : ' . $data['title']);
                    success($this->lang->line('update_success'));
                    redirect('frontend/slider');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('frontend/slider/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['slider'] = $this->slider->get_single('sliders', array('id' => $this->input->post('id')));
            }
        } else {
            if ($id) {
                $this->data['slider'] = $this->slider->get_single('sliders', array('id' => $id));
                if (!$this->data['slider']) {
                    redirect('frontend/slider');
                }
            }
        }

        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('slider') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('slider/edit', $this->data);
    }

    /*     * ***************Function _prepare_slider_validation**********************************
     * @type            : Function
     * @function name   : _prepare_slider_validation
     * @description     : Process "slider" user input data validation                 
     *                       
     * @param           : null
     * @return          : null 
     * ********************************************************** */

    private function _prepare_slider_validation() {
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
        $this->form_validation->set_rules('title', $this->lang->line('title'), 'trim|required');
        $this->form_validation->set_rules('image', $this->lang->line('slider') . ' ' . $this->lang->line('image'), 'trim|callback_image');
    }

    /*     * ***************Function image**********************************
     * @type            : Function
     * @function name   : image
     * @description     : validate  slider  image type/format                  
     *                       
     * @param           : null
     * @return          : boolean true/false 
     * ********************************************************** */

    public function image() {

        if ($this->input->post('id')) {
            if (!empty($_FILES['image']['name'])) {
                $name = $_FILES['image']['name'];
                $arr = explode('.', $name);
                $ext = end($arr);
                if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif') {
                    return TRUE;
                } else {
                    $this->form_validation->set_message('image', $this->lang->line('select_valid_file_format'));
                    return FALSE;
                }
            }
        } else {
            if (isset($_FILES['image']['name'])) {
                $name = $_FILES['image']['name'];
                $arr = explode('.', $name);
                $ext = end($arr);
                if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif') {
                    return TRUE;
                } else {
                    $this->form_validation->set_message('image', $this->lang->line('select_valid_file_format'));
                    return FALSE;
                }
            } else {
                $this->form_validation->set_message('image', $this->lang->line('required_field'));
                return FALSE;
            }
        }
    }

    /*     * ***************Function _get_posted_slider_data**********************************
     * @type            : Function
     * @function name   : _get_posted_slider_data
     * @description     : Prepare "slider" user input data to save into database                  
     *                       
     * @param           : null
     * @return          : $data array(); value 
     * ********************************************************** */

    private function _get_posted_slider_data() {

        $items = array();
        $items[] = 'title';
        $items[] = 'type';
        $items[] = 'note';
        $items[] = 'sort_by';

        $data = elements($items, $_POST);

        $data['is_view_on_web'] = $this->input->post('is_view_on_web') ?? 0;

        if ($this->input->post('id')) {
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = logged_in_user_id();
        } else {
            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();
        }

        if (isset($_FILES['image']['name'])) {
            $data['image'] = $this->_upload_image();
        }

        return $data;
    }

    /*     * ***************Function _upload_slider**********************************
     * @type            : Function
     * @function name   : _upload_slider
     * @description     : Process to to upload slider in the server
     *                    and return slider name                   
     *                       
     * @param           : null
     * @return          : $return_slider string value 
     * ********************************************************** */

    private function _upload_image() {

        $prev_image = $this->input->post('prev_image');
        $image = $_FILES['image']['name'];
        $image_type = $_FILES['image']['type'];
        $return_image = '';
        if ($image != "") {
            if (
                $image_type == 'image/jpeg' || $image_type == 'image/pjpeg' ||
                $image_type == 'image/jpg' || $image_type == 'image/png' ||
                $image_type == 'image/x-png' || $image_type == 'image/gif'
            ) {

                $destination = 'assets/uploads/slider/';

                $file_type = explode(".", $image);
                $extension = strtolower($file_type[count($file_type) - 1]);
                $image_path = 'slider-' . time() . '-hms.' . $extension;

                move_uploaded_file($_FILES['image']['tmp_name'], $destination . $image_path);

                // need to unlink previous slider
                if ($prev_image != "") {
                    if (file_exists($destination . $prev_image)) {
                        @unlink($destination . $prev_image);
                    }
                }

                $return_image = $image_path;
            }
        } else {
            $return_image = $prev_image;
        }

        return $return_image;
    }

    /*     * ***************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "slider" from database                  
     *                    and unlink slider from server   
     * @param           : $id integer value
     * @return          : null 
     * ********************************************************** */

    public function delete($id = null) {

        check_permission(DELETE);

        if (!is_numeric($id)) {
            error($this->lang->line('unexpected_error'));
            redirect('frontend/slider');
        }

        $slider = $this->slider->get_single('sliders', array('id' => $id));
        if ($this->slider->delete('sliders', array('id' => $id))) {
            // delete slider
            $destination = 'assets/uploads/';
            if (file_exists($destination . '/slider/' . $slider->image)) {
                @unlink($destination . '/slider/' . $slider->image);
            }
            create_log('Has been deletd a slider image : ' . $slider->title);
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }
}
