angular.module('voxality').controller('AdminUserController', [

'$scope',
'$http',
'$window',
function(
  $scope,
  $http,
  $window) {
    $scope.displayUser = function(user) {
      return user.detail.first_name + ' ' + user.detail.last_name + '(' + user.email + ')'
    };

    $scope.searchUsers = function(text) {
      var protocol = $window.location.protocol;
      var host = $window.location.host;
      var token = $window.Voxality.API.getToken();
      var url = protocol + '//' + host + '/api/admin/users/search';
      var params = { api_token: token, query: text };

      var onSuccess = function(response) {
        $scope.resultUsers = response.data.data;
      };
      var onFailure = function(response) {
        alert(response.data.type + '\n' + response.data.exception);
      };

      $http.get(url, { params: params }).then(onSuccess, onFailure);
    };

    $scope.addFunds = function(amount) {
      $scope.fundsLoading = true;
      var protocol = $window.location.protocol;
      var host = $window.location.host;
      var token = $window.Voxality.API.getToken();
      var url = protocol + '//' + host + '/api/admin/users/' + $scope.selectedUser.id + '/balance/deposit';
      var params = { api_token: token, amount: amount };

      var onSuccess = function(response) {
        $scope.fundsAmount = null;
        $scope.topupForm.$setPristine();
        $scope.topupForm.$setUntouched();
        $scope.fundsLoading = false;
      };
      var onFailure = function(response) {
        alert(response.data.type + '\n' + response.data.exception);
      };

      $http.post(url, params).then(onSuccess, onFailure);
    };
  }

]);