<?php

/*
 * *************************************************
 * Copyright (C) 2021 Earworks.                    *
 * Codeigniter Project Template Modification       *
 * Please contact our email for more information : *
 * contact@earworks.co.id                          *
 * *************************************************
 */

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

/**
 * Description of Login
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Login extends MY_Controller {

    public function index() {
        $this->_init_api(false);
        $data = [
            'username' => $this->post('username'),
            'password' => $this->post('password'),
            'rememberme' => $this->post('rememberme')
        ];
        $validate = $this->validate_form(['username', 'password'], true);
        if ($validate === true) {
            $model = new User_model();
            $result = $model->login($data, User_model::LOGIN_TYPE_PUBLIC);
            if ($result['status'] === 1) {
                $user['user'] = $result['user'];
                $user['profile'] = $result['user']->profile;
                $user_absen = User_absen_model::get_dbo()->where('user_id',$user['user']->id)->get();
                $user['absen'] = [];
                if ($user_absen->count() >= 1) {
                    foreach ($user_absen as $res) {
                        $user['absen'][] = $res->absen->toArray();
                    }
                }
                return $this->_success('Login Success', $user);
            } else {
                return $this->_error($result['message']);
            }
        } else {
            return $validate; // invalid request [post or get] or invalid validation form
        }
    }

    public function logout() {
        $this->_init_api();
        $user = new User_model();
        $user->logout($this->user['user']['id']);
        return $this->_success('Logout Success');
    }

}
