<?php

class Branch {

    private $db;
    private $info;

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
    }

    public function setData(array $info) {
        $this->info = $info;
        return $this;
    }

    public function create() {
        $logged_id = Session::getUserID();

        foreach ($this->info['Branch'] as $item) {

            $this->db->prepare_Stmt('
			INSERT INTO tbl_hrm_branch
                        (Branch_Name,Logged_ID,department_id)
			VALUES 
                        (?,?,?)
		', [&$item['Branch_Name'], &$logged_id, &$this->info['Department_ID']]);
        }
        $error = $this->db->error();
        return $error;
    }

    public function view() {
        $data = array();
        $query = '
			SELECT * FROM tbl_hrm_branch WHERE Status_ID = 1
		';
        $result = $this->db->query($query);
        while ($row = $this->db->assoc($result))
            $data[] = $row;
        return $data;
    }

    public function isDepartmentExistRelatedPrefix($prefix, $dep_id = null) {
        //here if new prefix 'A' and already exist 'A1' or 'ABC' or 'Axxx' we must disabled add that prefix, in inverse way if the prefix
        //is 'ABX' then we must prevent add it if already exist prefix: 'A', 'AB' .. but we can add same prefix if we want..
        if (empty($prefix))
            return false;

        $query = $this->db->prepare_Stmt("SELECT department_id FROM `tbl_department` 
            WHERE `department_prefix` != '' " . (empty($dep_id) ? " " : " and department_id <> '{$dep_id}' ") . " and `department_prefix` <> ? 
                and (`department_prefix` = SUBSTRING(?, 1, CHAR_LENGTH(`department_prefix`)) || ? = SUBSTRING(`department_prefix`, 1, CHAR_LENGTH(?)))"
                , [&$prefix, &$prefix, &$prefix, &$prefix]);

        if ($this->db->rowsno($query) > 0)
            return true;
        return false;
    }

    public function createDepartment() {
//        if ($this->isDepartmentExistRelatedPrefix($this->info['Department_Prefix']))
//            return 'errorrrr prefix';
        $logged_id = Session::getUserID();
        $this->db->prepare_Stmt('
			INSERT INTO tbl_department
                        (department_name,department_phone,department_location,Parent_ID,Logged_ID)
			VALUES 
                        (?,?,?,?,?)
		', [&$this->info['Department_Name'], &$this->info['department_phone'], &$this->info['department_location'],
            &$this->info['Parent_ID'], &$logged_id]);
        $error = $this->db->error();
        if (empty($error))
            return $this->db->id();
        return $error;
    }

    public function updateParentForDepartment($Department_ID, $Parent_ID) {
        $logged_id = Session::getUserID();
        $this->db->prepare_Stmt('UPDATE tbl_department SET parent_id= ? ,Logged_ID=? WHERE department_id =?', [&$Parent_ID, &$logged_id, &$Department_ID]);
        $error = $this->db->error();
        return $error;
    }

    public function updateDepartment($Department_ID) {
//        if ($this->isDepartmentExistRelatedPrefix($this->info['Department_Prefix'], $Department_ID))
//            return 'errorrrr prefix';
        $logged_id = Session::getUserID();
        //
//        $query = $this->db->prepare_Stmt('Select * FROM tbl_department WHERE department_id = ? ', [&$Department_ID]);
//        $old_row = $this->db->assoc($query);
        //
        $this->db->prepare_Stmt('UPDATE tbl_department SET department_name= ? ,
            department_phone=?,department_location=?,
            Logged_ID=? WHERE department_id =?', [&$this->info['Department_Name'],
            &$this->info['department_phone'], &$this->info['department_location'], &$logged_id, &$Department_ID]);
        $error = $this->db->error();
        //
