<!DOCTYPE html>
<html ng-app="ShoppingCartApp">

  <head>
    <link data-require="animate.css@*" data-semver="3.2.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.0.x" src="https://code.angularjs.org/1.3.10/angular.js" data-semver="1.3.10"></script>
    <script data-require="angular.js@1.0.x" src="https://code.angularjs.org/1.3.10/angular-route.min.js" data-semver="1.3.10"></script>
    <script data-require="angular.js@1.0.x" src="https://code.angularjs.org/1.3.10/angular-animate.js" data-semver="1.3.10"></script>
    <script data-require="underscore.js@*" data-semver="1.8.3" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="app.js"></script>
    <script src="controller.js"></script>
    <script src="shoppingFactory.js"></script>
    <script src="aunthentication.js"></script>
  </head>

  <body class="ng-cloak">
    <div ng-controller="HeaderController" ng-include="'header.html'"></div>
    <div class="mainContent" ng-view></div>
  </body>

</html>
var app = angular.module('ShoppingCartApp',[
  'ngRoute',
  'mainControllers'
  ]);


app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.
  when('/login', {
    templateUrl: 'login.html',
    controller: 'LoginController'
  }).
  when('/list', {
    templateUrl: 'list.html',
    controller: 'ListController'
  }).
  when('/shoppingcart', {
    templateUrl: 'shoppingCart.html',
    controller: 'ShoppingCartController'
  }).
  when('/checkout', {
    templateUrl: 'checkout.html',
    controller: 'ShoppingCartController'
  }).
  when('/checkoutsuccess', {
    templateUrl: 'checkoutSuccess.html',
    controller: 'ShoppingCartController'
  }).
  when('/details/:itemId', {
    templateUrl: 'details.html',
    controller: 'DetailsController'
  }).
  otherwise({
    redirectTo: '/login'
  });
}]);

/* Styles go here */

[
  {"username":"reemar", "password":"reemar",
    "shoppingcart": [{
      "item": "Physics Master Level",
      "description": "Level up Physics Mastery",
      "price": 12,
      "supplier":"Physics Central",
      "available": true,
      "itemcount": 2
    },
    {
      "item": "Math Master Level",
      "description": "Level up Math Mastery",
      "price": 12,
      "supplier":"Math Central",
      "available": true,
      "itemcount": 3
    }]
  },
  {"username":"admin", "password":"reemar",
    "shoppingcart": [{
      "item": "Cooking Master Level",
      "description": "Level up Cooking Mastery",
      "price": 14,
      "supplier":"Cooking Central",
      "available": true,
      "itemcount": 2
    },
    {
      "item": "Science Master Level",
      "description": "Level up Math Science",
      "price": 12,
      "supplier":"Science Central",
      "available": true,
      "itemcount": 3
    }]
  }
]
[
   {"name": "Physics Master Level",
    "description": "Level up Physics Mastery",
    "price": 11,
    "supplier":  [{
      "name": "Physics Central",
      "description": "Online Physics Training Platform!",
      "active": true,
      "address": "Mars"
    }],
    "available": true,
    "itemcount": 6
   },
   {"name": "English Master Level",
    "description": "Level up English Mastery",
    "price": 12,
    "supplier":  [{
      "name": "English Central",
      "description": "Online English Training Platform!",
      "active": true,
      "address": "Sydney"
    }],
    "available": true,
    "itemcount": 7
   },
   {"name": "Filipino Master Level",
    "description": "Level up Filipino Mastery",
    "price": 13,
    "supplier":  [{
      "name": "Filipino Central",
      "description": "Online Filipino Training Platform!",
      "active": true,
      "address": "Cebu"
    }],
    "available": true,
    "itemcount": 8
   },
   {"name": "Science Master Level",
    "description": "Level up Science Mastery",
    "price": 14,
    "supplier":  [{
      "name": "Science Central",
      "description": "Online Science Training Platform!",
      "active": true,
      "address": "Indonesia"
    }],
    "available": true,
    "itemcount": 9
   },
   {"name": "Cooking Master Level",
    "description": "Level up Cooking Mastery",
    "price": 15,
    "supplier":  [{
      "name": "Cooking Central",
      "description": "Online Cooking Training Platform!",
      "active": true,
      "address": "China"
    }],
    "available": true,
    "itemcount": 10
   }
]
var mainController = angular.module("mainControllers",[]);

