<?php

class ApiuserController extends Controller {

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login'),
                'users' => array('*'),
            ),
        );
    }

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

  public function actionLogin()
{
    $input = json_decode(file_get_contents('php://input'), true);

    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';

    if (empty($username) || empty($password)) {
        echo json_encode([
            'status' => 'failed',
            'message' => 'Username and password are required'
        ]);
        Yii::app()->end();
    }

    $login = new LoginForm();
    $login->isSSO = false;
    $login->username = $username;
    $login->password = $password;

    if ($login->validate() && $login->login()) {

        $user = User::model()->find([
            'condition' => 'LOWER(username) = :username AND isActive = "Y"',
            'params' => [':username' => strtolower($username)]
        ]);

        echo json_encode([
            'status' => 'success',
            'data' => [
                'id' => $user->id,
                'name' => $user->first_name,
                'username' => $user->username,
                'user_group' => $user->usergroups->group_name
            ]
        ]);

    } else {
        echo json_encode([
            'status' => 'failed',
            'message' => 'Username / password is wrong'
        ]);
    }

    Yii::app()->end();
}


}
