<?php

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

class Selection extends Epos_Template {

    private $branch = 0;

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

    public function save($category = null, $menu = null) {
        if (trim($category) && trim($menu)) {
            $data = $this->preparePostedData();
            $data['category'] = trim($category);
            $data['menu'] = trim($menu);
            $insert_id = null;
            $result = true;
            $uploadErrorMessage = '';
            if (!empty($_FILES['image'])) {
                $config = array('upload_path' => './uploads/menuselection/', 'allowed_types' => 'gif|jpg|png|jpeg', 'max_size' => '1000', 'max_width' => '650', 'max_height' => '450', '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'];
                }
            }

            if (!isset($data['id']) || $data['id'] == NULL) {
                $data['created_by'] = $this->session->userdata('owner');
                $data['status'] = 3;
                $data['online'] = 3;
                $data['branch'] = $this->branch;
                $insert_id = $this->Selection_Model->save($data, NULL);
                if ($insert_id) {
                    $activity = array(
                        'activity' => ucfirst($this->session->userdata('name')) . ' has added selection ' . $data['title']
                    );
                    $this->Selection_Model->posactivity($activity);
                }
                $result = $insert_id ? $this->Selection_Model->save(array('position' => $insert_id), $insert_id) : false;
            } else {
                if (empty($data['breakfast'])) {
                    $data['breakfast'] = 'no';
                }
                if (empty($data['launch'])) {
                    $data['launch'] = 'no';
                }
                if (empty($data['dinner'])) {
                    $data['dinner'] = 'no';
                }
                if (empty($data['inline'])) {
                    $data['inline'] = 2;
                }
                if (empty($data['online'])) {
                    $data['online'] = 2;
                }
                $id = $data['id'];
                unset($data['id']);
                $insert_id = $this->Selection_Model->save($data, $id);
                if ($insert_id) {
                    $activity = array(
                        'activity' => ucfirst($this->session->userdata('name')) . ' has updated selection ' . $data['title']
                    );
                    $this->Selection_Model->posactivity($activity);
                }
            }
            if ($insert_id && $this->config->item('znotifysystemupdate') === 'yes') {
                $this->Selection_Model->notifyupdate('zamanDbEposMenuSelection');
            }
            $message = $insert_id && $result ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed') . ' ' . $uploadErrorMessage;
            echo json_encode(array('status' => $insert_id && $result, 'message' => $message, 'category' => trim($category), 'menu' => trim($menu), 'selection' => trim($insert_id)));
        } else {
            echo json_encode(array('status' => false));
        }
    }

    public function checkme() {
        $column = $this->input->post('column');
        $value = $this->input->post('value');
        $update = $this->input->post('update');
        $result = $this->Selection_Model->checkme($column, $value, $update);
        if ($result) {
            echo json_encode(sprintf($this->lang->line('item_already_taken'), $value));
        } else {
            echo json_encode(true);
        }
    }

    public function sortme() {
        $func = $this->input->post('func');
        $id = $this->input->post('id');
        $position = $this->input->post('position');
        $newPosition = $position;
        if ($func == 'up') {
            $newPosition = $position + 1;
        }
        if ($func == 'down' && $position > 1) {
            $newPosition = $position - 1;
        }
        $MinMax = $this->Selection_Model->get_min_max('menuselection', 'position')->row();
        if (true === in_array($newPosition, range($MinMax->min, $MinMax->max))) {
            $s1 = $this->db->update('menuselection', array('position' => $position), array('position' => $newPosition));
            $s2 = $this->db->update('menuselection', array('position' => $newPosition), array('id' => $id));
            if ($s1 && $s2 && $this->config->item('znotifysystemupdate') === 'yes') {
                $this->Selection_Model->notifyupdate('zamanDbEposMenuSelection');
            }
            echo json_encode(array('status' => $s1 && $s2));
        }
    }

    function delete($id = null, $all = false) {
        $row = $this->db->where('id', (int) $id)->get('menuselection')->row();
        if (!empty($row)) {
            //Delete associated Toppings
            $toppinsCategory = $this->db->where('selection', $row->id)->get('menuattrcategory')->result();
            if (!empty($toppinsCategory)) {
                foreach ($toppinsCategory as $tc) {
                    $this->db->where('menuttrcategory', $tc->id)->delete('menuattr');
                }
                $this->db->where('selection', $row->id)->delete('menuattrcategory');
                if ($this->config->item('znotifysystemupdate') === 'yes') {
                    $this->Selection_Model->notifyupdate('zamanDbEposMenuAttrCategory');
                    $this->Selection_Model->notifyupdate('zamanDbEposMenuAttr');
                }
            }
            //Delete associated Modifier
            $modifierCategory = $this->db->where('selection', $row->id)->get('modifiercategory')->result();
            if (!empty($modifierCategory)) {
                foreach ($modifierCategory as $mc) {
                    $this->db->where('modcategory', $mc->id)->delete('modifiermenu');
                }
                $this->db->where('selection', $row->id)->delete('modifiercategory');
                if ($this->config->item('znotifysystemupdate') === 'yes') {
                    $this->Selection_Model->notifyupdate('zamanDbEposModifierCategory');
                    $this->Selection_Model->notifyupdate('zamanDbEposModifierMenu');
                }
            }
            //Delete associated Sets and set element
            $menuSet = $this->db->where('selection', $row->id)->get('menuset')->result();
            if (!empty($menuSet)) {
                foreach ($menuSet as $ms) {
                    $this->db->where('set', $ms->id)->delete('menusetitem');
                }
                $this->db->where('selection', $row->id)->delete('menuset');
                if ($this->config->item('znotifysystemupdate') === 'yes') {
                    $this->Selection_Model->notifyupdate('zamanDbEposMenuSet');
                    $this->Selection_Model->notifyupdate('zamanDbEposMenuSetItem');
                }
            }
            //Delete associated fixed deal element
            $fixedDealItems = $this->Selection_Model->get_list('menufixeddeal', array('deal_selection' => $row->id))->result();
            if (!empty($fixedDealItems)) {
                $this->db->where('deal_selection', $row->id);
                $this->db->or_where('selection', $row->id);
                $menufixeddealDeleteStatus = $this->db->delete('menufixeddeal');
                if ($menufixeddealDeleteStatus && $this->config->item('znotifysystemupdate') === 'yes') {
                    $this->Selection_Model->notifyupdate('zamanDbEposFixedDealItems');
                }
            } else {
                $this->db->where('selection', $row->id)->delete('menufixeddeal');
            }
            //Delete associated image
            if (trim($row->image)) {
                $status = checkfile('./uploads/menuselection/', $row->image);
                if ($status) {
                    unlink(realpath('./uploads/menuselection/' . $row->image));
                }
            }
        }
        $hasDeletedId = $this->Selection_Model->deleteSelection($id);
        if ($hasDeletedId) {
            if ($this->config->item('znotifysystemupdate') === 'yes') {
                $this->Selection_Model->notifyupdate('zamanDbEposMenuSelection');
            }
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has deleted selection ' . $row->title
            );
            $this->Selection_Model->posactivity($activity);
        }
        if ($all) {
            return $hasDeletedId;
        } else {
            echo json_encode(array('status' => $hasDeletedId));
        }
    }

    function deleteAll($menu) {
        $rows = $this->Selection_Model->get_list('menuselection', array('menu' => (int) $menu, 'branch' => $this->session->userdata('branch')), array('id'))->result();
        $status = false;
        if (!empty($rows)) {
            foreach ($rows as $arow) {
                $status = $this->delete($arow->id, true);
            }
        }
        echo json_encode(array('status' => $status));
    }

}