mainController.controller('LoginController',[
  '$scope','$http','$location','$rootScope','Authentication', 
  function($scope,$http,$location,$rootScope,Authentication){
   //var accountService = ShoppingFactory.createAccountsService();
   $scope.init = function(){
     
    /*AccountsService.getAccounts().then(function(data){
      $scope.users = data;
    });*/
    console.log(Authentication);
    $http.get('accounts.json').success(function(data){
      $scope.users = data;
    });
  };
  
  $scope.login = function(){
    Authentication.login($scope.user);
    if($scope.authenticate($scope.user)){
      $location.path('/list');
    }else{
       $scope.message = "Please enter valid credentials";
    }

  };
  
  $scope.authenticate = function(loggingUser){
    $scope.validUser = false;
    $scope.users.forEach(function(user){
      if(user.username == loggingUser.username && user.password == loggingUser.password){
        $scope.validUser = true;
      }
    });
    
    return $scope.validUser;
  }
  
  $scope.$watch('validUser', function(){
     $rootScope.$broadcast('validUser', $scope.validUser);
     console.log($rootScope);
  });
  
  $scope.init();
}]);

mainController.controller('HeaderController',['$scope','$http', function($scope,$http){
   $scope.init = function(){
/*    $scope.users = [];
    
    $http.get('accounts.json').success(function(data){
      $scope.users = data;
      console.log(data);
    });*/
  };
  
  $scope.init();
}]);

mainController.controller('ListController',['$scope','$http', '$rootScope', function($scope,$http, $rootScope){
   $scope.listOrder ="name";
   $scope.init = function(){
    $scope.itemList ={};

    $http.get('items.json').success(function(data){
      $scope.itemList = data;
      console.log(data);
    });
    
  };
  $scope.$watch('itemList', function(){
     $scope.$emit('itemList', $scope.itemList);
  });
  
  $scope.addToCart = function(item,no){
    $rootScope.shoppingCart.push({item,no});
    console.log($rootScope.shoppingCart);
  };
  
  $scope.init();
}]);

mainController.controller('ShoppingCartController',['$scope','$http', '$rootScope','$location','$sce', function($scope,$http,$rootScope,$location,$sce){
    $scope.isCheckoutPage = false;
    $rootScope.shoppingCart = $rootScope.shoppingCart || [];
    $rootScope.shoppingCart.totalPrice = 0;
    $rootScope.$on('validUser', function(event,user){
      $scope.validUser = user;
      console.log(user);
    });
    
    $rootScope.$on('itemList', function(event,itemList){
      $scope.itemList = itemList;
    });
    
    $scope.$watch('shoppingCart',function(){
      $rootScope.shoppingCart.totalPrice = 0;
      $rootScope.shoppingCart.totalItems = 0;
      $scope.getTotalPrice();
      $scope.getTotalNoOfItems();
      console.log('changed');
    },true);
    
    $scope.checkout = function(){
      $location.path('/checkout');
      $scope.isCheckoutPage = true;
    };
    
    $scope.deleteFromCart = function(index){
      $rootScope.shoppingCart.splice(index,1);
    };
    
    $scope.clearShoppingCart = function(index){
      $rootScope.shoppingCart = [];
    };
    
    $scope.backToList = function(){
      $location.path('/list');
      $scope.isCheckoutPage = false;
    };
    
    $scope.getTotalPrice = function(){
      $rootScope.shoppingCart.forEach(function(itemObj){
        $rootScope.shoppingCart.totalPrice += $scope.getItemPrice(itemObj);
      });
    };
    
    $scope.getTotalNoOfItems = function(){
      $rootScope.shoppingCart.forEach(function(itemObj){
        $rootScope.shoppingCart.totalItems += $scope.getItemNo(itemObj);
      });
    };
    
    $scope.getItemPrice = function(itemObj){
      var itemPrice = 0;
      itemPrice = Number(itemObj.item.price) * Number(itemObj.no);
      return itemPrice;
    };
    
    $scope.getItemNo = function(itemObj){
      return itemObj.no;
    };
    
    $scope.confirmCheckout = function(){
      $location.path('/checkoutsuccess');
      $scope.message = $sce.trustAsHtml($rootScope.shoppingCart.length + ' Items' + ' @ $' + $rootScope.shoppingCart.totalPrice);
      console.log($scope.successMsg);
      $rootScope.shoppingCart = [];
    };
}]);
<div ng-controller = "HeaderController">
  <h1>Welcome to Shopping Central</h1>
</div>
<div class="ng-cloak" ng-show="validUser" ng-controller = "ShoppingCartController" ng-include="'shoppingCart.html'"></div>
<section class="well">
  <h1>Please Login</h1>
  <form name="loginForm" class="well" ng-submit= "login()" novalidate>
    <p class="error bg-danger" ng-show="message">{{ message }}</p>
    <div class="form-group">
      <label for="username">Username</label>
      <input type="text" ng-model="user.username" ng-required ="true" class="form-control" id="username" placeholder="Enter your Username">
    </div>
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" ng-model="user.password" ng-required ="true" class="form-control" id="password" placeholder="Enter your Password">
    </div>
    <button type="submit" class="btn btn-default" ng-disabled="loginForm.$invalid">Submit</button>
  </form>
