<?php
/*
### Auth API
- Functions
  - login x
  - logout
  template function  {
    $this->sys_debug();
    try {
      if (! $this->isLogin) {
        $this->sys_error("Invalid Token");
        exit;
      }
      $prm = $this->sys_input;

    } catch(Exception $exc) {
      $message = $exc->getMessage();
      $this->sys_error($message);
    }

  }
*/

class Authv3 extends MY_Controller
{
    var $db_onedev;
    public function index()
    {
        echo "AUTH API";
    }
    public function __construct()
    {
        parent::__construct();
        $this->db_onedev = $this->load->database("onedev", true);
    }
    function isLogin()
    {
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
        } else {
            $prm = $this->sys_input;
            $data = array(
                "user" => $this->sys_user
            );
            $this->sys_ok($data);
        }
    }
    function login()
    {
        $prm = $this->sys_input;
        try {
            //existing password enc
            $sm_password = md5($this->one_salt . $prm["password"] . $this->one_salt);
            $query = $this->db_onedev->query(
                "SELECT
                    M_UserID,M_UserUsername, M_UserGroupDashboard, M_UserDefaultT_SampleStationID,
                    M_StaffName, 'N' as is_courier, M_UserM_ApproveLevelID,
                    IFNULL(S_SystemsAutoLogoutTime,0) as time_autologout
                FROM m_user
                JOIN m_usergroup ON M_UserM_UserGroupID = M_UserGroupID
                LEFT JOIN m_staff ON M_UserM_StaffID = M_StaffID
                LEFT JOIN conf_systems ON S_SystemsIsActive = 'Y'
                WHERE M_UserUsername = ? AND M_UserPassword = ?
                    AND M_UserIsActive = 'Y'",
                array($prm["username"], $sm_password)
            );
            //echo $query;
            if (!$query) {
                $message = $this->db_onedev->error();
                $this->sys_error($message);
                exit;
            }
            // echo $this->db_onedev->last_query();
            $rows = $query->result_array();
            if (count($rows) > 0) {
                $user = $rows[0];

                $sql = "SELECT
                        M_UserLocationID,
                        M_UserLocationM_UserID,
                        M_UserLocationFlag,
                        M_UserLocationS_RegionalID,
                        M_UserLocationM_BranchID,
                        IFNULL(S_RegionalName, '') S_RegionalName,
                        IFNULL(S_RegionalID, '') S_RegionalID,
                        IFNULL(M_BranchName, '') M_BranchName,
                        IFNULL(M_BranchID, '0') M_BranchID,
                        IFNULL(M_BranchCode, '') M_BranchCode
                    FROM m_userlocation
                    LEFT JOIN s_regional ON M_UserLocationS_RegionalID = S_RegionalID
                        AND S_RegionalIsActive = 'Y'
                    LEFT JOIN m_branch ON M_UserLocationM_BranchID = M_BranchID
                        AND M_BranchIsActive = 'Y'
                    WHERE M_UserLocationM_UserID = ?
                        AND M_UserLocationIsActive = 'Y'";
                $qry = $this->db_onedev->query($sql, array($user['M_UserID']));
                if (!$qry) {
                    $this->sys_error_db("Error get regional");
                    exit;
                }
                $userLocation = $qry->result_array();

                if (count($userLocation) == 0) {
                    $this->sys_error('User belum disetting');
                    exit;
                }

                $location = $userLocation[0];
                $user['M_UserLocationID'] = $location['M_UserLocationID'];
                $user['M_UserLocationFlag'] = $location['M_UserLocationFlag'];
                $user['S_RegionalName'] = $location['S_RegionalName'];
                $user['S_RegionalID'] = $location['S_RegionalID'];
                $user['M_BranchName'] = $location['M_BranchName'];
                $user['M_BranchCode'] = $location['M_BranchCode'];
                $user['M_BranchID'] = $location['M_BranchID'];

                switch ($location['M_UserLocationFlag']) {
                    case 'P':
                        $user['S_RegionalName'] = '';
                        $user['S_RegionalID'] = 0;
                        $user['M_BranchName'] = '';
                        $user['M_BranchCode'] = '';
                        $user['M_BranchID'] = 0;
                        $user['loginLevel'] = 'pusat';
                        break;
                    case 'R':
                        if ($prm['branch'] != '0') {
                            $sql = "SELECT
                                    M_BranchID as branchID,
                                    M_BranchS_RegionalID as branchRegionalID,
                                    M_BranchCode as branchCode ,
                                    M_BranchName as branchName,
                                    M_BranchCompanyDetailM_BranchCompanyID branchCompanyID
                                FROM m_branch JOIN m_branch_companydetail ON M_BranchCode  = M_BranchCompanyDetailM_BranchCode
                                WHERE M_BranchS_RegionalID =  ?
                                    AND M_BranchCompanyDetailIsActive = 'Y'
                                    AND M_BranchCompanyDetailM_BranchCompanyID = ?
                                    AND M_BranchID = ?
                                    AND M_BranchIsActive = 'Y'";
                            $qry = $this->db_onedev->query($sql, array($prm['regional'], $prm['company'], $prm['branch']));

                            if (!$qry) {
                                $this->sys_error_db("Error get branch");
                                exit;
                            }
                            $result = $qry->result_array();
                            if (count($result) == 0) {
                                $this->sys_error('User regional tidak memiliki akses cabang yang dipilih');
                                exit;
                            }
                            $user['M_BranchName'] = $result[0]['branchName'];
                            $user['M_BranchCode'] = $result[0]['branchCode'];
                            $user['M_BranchID'] = $result[0]['branchID'];
                        }
                        $user['M_UserLocationFlag'] = 'R';
                        $user['loginLevel'] = 'regional';
                        break;
                    case 'B':
                        $user['loginLevel'] = 'branch';
                        if ($location['M_UserLocationM_BranchID'] != $prm['branch']) {
                            $this->sys_error('User tidak memiliki akses cabang yang dipilih');
                            exit;
                        }
                        break;
                    default:
                        $this->sys_error('User belum disetting');
                        exit;
                }

                $filterBranch = "";
                if ($location['M_UserLocationFlag'] == 'B') {
                    $filterBranch = " AND M_BranchID = {$prm['branch']} ";
                }

                $sql = "SELECT
                        M_BranchCompanyID,
                        M_BranchCompanyName,
                        M_BranchCompanyDetailM_BranchCode,
                        M_branchName
                    FROM m_branch_company
                    JOIN m_branch_companydetail ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID
                        AND M_BranchCompanyDetailIsActive = 'Y'
                    JOIN m_branch ON M_BranchCompanyDetailM_BranchCode = M_BranchCode
                        AND M_BranchIsActive = 'Y'
                        AND M_BranchS_RegionalID = ?
                        $filterBranch
                    WHERE M_BranchCompanyID = ?
                        AND M_BranchCompanyDetailIsActive = 'Y'";
                $qry = $this->db_onedev->query($sql, array($prm['regional'], $prm['company']));
                if (!$qry) {
                    $this->sys_error_db("Error get company access");
                    exit;
                }
                $branchCompany = $qry->result_array();
                if (count($branchCompany) == 0) {
                    $this->sys_error_db("Company tidak memiliki akses ke cabang yang dipilih");
                    exit;
                }
                $company = $branchCompany[0];
                $user['M_BranchCompanyID'] = $company['M_BranchCompanyID'];
                $user['M_BranchCompanyName'] = $company['M_BranchCompanyName'];
                $user['ip'] = $_SERVER['REMOTE_ADDR'];
                $user['agent'] = $_SERVER['HTTP_USER_AGENT'];

                //v2
                $user['version'] = 'v2';
                $user['last-login'] = date('Y-m-d H:i:s');
                if (isset($prm['M_SatelliteID'])) {
                    $user['M_SatelliteID'] = $prm['M_SatelliteID'];
                } else {
                    $user['M_SatelliteID'] = 0;
                }
                $token  = JWT::encode($user, $this->SECRET_KEY);
                $data = array(
                    "user" => $user,
                    "token" => $token
                );

                $query = $this->db_onedev->query("UPDATE m_user SET
                        M_UserIsLoggedIn = 'Y',
                        M_UserLastAccess = now(),
                        M_UserActiveToken = '{$token}'
                    WHERE M_UserID = ?",
                    array($user['M_UserID'])
                );
                if (!$query) {
                    $message = $this->db_onedev->error();
                    $this->sys_error($message);
                    exit;
                }

                $query = $this->db_onedev->query("INSERT INTO acc_one_log.log_login(
                        Log_LoginDateTime,
                        Log_LoginIP,
                        Log_LoginType,
                        Log_LoginStatus,
                        Log_LoginLogin
                    ) VALUES (?,?,?,?,?)",
                    array(date('Y-m-d H:i:s'), $_SERVER['REMOTE_ADDR'], 'LOGIN', 'SUCCESS', $prm["username"])
                );
                if (!$query) {
                    $message = $this->db_onedev->error();
                    $this->sys_error($message);
                    exit;
                }

                $this->sys_ok($data);
                exit;
            }

            $query = $this->db_onedev->query("INSERT INTO acc_one_log.log_login(
                    Log_LoginDateTime,
                    Log_LoginIP,
                    Log_LoginType,
                    Log_LoginStatus,
                    Log_LoginLogin
                ) VALUES (?,?,?,?,?)",
                array(date('Y-m-d H:i:s'), $this->input->ip_address(), 'LOGIN', 'FAILED', $prm["username"])
            );
            if (!$query) {
                $message = $this->db_onedev->error();
                $this->sys_error($message);
                exit;
            }
            $this->sys_error_db("Invalid UserName / Password");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function logout()
    {
        $prm = $this->sys_input;
        try {

            $query = $this->db_onedev->query(
                "
        UPDATE m_user
        SET M_UserIsLoggedIn = 'N', M_UserActiveToken = null
        WHERE M_UserID = ?",
                array($this->sys_user['M_UserID'])
            );

            if (!$query) {
                $message = $this->db_onedev->error();
                $this->sys_error($message);
                exit;
            }

            $this->db_onedev->query("INSERT INTO one_log.log_login(Log_LoginDateTime,Log_LoginIP,Log_LoginType,Log_LoginStatus,Log_LoginLogin) VALUES (?,?,?,?,?)
        ", array(date('Y-m-d H:i:s'), $_SERVER['REMOTE_ADDR'], 'LOGOUT', 'SUCCESS', $this->sys_user['M_UserUsername']));
            $this->sys_ok("OK");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function getRegional()
    {
        $prm = $this->sys_input;
        try {
            $sql = "SELECT
              S_RegionalID regionalID,
              S_RegionalName regionalName
              FROM s_regional
              WHERE S_RegionalIsActive = 'Y'";
            $qry = $this->db_onedev->query($sql, array());

            if (!$qry) {
                // $this->db->trans_rollback();
                $this->sys_error_db("Error get regional");
                exit;
            }
            $result = $qry->result_array();
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    function getBranch($regionalID, $companyID)
    {
        $prm = $this->sys_input;
        try {
            $sql = "SELECT
              M_BranchID as branchID,
              M_BranchS_RegionalID as branchRegionalID,
              M_BranchCode as branchCode ,
              M_BranchName as branchName,
              M_BranchCompanyDetailM_BranchCompanyID branchCompanyID
              FROM m_branch
              JOIN m_branch_companydetail
              ON M_BranchCode  = M_BranchCompanyDetailM_BranchCode
              WHERE M_BranchS_RegionalID =  ?
              AND M_BranchCompanyDetailIsActive = 'Y'
              AND M_BranchCompanyDetailM_BranchCompanyID = ?
              AND M_BranchIsActive = 'Y'";
            $qry = $this->db_onedev->query($sql, array($regionalID, $companyID));

            if (!$qry) {
                // $this->db->trans_rollback();
                $this->sys_error_db("Error get branch");
                exit;
            }
            $result = $qry->result_array();
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    function getCompany()
    {
        $prm = $this->sys_input;
        try {
            $sql = "SELECT
              M_BranchCompanyID branchCompanyID,
              M_BranchCompanyName branchCompanyName
              FROM m_branch_company
              WHERE M_BranchCompanyIsActive ='Y'";
            $qry = $this->db_onedev->query($sql, array());

            if (!$qry) {
                // $this->db->trans_rollback();
                $this->sys_error_db("Error get branch");
                exit;
            }
            $result = $qry->result_array();
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
}
