<?php

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

class User extends Epos_Template {

    function __construct() {
        parent::__construct();
        $this->load->model('User_Model');
        if ($this->User_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) {
        $services = $this->User_Model->get_list('service', array('status' => '3'))->result();
        $organizedServices = array();
        if (!empty($services)) {
            foreach ($services as $key => $aService) {
                $organizedServices[$aService->title] = $aService;
            }
        }
        $data['services'] = $organizedServices;
        $data['employees'] = $this->User_Model->get_list('employee', array('status' => '3'))->result();
        $data['users'] = $this->User_Model->get_list('user', array('group >=' => 3, 'employee>=' => '1'))->result();
        if ($id) {
            $data['thisUser'] = $this->User_Model->get_list('user', array('id' => $id))->row_array();
        }
        $data['refresh'] = site_url('settings/user');
        $this->load->view('settings/user/index', $data, false);
    }

    public function add() {
        $data = $this->preparePostedData();
        $data['onapp'] = serialize($data['onapp']);
        if (trim($data['password'])) {
            $data['password'] = md5($data['password']);
        } else {
            unset($data['password']);
        }
        $status = false;
        unset($data['confirmedPassword']);
        if (isset($data['id']) && (int) $data['id'] > 0) {
            $id = $data['id'];
            unset($data['id']);
            $status = $this->User_Model->save($data, $id);
        } else {
            $status = $this->User_Model->save($data);
        }
        echo json_encode(array('status' => $status));
    }

}