</section>
<section class="well">
 <div class="search">
    <h1>Sale Items</h1>
    <label>search: </label>
    <input ng-model="query" placeholder="Search for Items" autofocus>

    <label class="formgroup">by:
      <select ng-model="listOrder">
        <option value="name">Name</option>
        <option value="price">Price</option>
      </select>
    </label>

    <label class="formgroup">
      <input type="radio" ng-model="direction" name="direction" checked>
      ascending
     </label>
    <label class="formgroup">
      <input type="radio" ng-model="direction" name="direction" value="reverse">
      descending
    </label>
   
  </div>
  
  <table ng-show="itemList.length>0" class="table table-hover">
      <tr>
        <th></th>
        <th></th>
        <th></th>
      </tr>
      <tbody>
      <tr class="row" ng-animate="'slide'" ng-repeat="item in itemList | filter: query | orderBy: listOrder:direction">
        <td>
          <p style="font-weight:bold;">{{item.name}}</p>
          <p>{{item.description}}</p>
        </td>
        <td>
          <p>{{item.supplier[0].name}}</p>
        </td>
        <td>
          <p>${{item.price}}</p>
        </td>
        <td>
          <p>{{item.itemcount}} Items Left</p>
        </td>
        <td>
          <div class="input-group">
            <input type="number" min="1" max="{{item.itemcount}}" class="form-control" ng-model="noOfItem[$index]" placeholder="No of Item">
            <span class="input-group-btn">
              <button class="btn btn-info" type="button" ng-click="addToCart(item,noOfItem[$index])" ng-disabled="noOfItem[$index]==undefined">Add to Cart</button>
            </span>
          </div>
        </td>
      </tr>
    </tbody>
  </table>

  
  
  
</section>

<section class="well" ng-show="itemList">
  <h1>Your Shopping Cart</h1>
  <div>
    <span class="glyphicon glyphicon-shopping-cart"></span>
    <span>{{shoppingCart.totalItems}} Items</span>
    <span class="bold">${{shoppingCart.totalPrice}}</span>
    <button ng-disabled="!shoppingCart.length" ng-show="!isCheckoutPage" ng-click="checkout()" class="btn btn-success"> Checkout</button>
    <button ng-disabled="!shoppingCart.length" ng-click="clearShoppingCart()" class="btn btn-warning">Clear</button>
    <button ng-show="isCheckoutPage" ng-click="backToList()" class="btn btn-success"> Back to Store</button>
  </div>
</section>
<section class="well">
  <h1>Checkout Page</h1>
  <p ng-show="shoppingCart.length==0">No Item/s in your Shopping Cart.</p>
  <table ng-show="shoppingCart.length>0" class="table table-hover">
      <tr>
        <th></th>
        <th></th>
        <th></th>
      </tr>
      <tbody>
      <tr ng-class="" ng-animate="'slide'" ng-repeat="item in shoppingCart track by $index">
        <td>
          <p style="font-weight:bold;">{{item.item.name}}</p>
          <p>{{item.item.description}}</p>
        </td>
        <td>
          <p>{{item.item.supplier[0].name}}</p>
        </td>
        <td>
          <p>${{getItemPrice(item)}}</p>
        </td>
        <td>
          <p>{{getItemNo(item)}} Items</p>
        </td>
        <td>
          <button class="btn btn-warning" ng-click="deleteFromCart($index)">Delete from Cart</button>
        </td>
      </tr>
      <tr>
        <th>Total</th>
        <th></th>
        <th>${{shoppingCart.totalPrice}}</th>
        <th>{{shoppingCart.totalItems}} Items</th>
        <th>
          <button class="btn btn-success" ng-click="confirmCheckout()">Checkout</button>
        </th>
      </tr>
    </tbody>
  </table>
</section>
<section class="well">
  <h1>Congrats you have successfully Check out your Shopping Cart!</h1>
  <p class="error bg-success" ng-show="message">{{ message }}</p>
</section>
app.factory('ShoppingFactory',['AccountsService','ItemsService','$rootscope', function(AccountsService,ItemsService,$rootscope){
  return {
    createCurrentUser: function(){
      this.username='';
      this.password='';
      this.shoppingcart = [];
      $rootscope.currentUser = this;
    },
    createShoppingCart: function(){
      $rootscope.shoppingcart = [];
    }
  };
}]);
app.factory('Authentication', [
  '$rootScope',
  '$routeParams',
  '$location',
  '$http',
  function($rootScope, $routeParams, $location, $http) {
    var getUsers = function() {
      var users = [];
      $http.get('accounts.json').success(function(data){
        users = data;
      });
      return users;
    },
    authenticate = function(loggingUser) {
        var validUser = false,
             users = getUsers();
        return validUser;
      };
      
      
      var authObj = {
        login: function(user) {
          console.log(user);
          console.log(getUsers());
          return authenticate(user);
        },
        register: function(newUser) {
          //factory method for registration
        }
      };

    return authObj;
  }
]);