<?php

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

class Online extends Gkpos_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('Online_Model');
        $this->load->helper('gkpos');
        $this->load->model('Entry_Model');
        $this->site_title = $this->config->item('gk_name');
        if (!$this->Entry_Model->is_logged_in()) {
            redirect('gkpos/entry');
        }
    }

    public function index() {
        $data['current_section'] = $this->lang->line('gkpos_system_management');
        $data['current_page'] = "settings";
        $data['is_touch'] = $this->config->item('is_touch');
        $this->load->view('gkpos/online/index', $data);
    }

    public function indexcontent() {
        $data['current_section'] = $this->lang->line('gkpos_system_management');
        $data['current_page'] = "settings";
        $data['is_touch'] = $this->config->item('is_touch');
        $this->load->view('gkpos/online/indexcontent', $data);
    }

    public function openinghour() {
        $data['current_section'] = $this->lang->line('gkpos_system_managemen');
        $data['current_page'] = "settings";
        $sevenDays = $this->Online_Model->get_list('servicetime');
        $week = array();
        foreach ($sevenDays as $key => $day) {
            $open = $day->open;
            $open_arr1 = explode(' ', $open);
            $open_arr2 = explode(':', $open_arr1[0]);
            $number_open_hour_time = (int) $open_arr2[0] > 0 ? (int) $open_arr2[0] * 60 : 0;

            $close = $day->closed;
            $close_arr1 = explode(' ', $close);
            $close_arr2 = explode(':', $close_arr1[0]);
            $number_close_hour_time = (int) $close_arr2[0] > 0 ? (int) $close_arr2[0] * 60 : 0;
            if ($number_open_hour_time < $number_close_hour_time) {
                $number_open_hour_time += $open_arr1[1] == 'PM' ? 12 * 60 : 0;
            }
            $number_open_minute_time = (int) $open_arr2[1] > 0 ? (int) $open_arr2[1] : 0;
            $total_open_number_time = $number_open_hour_time + $number_open_minute_time;
            $number_close_hour_time += $close_arr1[1] == 'PM' ? 12 * 60 : 0;
            $number_close_minute_time = (int) $close_arr2[1] > 0 ? (int) $close_arr2[1] : 0;
            $total_close_number_time = $number_close_hour_time + $number_close_minute_time;
            $week[$day->day] = $day;
            $week[$day->day]->opentime = $total_open_number_time;
            $week[$day->day]->closedtime = $total_close_number_time;
        }
        $data['week'] = $week;
        //debugPrint($data);
        $this->load->view('gkpos/online/openinghour', $data);
    }

    public function pagesetup() {
        $data = array();
        $this->current_section = "Online Page Setup";
        $this->load->view('gkpos/online/pagesetup', $data, false);
    }

    public function save_pagesetup() {
        $data = $this->prepareData();
        $result = $this->Appconfig->batch_save($data);
        $success = $result ? true : false;
        $message = $this->lang->line('config_saved_' . ($success ? '' : 'un') . 'successfully');
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function template() {
        $this->page_title = 'Online | Template';
        $this->render_page('gkpos/online/template');
    }

    public function save_tamplate() {
        $wrapper = $this->input->post('wrapper');
        $data = $this->prepareData();
        unset($data['wrapper']);
        $success = $this->db->update('template', $data, array('wrapper' => $wrapper));
        $message = $success ? 'Template saved successfully' : 'Template saved failed';
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function save_openinghour() {
        $day = trim($this->input->post('day'));
        $is_opened = trim($this->input->post('is_opened'));
        $open = trim($this->input->post('open'));
        $closed = trim($this->input->post('closed'));
        $isColTime = trim($this->input->post('isColTime'));
        $isDelTime = trim($this->input->post('isDelTime'));
        $col_time = null;
        $del_time = null;
        if ($isColTime == 'yes') {
            $col_time = $open . '-' . $closed;
        }
        if ($isDelTime == 'yes') {
            $del_time = $open . '-' . $closed;
        }
        $responseDay = 'No days';
        if ($this->db->update('servicetime', array('open' => $open, 'is_opened' => $is_opened, 'closed' => $closed, 'col_time' => $col_time, 'del_time' => $del_time), array('day' => $day))) {
            if ($day == 'mon') {
                $responseDay = "Monday";
            }
            if ($day == 'tue') {
                $responseDay = "Tuesday";
            }
            if ($day == 'wed') {
                $responseDay = "Wednesday";
            }
            if ($day == 'thu') {
                $responseDay = "Thursday";
            }
            if ($day == 'fri') {
                $responseDay = "Friday";
            }
            if ($day == 'sat') {
                $responseDay = "Saturday";
            }
            if ($day == 'sun') {
                $responseDay = "Sunday";
            }
            echo json_encode(array('success' => true, 'message' => ucfirst($responseDay) . ' ' . $this->lang->line('gkpos_update_success')));
        } else {
            echo json_encode(array('success' => false, 'message' => ucfirst($responseDay) . ' ' . $this->lang->line('gkpos_update_failed')));
        }
    }

    public function promotion() {
        $data['current_section'] = 'online promotion';
        $data['current_page'] = "online_promotion";
        $data['voucher_list'] = $this->Online_Model->get_list('promotion');
        $data['promotion_code'] = $this->Online_Model->get_code();
        $this->load->view('gkpos/online/promotion', $data, false);
    }

    public function save_promotion($id = null) {
        $data = array(
            'title' => $this->input->post('title'),
            'code' => $this->input->post('code'),
            'amount' => $this->input->post('amount'),
            'function' => $this->input->post('function'),
            'min_order' => $this->input->post('min_order'),
            'start' => $this->input->post('start'),
            'end' => $this->input->post('end'),
            'is_opened' => $this->input->post('is_opened'),
            'used_as' => $this->input->post('used_as'),
            'delivery' => $this->input->post('delivery'),
            'collection' => $this->input->post('collection'),
            'food' => $this->input->post('food'),
            'nonfood' => $this->input->post('nonfood'),
            'allow_cross' => $this->input->post('allow_cross')
        );
        $exists = $this->Online_Model->exists('promotion', 'LOWER(code)', strtolower($data['code']));
        if ($exists && $id == null) {
            $message = $this->lang->line('gkpos_duplicate_entry') . ' ' . $this->lang->line('gkpos_voucher_code') . ' ' . $data['code'] . ' ' . $this->lang->line('gkpos_already_exists') . ' ' . $this->lang->line('gkpos_try_another');
            $success = false;
            echo json_encode(array('success' => $success, 'message' => $message));
            exit();
        }
        if ($id == null) {
            $data['status'] = 1;
            $data['created_by'] = $this->session->userdata('gkpos_userid');
        }
        if ($id != null && $id > 0) {
            $data['modified'] = date('Y-m-d H:i:s');
            $data['modified_by'] = $this->session->userdata('gkpos_userid');
        }
        $start_date = DateTime::createFromFormat($this->config->item('dateformat'), $data['start'] != null ? $data['start'] : date($this->config->item('dateformat'), strtotime('today')));
        $end_date = DateTime::createFromFormat($this->config->item('dateformat'), $data['end'] != null ? $data['end'] : date($this->config->item('dateformat'), strtotime('today')));
        $data['start'] = $start_date->format('Y-m-d');
        $data['end'] = $end_date->format('Y-m-d');
        $result = $this->Online_Model->save_promotion($data, $id);
        $success = $result ? true : false;
        if ($success) {
            $activity = array(
                'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has created a promotion' . $data['title'] . ' code:' . $data['code']
            );
            $this->Online_Model->posactivity($activity);
        }
        $message = $this->lang->line('config_saved_' . ($success ? '' : 'un') . 'successfully');
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function update_promotion() {
        $action = $this->input->post('action');
        $id = $this->input->post('id');
        if ($action == 'delete') {
            $success = $this->db->delete('promotion', array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has deleted a promotion'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? $this->lang->line('gkpos_delete_success') : $this->lang->line('gkpos_delete_failed');
        }
        if ($action == 'activate') {
            $success = $this->db->update('promotion', array('status' => 1), array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has activated a promotion'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'Voucher activated successfully' : 'Voucher activation failed';
        }
        if ($action == 'deactivate') {
            $success = $this->db->update('promotion', array('status' => 2), array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has deactivated a promotion'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'promotion activated successfully' : 'promotion activattion failed';
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function gateway($id = null) {
        $data = [];
        $data['current_section'] = 'Payment Gateway Setup';
        $data['current_page'] = "gateway";
        $data['voucher_list'] = $this->Online_Model->get_list('payment_gateway');
        $data['toEdit'] = array();
        if ($id != null && (int) $id > 0) {
            $data['toEdit'] = $this->Online_Model->get_list('payment_gateway', array('id' => $id));
        }
        $this->load->view('gkpos/online/gateway', $data, false);
    }

    public function save_gateway() {
        $data = $this->prepareData();
        $success = false;
        $message = null;
        if (isset($data['gateway_id']) != null && (int) $data['gateway_id'] > 0) {
            $id = $data['gateway_id'];
            unset($data['gateway_id']);
            $success = $this->db->update('payment_gateway', $data, array('id' => $id));
            $message = $success == true ? $this->lang->line('gkpos_update_success') : $this->lang->line('gkpos_update_failed');
        } else {
            $success = $this->db->insert('payment_gateway', $data);
            $message = $success == true ? $this->lang->line('gkpos_save_success') : $this->lang->line('gkpos_save_dailed');
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function update_gateway() {
        $action = $this->input->post('action');
        $id = $this->input->post('id');
        if ($action == 'delete') {
            $success = $this->db->delete('payment_gateway', array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has deleted a payment gateway'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'Payment Gateway deleted successfully' : 'Payment Gateway Deletion failed';
        }
        if ($action == 'activate') {
            $success = $this->db->update('payment_gateway', array('status' => 1), array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has activated a Payment Gateway'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'Payment Gateway successfully' : 'Payment Gateway Deletion failed';
        }
        if ($action == 'deactivate') {
            $success = $this->db->update('payment_gateway', array('status' => 2), array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has deactivated a Payment Gateway'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'Payment Gateway activated successfully' : 'Payment Gateway Deletion failed';
        }

        if ($action == 'test') {
            $success = $this->db->update('payment_gateway', array('is_live' => 2), array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has activated a Payment Gateway'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'Payment Gateway Mode Converted successfully' : 'Payment Gateway Deletion failed';
        }
        if ($action == 'live') {
            $success = $this->db->update('payment_gateway', array('is_live' => 1), array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has deactivated a Payment Gateway'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'Payment Gateway Mode Converted successfully' : 'Payment Gateway Deletion failed';
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function home() {
        $data = array();
        $this->current_section = "Home";
        $data['home'] = $this->Online_Model->get_list('page', array('slug' => 'home'));
        $this->load->view('gkpos/online/home', $data, false);
    }

    public function save_home() {
        $data = $this->prepareData();
        $uploader_config = array('upload_path' => 'uploads/page/',
            'allowed_types' => 'gif|jpg|png|jpeg',
            'max_size' => '10000',
            'max_width' => '43000',
            'max_height' => '43000',
            'file_name' => 'image'
        );
        $upload_success = $this->uploadimage($uploader_config);
        $upload_data = $this->upload->data();
        if (!empty($upload_data['orig_name'])) {
            $data['image'] = $upload_data['raw_name'] . $upload_data['file_ext'];
        }
        if (isset($data['slug'])) {
            if (isset($data['image']) && ($data['image'] == '' || $data['image'] == null)) {
                unset($data['image']);
            }
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = $this->session->userdata('gkpos_userid');
            $result = $this->db->update('page', $data, array('slug' => $data['slug']));
        }
        $success = $upload_success && $result ? true : false;
        $message = $this->lang->line('common_item_saved_' . ($success ? '' : 'un') . 'successfully');
        $message = $upload_success ? $message : $this->upload->display_errors();
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function about() {
        $data = array();
        $this->current_section = "About";
        $data['home'] = $this->Online_Model->get_list('page', array('slug' => 'about'));
        $this->load->view('gkpos/online/about', $data, false);
    }

    public function save_about() {
        $data = $this->prepareData();
        $uploader_config = array('upload_path' => 'uploads/page/',
            'allowed_types' => 'gif|jpg|png|jpeg',
            'max_size' => '10000',
            'max_width' => '43000',
            'max_height' => '43000',
            'file_name' => 'image'
        );
        $upload_success = $this->uploadimage($uploader_config);
        $upload_data = $this->upload->data();
        if (!empty($upload_data['orig_name'])) {
            $data['image'] = $upload_data['raw_name'] . $upload_data['file_ext'];
        }
        if (isset($data['slug'])) {
            if (isset($data['image']) && ($data['image'] == '' || $data['image'] == null)) {
                unset($data['image']);
            }
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = $this->session->userdata('gkpos_userid');
            $result = $this->db->update('page', $data, array('slug' => $data['slug']));
        }
        $success = $upload_success && $result ? true : false;
        $message = $this->lang->line('common_item_saved_' . ($success ? '' : 'un') . 'successfully');
        $message = $upload_success ? $message : $this->upload->display_errors();
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function onlineorder() {
        $data = array();
        $this->current_section = "Online Order";
        $data['home'] = $this->Online_Model->get_list('page', array('slug' => 'onlineorder'));
        $this->load->view('gkpos/online/onlineorder', $data, false);
    }

    public function contact() {
        $data = array();
        $this->current_section = "Online Order";
        $data['home'] = $this->Online_Model->get_list('page', array('slug' => 'contact'));
        $this->load->view('gkpos/online/contact', $data, false);
    }

    public function gallery() {
        $data = array();
        $this->current_section = "Online Order";
        $data['home'] = $this->Online_Model->get_list('page', array('slug' => 'gallery'));
        $this->load->view('gkpos/online/gallery', $data, false);
    }

    public function save_common_page() {
        $data = $this->prepareData();
        if (isset($data['slug'])) {
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = $this->session->userdata('gkpos_userid');
            $result = $this->db->update('page', $data, array('slug' => $data['slug']));
        }
        $success = $result ? true : false;
        $message = $this->lang->line('common_item_saved_' . ($success ? '' : 'un') . 'successfully');
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function gallery_images() {
        $this->page_title = 'Dashboard';
        $this->current_section = "Gallery";
        $this->body_class[] = 'dashboard-gallery';
        $data['gallery_images'] = $this->Online_Model->get_list('gallery');
        $this->load->view('gkpos/online/gallery_images', $data, false);
    }

    public function upload_gallery_image() {
        $uploader_config = array('upload_path' => 'uploads/gallery/',
            'allowed_types' => 'gif|jpg|png|jpeg',
            'max_size' => '10000',
            'max_width' => '3000',
            'max_height' => '3000',
            'file_name' => 'image'
        );
        $upload_success = $this->uploadimage($uploader_config);
        $success = false;
        $message = null;
        $upload_data = $this->upload->data();
        if (!empty($upload_data['orig_name'])) {
            $data['image'] = $upload_data['raw_name'] . $upload_data['file_ext'];
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = $this->session->userdata('gkpos_userid');
            $result = $this->db->insert('gallery', $data);
            $success = $upload_success && $result ? true : false;
            $message = $this->lang->line('common_item_saved_' . ($success ? '' : 'un') . 'successfully');
            $message = $upload_success ? $message : $this->upload->display_errors();
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function delete_image() {
        $id = $this->input->post('id');
        if ($this->delete_image_data($id, 'gallery', 'uploads/gallery/')) {
            echo json_encode(array('success' => true, 'message' => $this->lang->line('gkpos_delete_success')));
        } else {
            echo json_encode(array('success' => false, 'message' => $this->lang->line('gkpos_delete_failed')));
        }
    }

    function delete_image_data($id, $table, $path) {
        $query = $this->db->get_where($table, array('id' => $id));
        if ($query->num_rows() > 0) {
            $row = $query->row();
            $picture = $row->image;
            unlink(realpath($path . $picture));
            $this->db->delete('gallery', array('id' => $id));
            return true;
        }
        return false;
    }

    public function footer_links() {
        $data['current_section'] = 'Footer Links';
        $data['current_page'] = "footer_links";
        $this->load->view('gkpos/online/footer_links', $data, false);
    }

    public function save_footer_links() {
        $batch_save_data = array(
            'footer_apple' => $this->input->post('footer_apple'),
            'footer_android' => $this->input->post('footer_android'),
            'footer_instagram' => $this->input->post('footer_instagram'),
            'footer_youtube' => $this->input->post('footer_youtube'),
            'footer_facebook' => $this->input->post('footer_facebook'),
            'footer_pinterest' => $this->input->post('footer_pinterest'),
            'footer_googleplus' => $this->input->post('footer_googleplus'),
            'footer_twitter' => $this->input->post('footer_twitter'),
        );
        $result = $this->Appconfig->batch_save($batch_save_data);
        $success = $result ? true : false;
        if ($success) {
            $activity = array(
                'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has updated footer links setup'
            );
            $this->Online_Model->posactivity($activity);
        }
        $message = $this->lang->line('config_saved_' . ($success ? '' : 'un') . 'successfully');
        echo json_encode(array('success' => $success, 'message' => $message));
    }

    public function listreviews($segment = 0) {
        $data = array();
        $limit = $this->config->item('gk_category_line_page');
        $data['cat_counter'] = $records = $this->Online_Model->count_rows('review');
        $pages = $records > $limit ? $records / $limit : 0;
        $ajaxpages = is_double($pages) ? floor($pages) + 1 : $pages;
        if ($segment <= $ajaxpages) {
            $offset = $segment * $limit;
            $result = $this->Online_Model->get_list('review', null, null, $limit, $offset, 'created_at', 'DESC');
            $data['reviews'] = $result;
            $data['ajaxpages'] = $ajaxpages;
            $data['segment'] = $segment;
            $data['prevPage'] = $segment > 0 ? $segment - 1 : 0;
            $data['nextPage'] = $segment + 1;
            if ($segment + 1 > $pages) {
                $data['nextPage'] = 0;
            }
        } else {
            $data['reviews'] = array();
            $data['ajaxpages'] = 0;
            $data['segment'] = 0;
            $data['prevPage'] = 0;
            $data['nextPage'] = 1;
        }
        // debugPrint($data);
        $this->load->view('gkpos/online/reviews', $data);
    }

    public function update_review() {
        $action = $this->input->post('action');
        $id = $this->input->post('id');
        if ($action == 'delete') {
            $success = $this->db->delete('review', array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has deleted a review'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? $this->lang->line('gkpos_delete_success') : $this->lang->line('gkpos_delete_failed');
        }
        if ($action == 'approve') {
            $success = $this->db->update('review', array('status' => 1), array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has approved a review'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'Review approved successfully' : 'Review approved failed';
        }
        if ($action == 'disapprove') {
            $success = $this->db->update('review', array('status' => 2), array('id' => $id));
            if ($success) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('gkpos_username')) . ' has disapproved a review'
                );
                $this->Online_Model->posactivity($activity);
            }
            $message = $success ? 'Review disapproved successfully' : 'Review disapproval failed';
        }
        echo json_encode(array('success' => $success, 'message' => $message));
    }

}
