<?php

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

class Page extends Epos_Template {

    function __construct() {
        parent::__construct();
        $this->load->model('Page_Model');
        if ($this->Page_Model->isThisUserAnEposLogger() && (($this->cookies && !empty($this->cookies)) || ($this->session->userdata('group') == 2))) {
            return true;
        } else {
            redirect('user/login/index/' . $this->session->userdata('branch') . '/' . $this->session->userdata('team'));
        }
    }

    public function index($id = null) {
        $data['pageList'] = $this->Page_Model->get_list('page', array('branch' => $this->session->userdata('branch')))->result();
        $data['page'] = array();
        foreach ($data['pageList'] as $page) {
            if ($page->slug === 'home') {
                $data['page'] = (array) $page;
            }
        }
        if ($id) {
            $data['page'] = $this->Page_Model->get_single('page', array('id' => $id))->row_array();
        }
        $data['refresh'] = base_url(uri_string());
        $this->load->view('page/index', $data, false);
    }

    public function save() {
        $data = $this->preparePostedData();
        $uploadStatus = true;
        $uploadErrorMessage = null;
        if (!empty($_FILES['image'])) {
            $config = array('upload_path' => './uploads/page', 'allowed_types' => 'gif|jpg|png|jpeg', 'max_size' => '1000', 'max_width' => '2300', 'max_height' => '2300', 'overwrite' => true);
            $uploadStatus = $this->uploadimage($config, 'image');
            $uploadErrorMessage = $uploadStatus ? null : $this->upload->display_errors();
            $upload_data = $this->upload->data();
            if ($uploadStatus && !empty($upload_data['orig_name'])) {
                $data['image'] = $upload_data['raw_name'] . $upload_data['file_ext'];
            }
        }
        $id = $data['id'];
        unset($data['id']);
        $insert_id = $this->Page_Model->savePage($data, $id);
        if ($insert_id) {
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has updated page #' . $data['title']
            );
            $this->Page_Model->posactivity($activity);
        }
        $message = $insert_id ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed');
        echo json_encode(array('status' => $insert_id, 'message' => $message, 'id' => $insert_id));
    }

    public function removePageImage($id) {
        $data = $this->input->post();
        $status = checkfile($data['path'], $data['image']);
        if ($status) {
            $result = $this->Page_Model->savePage(array('image' => ''), $id);
            unlink(realpath($data['path'] . $data['image']));
            if (!checkfile($data['path'], $data['image']) && $result) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('name')) . ' has deleted a page #' . $id . ' photo'
                );
                $this->Page_Model->posactivity($activity);
                echo json_encode(array('status' => $result, 'id' => $id, 'message' => $this->lang->line('delete_success')));
            } else {
                echo json_encode(array('status' => false, 'message' => $this->lang->line('delete_failed')));
            }
        }
    }

    public function externallink() {
        $data['refresh'] = base_url(uri_string());
        $data['pageList'] = $this->Page_Model->get_list('page', array('branch' => $this->session->userdata('branch')))->result();
        $data['externallink'] = $this->Page_Model->get_list('extranallinks', array('branch' => $this->session->userdata('branch')))->result();
        $this->load->view('page/externallink', $data, false);
    }

    public function saveExternallink() {
        $data = $this->preparePostedData();
        foreach ($data as $key => $value) {
            $this->db->update('extranallinks', array('link' => $value), array('slug' => $key, 'branch' => $this->session->userdata('branch')));
        }
        echo json_encode(array('status' => true));
    }

    public function uploadGalleryImage() {
        $data['refresh'] = base_url(uri_string());
        $data['pageList'] = $this->Page_Model->get_list('page', array('branch' => $this->session->userdata('branch')))->result();
        $data['images'] = $this->Page_Model->get_list('gallery', array('branch' => $this->session->userdata('branch')))->result();
        $this->load->view('page/gallery', $data, false);
    }

    public function saveUploadedGalleryImage() {
        $message = "Please select a iamge first";
        if (!empty($_FILES['image'])) {
            $config = array('upload_path' => './uploads/gallery', 'allowed_types' => 'gif|jpg|png|jpeg', 'max_size' => '1000', 'max_width' => '2300', 'max_height' => '2300', 'overwrite' => true);
            $uploadStatus = $this->uploadimage($config, 'image');
            $upload_data = $this->upload->data();
            $uploadErrorMessage = $uploadStatus ? $message : $this->upload->display_errors();
            $saveStatus = false;
            if ($uploadStatus && !empty($upload_data['orig_name'])) {
                $data['image'] = $upload_data['raw_name'] . $upload_data['file_ext'];
                $data['branch'] = $this->session->userdata('branch');
                $saveStatus = $this->db->insert('gallery', $data);
            }
            echo json_encode(array('status' => $uploadStatus && $saveStatus, 'message' => $uploadErrorMessage));
        } else {
            echo json_encode(array('status' => FALSE, 'message' => 'Please select image first'));
        }
    }

    public function removeGalleryImage() {
        $data = $this->input->post();
        $status = checkfile('./uploads/gallery/', $data['image']);
        if ($status) {
            unlink(realpath('./uploads/gallery/' . $data['image']));
            echo json_encode(array('status' => $this->db->delete('gallery', array('id' => $data['id']))));
        } else {
            echo json_encode(array('status' => $this->db->delete('gallery', array('id' => $data['id']))));
        }
    }

    public function riviewlist() {
        $data['list'] = $this->Page_Model->get_list('review')->result();
        $data['refresh'] = base_url(uri_string());
        $data['pageList'] = $this->Page_Model->get_list('page', array('branch' => $this->session->userdata('branch')))->result();
        $this->load->view('page/reviews', $data, false);
    }
    public function emailSubscriber() {
        $data['list'] = $this->Page_Model->get_list('subscription')->result();
        $data['refresh'] = base_url(uri_string());
        $data['pageList'] = $this->Page_Model->get_list('page', array('branch' => $this->session->userdata('branch')))->result();
        $this->load->view('page/emailSubscriber', $data, false);
    }

    public function changeReviewStatus() {
        $id = $this->input->post('id');
        $action = $this->input->post('status');
        $status = $action == 'approve' ? 3 : 2;
        $success = $this->db->update('review', array('status' => $status), array('id' => $id));
        $message = $success ? 'Ok' : "Sorry your update failed, try again";
        echo json_encode(array('status' => $success, 'message' => $message));
    }

}
