<?php

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

/* * *****************Video.php**********************************
 * @product name    : Hospital Management System
 * @type            : Class
 * @class name      : Video
 * @description     : Manage gallery video.
 * @author          : South Bangla IT Zone Team
 * @url             : http://hms.sbitzone.com
 * @support         : rabibd.it@gmail.com
 * @copyright       : South Bangla IT Zone Team
 * ********************************************************** */

class Video extends MY_Controller {

    public $data = array();

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

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

        check_permission(VIEW);

        $keyword = $this->input->get('keyword');
        $category_id = $this->input->get('category_id');
        $created_by = $this->input->get('created_by');
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($_GET) {
            $config['base_url'] = site_url('gallery/video/?keyword=' . $keyword . '&category_id=' . $category_id . '&created_by=' . $created_by);
        } 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->video->get_video_list($config['per_page'], $offset, $keyword, $category_id, $created_by, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['videos'] = $this->video->get_video_list($config['per_page'], $offset, $keyword, $category_id, $created_by, $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['category_id'] = $category_id;
        $this->data['created_by'] = $created_by;

        $this->data['categories'] = $this->video->get_list('galleries', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['employees'] = $this->video->get_employee_list();

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

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

        check_permission(ADD);
        if ($_POST) {
            $this->_prepare_video_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_video_data();
                $insert_id = $this->video->insert('videos', $data);
                if ($insert_id) {
                    create_log('Has been created a gallery video : ' . $data['title']);
                    success($this->lang->line('insert_success'));
                    redirect('gallery/video');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('gallery/video/add');
                }
            } else {
                $this->data = $_POST;
            }
        }
        $this->data['categories'] = $this->video->get_list('galleries', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('video') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('video/add', $this->data);
    }

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

        check_permission(EDIT);

        if ($_POST) {
            $this->_prepare_video_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_video_data();
                $updated = $this->video->update('videos', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a gallery video : ' . $data['title']);
                    success($this->lang->line('update_success'));
                    redirect('gallery/video');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('gallery/video/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['video'] = $this->video->get_single('videos', array('id' => $this->input->post('id')));
            }
        } else {
            if ($id) {
                $this->data['video'] = $this->video->get_single('videos', array('id' => $id));
                if (!$this->data['video']) {
                    redirect('gallery/video');
                }
            }
        }
        $this->data['categories'] = $this->video->get_list('galleries', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('video') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('video/edit', $this->data);
    }

    /*     * ***************Function get_single_video**********************************
     * @type            : Function
     * @function name   : get_single_video
     * @description     : "Load single video information" from database                  
     *                    to the user interface   
     * @param           : null
     * @return          : null 
     * ********************************************************** */

    public function get_single_video() {
        $id = $this->input->post('id');
        $this->data['video'] = $this->video->get_single_video($id);
        echo $this->load->view('video/view', $this->data);
    }

    /*****************Function _prepare_video_validation**********************************
     * @type            : Function
     * @function name   : _prepare_video_validation
     * @description     : Process "Video" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_video_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('gallery_id', $this->lang->line('category'), 'trim|required');
        $this->form_validation->set_rules('title', $this->lang->line('title'), 'trim|required|callback_title');
        $this->form_validation->set_rules('url', $this->lang->line('url'), 'trim|required');
    }

    /*****************Function title**********************************
     * @type            : Function
     * @function name   : title
     * @description     : Unique check for "Video Title" data/value
     *
     * @param           : null
     * @return          : boolean true/false
     * ********************************************************** */
    public function title() {
        if ($this->input->post('id') == '') {
            $video = $this->video->duplicate_check($this->input->post('gallery_id'), $this->input->post('title'));
            if ($video) {
                $this->form_validation->set_message('title', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else if ($this->input->post('id') != '') {
            $video = $this->video->duplicate_check($this->input->post('gallery_id'), $this->input->post('title'), $this->input->post('id'));
            if ($video) {
                $this->form_validation->set_message('title', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else {
            return TRUE;
        }
    }

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

        $items = array();
        $items[] = 'gallery_id';
        $items[] = 'title';
        $items[] = 'bn_title';
        $items[] = 'url';
        $items[] = 'description';
        $items[] = 'bn_description';
        $items[] = 'remark';
        $items[] = 'sort_by';
        $data = elements($items, $_POST);

        $data['is_view_on_web'] = $this->input->post('is_view_on_web') ?? 0;
        $data['status'] = $this->input->post('status') ?? 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['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();
        }

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


        return $data;
    }

    /*     * ***************Function _upload_image**********************************
     * @type            : Function
     * @function name   : _upload_image
     * @description     : Process to upload video image into server
     *                     and return image file name
     * @param           : null
     * @return          : $return_image 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/gallery-image/';

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

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

                // need to unlink previous image
                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 "Video" data from database
     *
     * @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('gallery/video');
        }

        $video = $this->video->get_single('videos', array('id' => $id));

        if ($this->video->delete('videos', array('id' => $id))) {
            create_log('Has been deleted a gallery video : ' . $video->title);

            // delete image
            $destination = 'assets/uploads/';
            if (file_exists($destination . '/gallery-image/' . $video->image)) {
                @unlink($destination . '/gallery-image/' . $video->image);
            }
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }
}