//        if (!$error && $old_row['department_prefix'] != $this->info['Department_Prefix']) {
//            $this->db->prepare_Stmt('UPDATE tbl_hrm_employee SET Employee_Work_ID = REPLACE(Employee_Work_ID, ?, ?) where Branch_ID =?', [&$old_row['department_prefix'], &$this->info['Department_Prefix'], &$Department_ID]);
//            $error = $this->db->error();
//        }
        return $error;
    }

    public function deleteDepartment($Department_ID) {
        $query = $this->db->prepare_Stmt('SELECT Employee_ID  FROM tbl_hrm_employee where Status_ID = 1 and  Branch_ID = ? limit 1 ', [&$Department_ID]);
        if ($this->db->rowsno($query))
            return 1;
        $query1 = $this->db->prepare_Stmt('SELECT  department_id  FROM tbl_department where Status_ID = 1 and  parent_id = ? limit 1 ', [&$Department_ID]);
        if ($this->db->rowsno($query1))
            return 2;
        $this->db->prepare_Stmt('DELETE FROM tbl_department WHERE department_id = ?', [&$Department_ID]);
        $error = $this->db->error();
        if (empty($error))
            return implode('<br/>', $error);
        return 0;
    }

    public function viewDepartment($id = null) {
        $cond = '';
        if (!is_null($id)) {

            $cond .= ' and  parent_id = "' . $id . '"';
        } else {
            $cond .= ' and parent_id = 0';
        }

        $data = array();
        $query = $this->db->query('Select * FROM tbl_department where 1=1 ' . $cond);


        while ($row = $this->db->assoc($query))
            $data[] = $row;
        return $data;
    }

    public function viewAllDepartment() {
        $data = array();
        $query = $this->db->query('Select * FROM tbl_department where status_id = 1 ');
        while ($row = $this->db->assoc($query))
            $data[] = $row;
        return $data;
    }

    public function searchDepartment($term = null, $page, $limit) {
        $data = array();
        $data['is_more'] = false;
        $data['data'] = array();
        $cond = '';
        if (!is_null($term)) {
            $cond .= ' and tbl_department.department_name LIKE "%' . $term . '%"';
        }
        $query = $this->db->query('select 
                                    tbl_department.department_id as id,
       concat(if(isNull(parent_dep.department_id),"",concat(parent_dep.department_name, " - ")), tbl_department.department_name) as text FROM tbl_department 
            left join tbl_department as parent_dep on tbl_department.Parent_ID = parent_dep.department_id where tbl_department.status_id = 1
        ' . $cond . ' limit ' . ($page * $limit) . ',' . ($limit + 1));

        while ($row = $this->db->assoc($query)) {
            $data['data'][] = $row;
        }
        if (count($data['data']) > $limit) {
            array_pop($data['data']);
            $data['is_more'] = true;
        }
        return $data;
    }

    public function searchBranch($term = null, $page, $limit) {
        $data = array();
        $data['is_more'] = false;
        $data['data'] = array();
        $cond = '';
        if (!is_null($term)) {
            $cond .= ' AND Branch_Name LIKE "%' . $term . '%"';
        }
        $query = $this->db->query('select 
                                    Branch_ID as id,
                                    Branch_Name as text
                                from 
                                    tbl_hrm_branch
                                    where status_id = 1 
                                ' . $cond . '
                                limit ' . ($page * $limit) . ',' . ($limit + 1));
        while ($row = $this->db->assoc($query)) {
            $data['data'][] = $row;
        }
        if (count($data['data']) > $limit) {
            array_pop($data['data']);
            $data['is_more'] = true;
        }
        return $data;
    }

    public function updateBranch($Branch_ID) {
        $logged_id = Session::getUserID();

        foreach ($this->info['Branch'] as $item) {


            $this->db->prepare_Stmt('UPDATE tbl_hrm_branch SET Branch_Name= ? ,Logged_ID=?,department_id=? WHERE Branch_ID =?', [&$item['Branch_Name'], &$logged_id, &$this->info['Department_ID'], &$Branch_ID]);
        }
        $error = $this->db->error();
        return $error;
    }

    public function deleteBranch($Branch_ID) {
        $logged_id = Session::getUserID();
        $this->db->prepare_Stmt('DELETE FROM tbl_hrm_branch WHERE Branch_ID = ?', [&$Branch_ID]);
        $error = $this->db->error();
        return $error;
    }

    public function viewAllDepartmentByTree($id) {
        if (empty($id)) {
            $query = $this->db->prepare_Stmt('Select * FROM tbl_department where status_id = 1 and parent_id = 0');
        } else {
            $query = $this->db->prepare_Stmt('Select * FROM tbl_department where status_id = 1 and department_id = ?', [&$id]);
        }
        $row = $this->db->assoc($query);
        $tmp_arr = array('id' => $row['department_id'], 'title' => $row['department_name']);
        $tmp_child_arr = self::viewAllChild($row['department_id']);
        if (!empty($tmp_child_arr))
            $tmp_arr['children'] = $tmp_child_arr;
        $root_arr_first = $tmp_arr;
        return $root_arr_first;
    }

    public function viewAllChild($parent_id) {
        $child_arr = array();
        $query = $this->db->prepare_Stmt('Select * FROM tbl_department where status_id = 1 and parent_id = ?', [&$parent_id]);
        while ($row = $this->db->assoc($query)) {
            $tmp_arr = array('id' => $row['department_id'], 'title' => $row['department_name']);
            $tmp_child_arr = self::viewAllChild($row['department_id']);
            if (!empty($tmp_child_arr))
                $tmp_arr['children'] = $tmp_child_arr;
            $child_arr[] = $tmp_arr;
        }
        return $child_arr;
    }

    public function view_department_emp($id = null) {
        $cond = '';
        if (!is_null($id)) {

            $cond .= ' and  parent_id = "' . $id . '"';
        } else {
            $cond .= ' and parent_id = 0';
        }
        $data_type=['normal','Manager','Supervisor'];

        $data = array();
        $query = $this->db->query('select department_name as name,concat("d",department_id) as id,
            department_id as myid,
            parent_id,0 as is_emp 
            FROM tbl_department where 1=1 ' . $cond);


        while ($row = $this->db->assoc($query))
            $data[] = $row;
        if (!is_null($id)) {
            $query = $this->db->query('select concat_ws(" ",`Employee_FirstName`, `Employee_MiddleName`, `Employee_LastName`) as name,
                concat("e",Employee_ID) as id,Employee_ID as myid,Branch_ID as parent_id,1 as is_emp,
                employee_level
                from tbl_hrm_employee where Status_ID = 1 and Branch_ID = "' . $id . '"');
            while ($row = $this->db->assoc($query)) {
                if($row['employee_level'] > 0)
                    $row['name'] = $row['name'].' ('.$data_type[$row['employee_level']].')';
                $data[] = $row;
            }
        }
        return $data;
    }

}
