<?php

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

class Selection_Model extends MY_Model {

    function __construct() {
        parent::__construct();
        $this->_order_by = 'position';
        $this->_primary_key = 'id';
        $this->_table_name = 'menuselection';
    }

    public function checkme($column, $value, $update = 'no') {
        $category = $this->input->post('category');
        $menu = $this->input->post('menu');
        $old = $this->input->post('old');
        if ($update == 'yes') {
            if (trim(strtolower($old)) === trim(strtolower($value))) {
                return false;
            } else {
                if ($column == 'title') {
                    return $this->selectiontitleexist($column, $value, $category, $menu);
                }
                if ($column == 'code') {
                    return $this->exists($this->_table_name, $column, $value);
                }
            }
        } else {
            if ($column == 'title') {
                return $this->selectiontitleexist($column, $value, $category, $menu);
            }
            if ($column == 'code') {
                return $this->exists($this->_table_name, $column, $value);
            }
        }
    }

    public function selectiontitleexist($column, $value, $category, $menu) {
        $this->db->where($column, $value);
        $this->db->where('category', $category);
        $this->db->where('menu', $menu);
        $this->db->where('branch', $this->session->userdata('branch'));
        return $this->db->count_all_results($this->_table_name) > 0;
    }

    public function save($data, $id = NULL) {
        if ($id !== NULL && $id > 0) {
            $data['updated_by'] = $this->session->userdata('owner');
        }
        return parent::save($data, $id);
    }

    public function deleteSelection($id) {
        return $this->delete($id);
    }

}
