<?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($how = false) {
        if ($this->session->userdata('group') <= 5) {
            $data['refresh'] = base_url(uri_string());
            $group = $this->session->userdata('group');
            $team = $this->session->userdata('team');
            if ($group == 4) {
                $data['users'] = $this->User_Model->get_list('user', array('group >=' => $group, 'branch' => $this->session->userdata('branch')), null, null, 0, 'team, group', 'ASC')->result();
            } else if ($group == 5) {
                $data['users'] = $this->User_Model->get_list('user', array('group >=' => $group, 'team' => $team, 'branch' => $this->session->userdata('branch')), null, null, 0, 'team, group', 'ASC')->result();
            } else {
                if ($group <= 3) {
                    $data['users'] = $this->User_Model->get_list('user', array('group >=' => $group, 'branch' => $this->session->userdata('branch')), null, null, 0, 'team, group', 'ASC')->result();
                }
            }
            if ($how == 'verified') {
                $this->render('index', $data);
            } else {
                $this->load->view('index', $data, false);
            }
        }
    }

    public function add($id = null) {
        if ($this->session->userdata('group') <= 5) {
            $data['branches'] = $this->User_Model->get_list('branch', array('id' => $this->session->userdata('branch')))->result();
            $data['teams'] = $this->User_Model->get_list('userteam', array('branch' => $this->session->userdata('branch')), array('id', 'title'))->result();
            $data['employees'] = $this->User_Model->employeeYetToUser($this->session->userdata('branch'));
            $data['services'] = $this->User_Model->get_single('service', array('branch' => $this->session->userdata('branch')))->row_array();
            if ($id) {
                $data['thisUser'] = $this->User_Model->get_single('user', array('id' => $id, 'branch' => $this->session->userdata('branch')))->row_array();
            }
            $data['refresh'] = base_url(uri_string());
            $this->load->view('add', $data, false);
        }
    }

    function getUserteam() {
        if ($this->session->userdata('group') <= 5) {
            $branch = $this->input->post('branch');
            $managers = $this->User_Model->get_list('userteam', array('branch' => $branch), array('id', 'title'))->result();
            $employees = $this->User_Model->employeeYetToUser($branch);
            $services = $this->User_Model->get_single('service', array('branch' => $branch))->row();
            $status = !empty($managers) ? true : false;
            echo json_encode(array('status' => $status, 'managers' => $managers, 'employees' => $employees, 'services' => $services));
        }
    }

    public function save() {
        if ($this->session->userdata('group') <= 5) {
            $data = $this->preparePostedData();
            if ($this->session->userdata('group') == 2 && isset($data['onapp'])) {
                $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));
        }
    }

    public function logtime($dateStart = null, $dateEnd = null) {
        if ($this->session->userdata('group') <= 5) {
            $actualStartDate = null;
            $actualEndDate = null;
            if (trim($dateStart)) {
                $actualStartDate = date('d-m-Y H:i:s', strtotime($dateStart . ' ' . date('H:i:s', mktime(0, 0, 0))));
            } else {
                $actualStartDate = date('d-m-Y', strtotime('today')) . ' ' . date('H:i:s', mktime(0, 0, 0));
            }
            $loginStartDateObj = DateTime::createFromFormat('d-m-Y H:i:s', $actualStartDate);
            $start = $loginStartDateObj->format('Y-m-d H:i:s');
            if (trim($dateEnd)) {
                $actualEndDate = date('d-m-Y H:i:s', strtotime($dateEnd . ' ' . date('H:i:s', mktime(23, 59, 59))));
            } else {
                if (trim($dateStart)) {
                    $actualEndDate = date('d-m-Y H:i:s', strtotime($dateStart . ' ' . date('H:i:s', mktime(23, 59, 59))));
                } else {
                    $actualEndDate = date('d-m-Y', strtotime('today')) . ' ' . date('H:i:s', mktime(23, 59, 59));
                }
            }
            $loginEndDateObj = DateTime::createFromFormat('d-m-Y H:i:s', $actualEndDate);
            $end = $loginEndDateObj->format('Y-m-d H:i:s');
            $data['logtimes'] = $this->User_Model->getEposLogtime($start, $end);
            $data['log_start'] = $loginStartDateObj->format('d-m-Y');
            $data['log_end'] = $loginEndDateObj->format('d-m-Y');
            $data['refresh'] = base_url(uri_string());
            $this->load->view('logtime', $data, false);
        }
    }

    public function activity($dateStart = null, $dateEnd = null) {
        if ($this->session->userdata('group') <= 4) {
            $actualStartDate = null;
            $actualEndDate = null;
            if (trim($dateStart)) {
                $actualStartDate = date('d-m-Y H:i:s', strtotime($dateStart . ' ' . date('H:i:s', mktime(0, 0, 0))));
            } else {
                $actualStartDate = date('d-m-Y', strtotime('today')) . ' ' . date('H:i:s', mktime(0, 0, 0));
            }
            $loginStartDateObj = DateTime::createFromFormat('d-m-Y H:i:s', $actualStartDate);
            $start = $loginStartDateObj->format('Y-m-d H:i:s');
            if (trim($dateEnd)) {
                $actualEndDate = date('d-m-Y H:i:s', strtotime($dateEnd . ' ' . date('H:i:s', mktime(23, 59, 59))));
            } else {
                if (trim($dateStart)) {
                    $actualEndDate = date('d-m-Y H:i:s', strtotime($dateStart . ' ' . date('H:i:s', mktime(23, 59, 59))));
                } else {
                    $actualEndDate = date('d-m-Y', strtotime('today')) . ' ' . date('H:i:s', mktime(23, 59, 59));
                }
            }
            $loginEndDateObj = DateTime::createFromFormat('d-m-Y H:i:s', $actualEndDate);
            $end = $loginEndDateObj->format('Y-m-d H:i:s');
            $data['logtimes'] = $this->User_Model->getActivity($start, $end);
            $data['log_start'] = $loginStartDateObj->format('d-m-Y');
            $data['log_end'] = $loginEndDateObj->format('d-m-Y');
            $data['refresh'] = base_url(uri_string());
            $this->load->view('activity', $data, false);
        }
    }

    public function team($id = null) {
        if ($this->session->userdata('group') == 2) {
            $this->page_title = $this->lang->line('employee') . ' | ' . $this->lang->line('manager');
            $data['branches'] = $this->User_Model->get_list('branch', array('id' => $this->session->userdata('branch')))->result();
            $data['managers'] = $this->User_Model->get_list('userteam', array('branch' => $this->session->userdata('branch')))->result();
            if ($id) {
                $data['thisManager'] = $this->User_Model->get_single('userteam', array('id' => $id))->row_array();
            }
            $data['refresh'] = base_url(uri_string());
            $this->load->view('team', $data, false);
        }
    }

    function saveuserteam() {
        if ($this->session->userdata('group') == 2) {
            $data = $this->preparePostedData();
            $insert_id = null;
            if (!isset($data['id']) || $data['id'] == NULL) {
                $insert_id = $this->User_Model->saveuserteam($data, NULL);
                if ($insert_id) {
                    $activity = array(
                        'activity' => ucfirst($this->session->userdata('name')) . ' has created user manager ' . $data['title']
                    );
                    $this->User_Model->posactivity($activity);
                }
            } else {
                $id = $data['id'];
                unset($data['id']);
                $insert_id = $this->User_Model->saveuserteam($data, $id);
                if ($insert_id) {
                    $activity = array(
                        'activity' => ucfirst($this->session->userdata('name')) . ' has updated manager ' . $data['title']
                    );
                    $this->User_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, 'manager' => $insert_id));
        }
    }

    public function updateProfile() {
        $data = $this->preparePostedData();
        if (trim($data['password'])) {
            $data['password'] = md5($data['password']);
        } else {
            unset($data['password']);
        }
        unset($data['confirmPassword']);
        $status = $this->User_Model->save($data, $this->session->userdata('owner'));
        if ($status && isset($data['eposStyle'])) {
            $this->session->set_userdata('eposStyle', $data['eposStyle']);
            $this->session->set_userdata('beep', $data['beep']);
            $this->session->set_userdata('beepLabel', $data['beepLabel']);
        }
        echo json_encode(array('status' => $status));
    }

    function update() {
        $issue = $this->input->post('issue');
        $issueId = $this->User_Model->get_single('updateissue', array('title' => $issue))->row()->id;
        $status = false;
        $thisUser = $this->db->where(array('id' => $this->session->userdata('owner'), 'hasUpdate' => 'yes'))->get('user')->row();
        if (!empty($thisUser)) {
            $status = $this->db->update('updates', array('status' => 3), array('user' => $thisUser->id, 'issue' => $issueId));
        }
        $pendingUpdates = $updates = $this->db->where(array('status' => 2, 'user' => $thisUser->id))->get('updates')->result();
        if (count($pendingUpdates) < (int) 1) {
            $this->db->update('user', array('hasUpdate' => 'no'), array('id' => (int) $thisUser->id));
        }
        echo json_encode(array('status' => true, 'issuesPending' => count($pendingUpdates)));
    }

    function changeOwnerUpdateStatus() {
        $status1 = $this->db->update('user', array('hasUpdate' => 'no'), array('id' => (int) $this->session->userdata('owner')));
        $status2 = $this->db->update('updates', array('status' => 3), array('user' => $this->session->userdata('owner')));
        echo json_encode(array('status' => $status1 && $status2));
    }

    public function logout($branch = null, $team = null) {
        $usserAccessID = $this->session->userdata('usserAccessID');
        $branchId = $branch ? $branch : $this->session->userdata('loginBranch');
        $teamId = $team ? $team : $this->session->userdata('loginTeam');
        $status = $this->User_Model->eposUserLogs(array('logout' => date('Y-m-d H:i:s')), array('id' => $usserAccessID));
        if ($status) {
            $isloggedOut = $this->User_Model->eposUserLogout();
            if ($isloggedOut) {
                redirect('user/login/index/' . $branchId . '/' . $teamId);
            }
        }
    }

}
