angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $rootScope, $ionicPopup, $ionicLoading, $location, $ionicHistory, $ionicPlatform, $interval, $http, $filter, $ionicModal, $window, $state) {

  $scope.getDateTime = function(){
    $scope.currentdatetime = $filter('date')(new Date(), 'dd/MM/yyyy HH:mm');
  };
  $scope.getDateTime();
  $interval($scope.getDateTime, 5000);

  $rootScope.saveSettings = function(){
    window.localStorage.setItem('settings', JSON.stringify($rootScope.settings));
  };

  $rootScope.hall = {};

  $rootScope.settings = JSON.parse(window.localStorage.getItem('settings'));
  $rootScope.license = window.localStorage.getItem('license');

  $rootScope.waiter = JSON.parse(window.localStorage.getItem('waiter'));



  $rootScope.check = function(){
    $http.post('http://lisans.viapos.com.tr/check.php', {
      license:$scope.license,
      uuid: window.device ? device.uuid : 'test'
    }, {timeout:5000})
    .success(function(response){
      if(!response.successful){
        $rootScope.license = null;
        localStorage.removeItem('license');

        $rootScope.settings = null;
        localStorage.removeItem('settings');
        $scope.popup("Lisans Doğrulama Hatası", "Lisansınızı doğrularken bir sorunla karşılaştık.", "button-assertive");
        $scope.goLogin()
      }
    });
  };




  $scope.addLicense = function(){
    $scope.licenseData = {};

    $ionicPopup.show({
      template: '<input type="text" ng-model="licenseData.name" placeholder="Ad Soyad"><br>' +
                '<input type="text" ng-model="licenseData.key" placeholder="Lisans Anahtarı">',
      title: 'Lisans Anahtarı',
      scope: $scope,
      buttons: [
        {
          text: 'Kaydet',
          type: 'button-royal',
          onTap: function(e) {
            $scope.activate();
          }
        },
        {
          text: 'Vazgeç',
          type: 'button-stable',
          onTap: function(e) {
            return false;
          }
        }
      ]
    });
  };

  $scope.activate = function(){
    $scope.loading();
    $http.post('http://lisans.viapos.com.tr/activate.php', {
      license:$scope.licenseData.key,
      name:$scope.licenseData.name,
      uuid: window.device ? device.uuid : 'test',
      os: window.device ? device.platform : 'test',
      model: window.device ? device.model : 'test'
    }, {timeout:5000})
    .success(function(response){
      if(response.successful){
        $rootScope.license = response.data.license;
        window.localStorage.setItem('license', $rootScope.license);

        $rootScope.settings = response.data.settings;

        $rootScope.settings.servername = "WiFi";
        $rootScope.settings.server = "http://" + $rootScope.settings.local_ip + "/mobil/";

        $rootScope.saveSettings();
      } else {
        $scope.popup(response.error_title, response.error_message, "button-assertive");
      }
    })
    .error(function(e){
      $scope.popup("Bağlantı Hatası", "Lütfen bağlantınızı kontrol ediniz.", "button-assertive");
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };




    $scope.removeLicense = function(){
      $ionicPopup.show({
        template: 'Lisans anahtarını silmek istediğinize emin misiniz?',
        title: 'Lisans Sil',
        buttons: [
          {
            text: 'Sil',
            type: 'button-assertive',
            onTap: function(e) {
              $scope.deactivate();
            }
          },
          {
            text: 'Vazgeç',
            type: 'button-stable',
            onTap: function(e) {
              return false;
            }
          }
        ]
      });
    };

    $scope.deactivate = function(){
      $scope.loading();
      $http.post('http://lisans.viapos.com.tr/deactivate.php', {
        license:$scope.license,
        uuid: window.device ? window.device.uuid : 'test'
      }, {timeout:5000})
      .success(function(response){
        if(response.successful){
          $rootScope.license = null;
          localStorage.removeItem('license');

          $rootScope.settings = null;
          localStorage.removeItem('settings');
        } else {
          $scope.popup(response.error_title, response.error_message, "button-assertive");
        }
      })
      .error(function(e){
        $scope.popup("Bağlantı Hatası", "Lütfen bağlantınızı kontrol ediniz.", "button-assertive");
      })
      .finally(function(){
        $scope.loading('hide');
      });
    };


  $scope.logout = function(promp){
    promp = promp || false;
    if(promp){
      $ionicPopup.show({
        template: "Kilitlemeyi onaylıyor musunuz?",
        title: "Kilitle",
        buttons: [
          {
            text: 'Kilitle',
            type: 'button-balanced',
            onTap: function(e) {
              window.localStorage.removeItem('waiter');
              $rootScope.stopRefresh();
              $location.path('/login');
            }
          },
          {
            text: 'Vazgeç',
            type: 'button-energized',
            onTap: function(e) {
              return false;
            }
          }
        ]
      });
    } else {
      window.localStorage.removeItem('waiter');
      $location.path('/login');
    }
  };

  $scope.popup = function(title, message, button){
    $ionicPopup.show({
       template: message,
       title: title,
       buttons: [
          { text: 'Tamam', type: button }
       ]
    });
  };

  $scope.loading = function(act){
    if(act == 'hide')
      $ionicLoading.hide();
    else
      $ionicLoading.show({
        template: '<ion-spinner icon="android"></ion-spinner><br>Yükleniyor...'
      });
  };

  $scope.goBack = function(){
    $ionicHistory.goBack();
  };

  $scope.goHome = function(){
    $location.path('/masalar');
  };

  $scope.goLogin = function(){
    $location.path('/login');
  };

  $rootScope.refresh = function(loader, firstload){
    loader = loader || false;
	firstload = firstload || false;
    if($rootScope.settings){
      if(loader)
        $scope.loading();
      $http.post($rootScope.settings.server + 'tables.php', {api_key:$rootScope.settings.api_key}, {timeout:5000})
      .success(function(response){
        if(response.successful){
          $scope.salonlar = response.halls;
          $scope.masalar = response.tables;
          if(loader)
            $rootScope.hall.name = $scope.salonlar[0];
        } else {
          $scope.logout();
        }
      })
      .error(function(e){
        if($state.current.name != 'login' && loader)
          $scope.connectionError();
      })
      .finally(function(){
        if(loader)
          $scope.loading('hide');
      });
    }
  };

  var refreshTimer = null;

  $rootScope.startRefresh = function(){
    if($rootScope.waiter)
      refreshTimer = $interval(function(){
          $rootScope.refresh();
      }.bind(this), 2000);
  };

  $rootScope.stopRefresh = function(){
    $interval.cancel(refreshTimer);
  };

  $rootScope.startRefresh();



  $scope.refreshPage = function(){
    $window.location.reload(true);
  };


  $scope.changeServer = function(){
    if($rootScope.settings.connection4G){
      $rootScope.settings.servername = "4G";
      $rootScope.settings.server = "http://" + $rootScope.settings.remote_ip + "/mobil/";
      $rootScope.saveSettings();
    } else {
      $rootScope.settings.servername = "WiFi";
      $rootScope.settings.server = "http://" + $rootScope.settings.local_ip + "/mobil/";
      $rootScope.saveSettings();
    }
  };




  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/baglanti-hatasi.html', {
    scope: $scope,
    rootScope: $rootScope
  }).then(function(modal) {
    $scope.connectionErrorModal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeConnectionErrorModal = function() {
    $scope.connectionErrorModal.hide();
    $scope.logout();
  };
  $scope.connectionError = function(){
    $scope.connectionErrorModal.show();
  };
  $scope.connectionCheck = function(){
    $scope.loading();
    $http.post($rootScope.settings.server + 'tables.php', {api_key:$rootScope.settings.api_key}, {timeout:5000})
    .success(function(response){
      $scope.refreshPage();
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };
})
.controller('LoginCtrl', function($scope, $rootScope, $stateParams, $http, $location) {

  $scope.loginData = {"garsonKodu":""};

  $scope.numpad = function(number){
    if($scope.loginData.garsonKodu.length < 6)
      $scope.loginData.garsonKodu += number;
  };

  $scope.backspace = function(){
    $scope.loginData.garsonKodu = $scope.loginData.garsonKodu.slice(0, -1);
  };

  $scope.clear = function(){
    $scope.loginData.garsonKodu = "";
  };

  $scope.login = function(){
    $scope.loading();
    $http.post($rootScope.settings.server + 'login.php', {
      api_key:$rootScope.settings.api_key,
      garsonKodu:$scope.loginData.garsonKodu
    }, {timeout:5000})
    .success(function(response){
      if(response.successful){
        window.localStorage.setItem('waiter', JSON.stringify(response.waiter));
        $rootScope.waiter = JSON.parse(window.localStorage.getItem('waiter'));
        $rootScope.refresh(true);
        $rootScope.startRefresh();
        $location.path('/masalar');
        $scope.clear();
      } else {
        $scope.popup("Hatalı Garson", "Lütfen garson kodunuzu kontrol ediniz.", "button-assertive");
        $scope.clear();
      }
    })
    .error(function(e){
      $scope.popup("Bağlantı hatası", "Lüften bağlantı türünüzü değiştirip tekrar giriş yapın.", "button-assertive");
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };

})

.controller('MasalarCtrl', function($scope, $rootScope, $stateParams, $http, $location, $timeout, $ionicPopup, $ionicModal) {

    $scope.refresh(true, true);

    $scope.doubleclick = false;
    $scope.transfer_table = null;

    // Create the login modal that we will use later
    $ionicModal.fromTemplateUrl('templates/salon-degis.html', {
      scope: $scope,
      rootScope: $rootScope
    }).then(function(modal) {
      $scope.hallModal = modal;
    });

    // Triggered in the login modal to close it
    $scope.closeHallModal = function() {
      $scope.hallModal.hide();
    };

    // Open the login modal
    $scope.changeHall = function() {
      $scope.hallModal.show();
    };



    // Create the login modal that we will use later
    $ionicModal.fromTemplateUrl('templates/mars.html', {
      scope: $scope,
      rootScope: $rootScope
    }).then(function(modal) {
      $scope.marsModal = modal;
    });

    // Triggered in the login modal to close it
    $scope.closeMarsModal = function() {
      $scope.marsModal.hide();
    };

    // Open the login modal
    $scope.mars = function() {
      $scope.marsModal.show();
      $scope.getMars();
    };

    $scope.getMars = function(){

      $scope.marsData = {};
      $scope.marslar = [];
      $scope.loading();
      $http.post($rootScope.settings.server + 'marslar.php', {
        api_key:$rootScope.settings.api_key,
        hall:$scope.selected.hall,
        table:$scope.selected.name,
      }, {timeout:5000})
      .success(function(response){
        if(response.successful)
          $scope.marslar = response.items;
        else {
          $scope.popup(response.error_title, response.error_message, "button-assertive");
          $scope.closeMarsModal();
        }
      })
      .error(function(e){
        $scope.connectionError();
      })
      .finally(function(){
        $scope.loading('hide');
      });
    };

    $scope.marsla = function(){
      items = Object.keys($scope.marsData.items).filter(function(k){return $scope.marsData.items[k]}).map(Number).join();

      $scope.loading();
      $http.post($rootScope.settings.server + 'mars.php', {
        api_key:$rootScope.settings.api_key,
        hall:$scope.selected.hall,
        table:$scope.selected.name,
        items:items,
      }, {timeout:5000})
      .success(function(response){
        if(response.successful)
          $scope.closeMarsModal();
        else {
          $scope.popup(response.error_title, response.error_message, "button-assertive");
        }
      })
      .error(function(e){
        $scope.connectionError();
      })
      .finally(function(){
        $scope.loading('hide');
      });
    };


    $scope.click = function(masa){
      $scope.temp = $scope.selected;
      $scope.selected = JSON.parse(masa);

      if($scope.transfer_table){
        $ionicPopup.show({
          template: ($scope.selected.waiter=='' ? "<b>"+$scope.transfer_table.table+"</b> numaralı masadan -> <b>"+$scope.selected.name+"</b> numaralı masaya transfer işlemini onaylıyor musunuz?" : "<b>"+$scope.transfer_table.table+"</b> numaralı masayı -> <b>"+$scope.selected.name+"</b> numaralı masa ile birleştirme işlemini onaylıyor musunuz?"),
          title: ($scope.selected.waiter=='' ? "Masa Transfer" : "Masa Birleştirme"),
          buttons: [
            {
              text: ($scope.selected.waiter=='' ? 'Transfer Et':'Birleştir'),
              type: 'button-balanced',
              onTap: function(e) {
                $scope.complete_transfer($scope.transfer_table, $scope.selected);
              }
            },
            {
              text: 'Vazgeç',
              type: 'button-energized',
              onTap: function(e) {
                $scope.selected = false;
                $scope.transfer_table = null;
                return false;
              }
            }
          ]
        });
        return false;
      }

      if($scope.doubleclick && $scope.temp.name == $scope.selected.name){
        $scope.order($scope.selected);
      }

      $scope.doubleclick = true;
      $timeout(function(){ $scope.doubleclick = false; }, 250);

      if($scope.selected.waiter == ''){
        $ionicPopup.show({
          template: "<b>"+$scope.selected.name+"</b> numaralı yeni masa açılacak onaylıyor musunuz?",
          title: "Yeni Masa",
          buttons: [
            {
              text: 'Yeni Masa Aç',
              type: 'button-balanced',
              onTap: function(e) {
                $scope.order($scope.selected);
                $scope.selected = false;
              }
            },
            {
              text: 'Vazgeç',
              type: 'button-energized',
              onTap: function(e) {
                $scope.selected = false;
                return false;
              }
            }
          ]
        });
      }
    };

    $scope.transfer = function(){
      if($scope.transfer_table)
        $scope.transfer_table = null;
      else
        $scope.transfer_table = {
          hall:$scope.selected.hall,
          table:$scope.selected.name
        };
    };

    $scope.complete_transfer = function(transfer, to){
      $scope.loading();
      $http.post($rootScope.settings.server + 'transfer-table.php', {
        api_key:$rootScope.settings.api_key,
        hall:transfer.hall,
        table:transfer.table,
        hall_to:to.hall,
        table_to:to.name
      }, {timeout:5000})
      .success(function(response){
        if(!response.successful){
          $scope.popup(response.error_title, response.error_message, "button-assertive");
        }
      })
      .error(function(e){
        $scope.connectionError();
      })
      .finally(function(){
        $scope.transfer_table = null;
        $scope.refresh();
        $scope.loading('hide');
      });
    };

    $scope.order = function(masa){
      $location.path('/siparis/'+masa.hall+'/'+masa.name);
    };

    $scope.detail = function(){
      $location.path('/masa-detay/'+$scope.selected.hall+'/'+$scope.selected.name);
    };

    $scope.printAddition = function(){
      $scope.loading();
      $http.post($rootScope.settings.server + 'print-addition.php', {
        api_key:$rootScope.settings.api_key,
        hall:$scope.selected.hall,
        table:$scope.selected.name
      }, {timeout:5000})
      .success(function(response){
        if(response.successful){
          $scope.selected.status = 3;
        } else {
          $scope.popup(response.error_title, response.error_message, "button-assertive");
        }
      })
      .error(function(e){
        $scope.connectionError();
      })
      .finally(function(){
        $scope.refresh();
        $scope.loading('hide');
      });
    };

    $scope.showCustomerToggle = function(){
      $ionicPopup.show({
        template: '<select ng-options="o as o for o in customers"><option>asd</option></select>',
        title: "Yeni Masa",
        buttons: [
          {
            text: 'Yeni Masa Aç',
            type: 'button-balanced',
            onTap: function(e) {
              $scope.order($scope.selected);
            }
          },
          {
            text: 'Vazgeç',
            type: 'button-energized',
            onTap: function(e) {
              $scope.selected = false;
              return false;
            }
          }
        ]
      });
    };

    $scope.changeCustomer = function(){
      $location.path('/cari-sec/'+$scope.selected.hall+'/'+$scope.selected.name);
    };
})

.controller('SiparisCtrl', function($scope, $rootScope, $stateParams, $http, $ionicPopup, $filter, $interval, $ionicModal) {

  $scope.cartData = {quantity:1};
  $rootScope.hall.name = $stateParams.hall;
  $scope.table = $stateParams.table;

  $scope.loaded = 0;

  $scope.getProducts = function(loader){
	loader = loader || false;
    if(loader)
      $scope.loading();

    $http.post($rootScope.settings.server + 'products.php', {
      api_key:$rootScope.settings.api_key,
      hall:$stateParams.hall
    }, {timeout:5000})
    .success(function(response){
      $scope.categories = response.categories;
      $scope.selectedCategory = $scope.categories[0];
      $scope.getCart(true);
    })
    .error(function(e){
      $scope.connectionError();
    })
    .finally(function(){
      if(++$scope.loaded >= 2)
        $scope.loading('hide');
    });
  };



  $scope.getCart = function(loader){
	loader = loader || false;
    if(loader)
      $scope.loading();

    $http.post($rootScope.settings.server + 'cart.php', {
      api_key:$rootScope.settings.api_key,
      hall:$stateParams.hall,
      table:$stateParams.table
    }, {timeout:5000})
    .success(function(response){
      $scope.cart = response.items;
    })
    .error(function(e){
      if(loader){
        $scope.connectionError();
      }
    })
    .finally(function(){
      if(++$scope.loaded >= 2)
        $scope.loading('hide');
    });
  };

  $scope.getProducts(true);
  refreshCart = $interval(function(){
      $scope.getCart();
  }.bind(this), 1000);

  $scope.$on('$destroy',function(){
    $interval.cancel(refreshCart);
  });

  $scope.selectCategory = function(category){
    $scope.selectedCategory = $filter('filter')($scope.categories, {name:category}, true)[0];
  };





  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/add-to-cart.html', {
    scope: $scope,
    rootScope: $rootScope
  }).then(function(modal) {
    $scope.addModal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeAddModal = function() {
    $scope.addModal.hide();
  };

  // Open the login modal
  $scope.add = function(product) {
    $scope.addToCartData = {
      portion: 'tek',
      quantity: 1,
    };
    $scope.extras = [];

    $scope.product = JSON.parse(product);

    $scope.loading();
    $http.post($rootScope.settings.server + 'extras.php', {
      api_key:$rootScope.settings.api_key,
      product:$scope.product.code,
      group:$scope.product.group
    }, {timeout:5000})
    .success(function(response){
      if(response.successful){
        $scope.extras = response.extras;
        console.log(response);
      } else {
        $scope.popup(response.error_title, response.error_message, "button-assertive");
        $scope.goBack();
      }
    })
    .error(function(e){
      $scope.connectionError();
    })
    .finally(function(){
      $scope.loading('hide');
    });

    $scope.addModal.show();

  };

  $scope.numpad = function(number){
    if(Number.isInteger($scope.addToCartData.quantity)){
      if(number == '.')
        $scope.addToCartData.quantity = '0.';
      else
        $scope.addToCartData.quantity = number;
    } else if($scope.addToCartData.quantity.length < 5)
      $scope.addToCartData.quantity += number;
  };

  $scope.backspace = function(){
    if($scope.addToCartData.quantity.length > 1)
      $scope.addToCartData.quantity = $scope.addToCartData.quantity.slice(0, -1);
    else
      $scope.addToCartData.quantity = 1;
  };
  /*
  $scope.add = function(code,name){
    $ionicPopup.show({
      template: '<input type="tel" ng-model="cartData.quantity">',
      title: name,
      buttons: [
        {
          text: 'Ekle',
          type: 'button-balanced',
          onTap: function(e) {
            $scope.addToCart(code);
          }
        },
        {
          text: 'Vazgeç',
          type: 'button-energized',
          onTap: function(e) {
            return false;
          }
        }
      ]
    });
  };
  */

  $scope.addToCart = function(){
    $scope.addToCartData.extra = [];
    $scope.addToCartData.extraPrice = 0;

    if($scope.addToCartData.reserve)
      $scope.addToCartData.extra.push("REZERVE");

    for(i in $scope.addToCartData.extras) {
       if($scope.addToCartData.extras[i] == true) {
           $scope.addToCartData.extra.push($scope.extras[i].name);
           $scope.addToCartData.extraPrice += parseFloat($scope.extras[i].price);
       }
    }

    if($scope.addToCartData.note)
      $scope.addToCartData.extra.push("NOT: " + $scope.addToCartData.note);

    $scope.loading();
    $http.post($rootScope.settings.server + 'add-to-cart.php', {
      api_key:$rootScope.settings.api_key,
      hall:$stateParams.hall,
      table:$stateParams.table,
      waiter:$rootScope.waiter.code,

      product:$scope.product.code,
      quantity:$scope.addToCartData.quantity,
      portion:$scope.addToCartData.portion,
      extra_text:$scope.addToCartData.extra.join(" / "),
      extra_price:$scope.addToCartData.extraPrice,

      reserve:($scope.addToCartData.reserve ? 1 : 0)
    }, {timeout:5000})
    .success(function(response){
      if(response.successful)
        $scope.closeAddModal();
    })
    .error(function(e){
      $scope.connectionError();
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };

  $scope.remove = function(id,name){
    $ionicPopup.show({
      template: 'Ürünü silmek istediğinize emin misiniz?',
      title: name,
      buttons: [
        {
          text: 'Sil',
          type: 'button-assertive',
          onTap: function(e) {
            $scope.removeFromCart(id);
          }
        },
        {
          text: 'Vazgeç',
          type: 'button-energized',
          onTap: function(e) {
            return false;
          }
        }
      ]
    });
  };

  $scope.removeFromCart = function(id){
    $scope.loading();
    $http.post($rootScope.settings.server + 'remove-from-cart.php', {
      api_key:$rootScope.settings.api_key,
      hall:$stateParams.hall,
      table:$stateParams.table,
      waiter:$rootScope.waiter.code,
      id:id
    }, {timeout:5000})
    .success(function(response){
      if(response.successful)
        $scope.getCart();
    })
    .error(function(e){
      $scope.connectionError();
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };

  $scope.giveOrder = function(print){
    $scope.loading();
    $http.post($rootScope.settings.server + 'give-order.php', {
      api_key:$rootScope.settings.api_key,
      hall:$stateParams.hall,
      table:$stateParams.table,
      print:(print ? 1 : 0)
    }, {timeout:5000})
    .success(function(response){
      $scope.goHome();
    })
    .error(function(e){
      $scope.connectionError();
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };

})

.controller('MasaDetayCtrl', function($scope, $rootScope, $stateParams, $http, $location, $ionicModal) {
  $scope.loading();
  $http.post($rootScope.settings.server + 'table-detail.php',{
    api_key:$rootScope.settings.api_key,
    hall:$stateParams.hall,
    table:$stateParams.table
  }, {timeout:5000})
  .success(function(response){
    if(response.successful){
      $scope.masa = response.table;
      $scope.urunler = response.items;
    } else {
      $scope.logout();
    }
  })
  .error(function(e){
    $scope.connectionError();
  })
  .finally(function(){
    $scope.loading('hide');
  });


  $scope.order = function(){
    $location.path('/siparis/'+$stateParams.hall+'/'+$stateParams.table);
  };


  $scope.printAddition = function(){
    $scope.loading();
    $http.post($rootScope.settings.server + 'print-addition.php', {
      api_key:$rootScope.settings.api_key,
      hall:$stateParams.hall,
      table:$stateParams.table
    }, {timeout:5000})
    .success(function(response){
      if(response.successful){
        $scope.adisyon = true;
        $scope.popup("Adisyon Yazdırıldı!", "Adisyon yazdırma işlemi başarıyla gerçekleştirildi.", "button-balanced");
      } else {
        $scope.popup(response.error_title, response.error_message, "button-assertive");
      }
    })
    .error(function(e){
      $scope.connectionError();
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };




  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/cari-sec.html', {
    scope: $scope,
    rootScope: $rootScope
  }).then(function(modal) {
    $scope.marsModal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeCariModal = function() {
    $scope.masa.tempcustomer = $scope.masa.customer;
    $scope.marsModal.hide();
  };

  // Open the login modal
  $scope.cari = function() {
    $scope.masa.tempcustomer = $scope.masa.customer;
    $scope.marsModal.show();
    $scope.getCustomers();
  };

  $scope.getCustomers = function(){
    $scope.marslar = [];
    $scope.loading();
    $http.post($rootScope.settings.server + 'customers.php', {api_key:$rootScope.settings.api_key}, {timeout:5000})
    .success(function(response){
      if(response.successful)
        $scope.customers = response.customers;
      else {
        $scope.popup(response.error_title, response.error_message, "button-assertive");
        $scope.closeCariModal();
      }
    })
    .error(function(e){
      $scope.connectionError();
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };

  $scope.setCustomer = function(cancel){
	cancel = cancel || false;
    if(cancel)
      $scope.masa.customer = '';
    else
      $scope.masa.customer = $scope.masa.tempcustomer;

    $scope.loading();
    $http.post($rootScope.settings.server + 'set-customer.php', {
      api_key:$rootScope.settings.api_key,
      hall:$scope.masa.hall,
      table:$scope.masa.name,
      customer:$scope.masa.customer,
    }, {timeout:5000})
    .success(function(response){
      if(response.successful)
        $scope.closeCariModal();
      else {
        $scope.popup(response.error_title, response.error_message, "button-assertive");
      }
    })
    .error(function(e){
      $scope.connectionError();
    })
    .finally(function(){
      $scope.loading('hide');
    });
  };


})


// .controller('MasaDetayCtrl', function($scope, $rootScope, $stateParams, $http, $location) {
//
// })
;
