﻿(function () {
    // "use strict";
    angular
        .module("lochnessApp")
        .controller("proctorpurchaseController",
            ctrl1);

    function ctrl1($scope, $location, growl, $filter, $http, $routeParams, userservice, cart) {
        var config = {};
        var ids;
        var products;
        var name;
        var quantity;
        var price;
        var weight;
        var dimensions;
        var cupMultiples = 1; // Leave as 1 for proctor purchases

        function getcustomerinfo(contactid) {
            //console.log(contactid);
            $http.get('/agent/customer/' + contactid)
                .then(function (response) {
                    var customer = response.data;
                    //console.log(customer);
                    $scope.userid = customer[0];
                    $scope.username = customer[1];
                    $scope.contactid = customer[2];
                    $scope.accountid = customer[3];
                    $scope.businessname = customer[4];
                    $scope.contactspermissions = customer[8];
                    $scope.isagent = customer[9];
                    $scope.hidecreditcard = customer[12];
                    $scope.hideponum = customer[13];
                    $scope.canorder = ($scope.contactspermissions.indexOf("2") === -1) ? false : true;
                    page_load();
                });
        }

        function page_load() {
            init();
            $http.get('/accounts/' + $scope.accountid + '/onhold')
                .then(function (response) {
                    $scope.onhold = response.data;
                });
            $http.get('/accounts/' + $scope.accountid + '/catalog')
                .then(function (response) {
                    $scope.catalogRowCollection = response.data;

                    // filter for certain products only (saliva cups for now)
                    $scope.catalogRowCollection = $scope.catalogRowCollection.filter(row => row.od.newProductName.includes("2FC1"));

                    //console.log($scope.catalogRowCollection);
                    var catalog_product_ids = [];

                    for (var i = 0; i < $scope.catalogRowCollection.length; ++i) {
                        // console.log($scope.catalogRowCollection[i].st.newProductStock);//newProductStock dne
                        if ($scope.catalogRowCollection[i].stocknum == 0) {
                            $scope.catalogRowCollection[i].productstockwarning = "This product is backordered and will ship as soon as possible.";
                        }
                    }

                    for (var i = 0; i < $scope.catalogRowCollection.length; ++i) {

                        // set default images if missing based on product category
                        if ($scope.catalogRowCollection[i].ImageFile == "") {
                            if ($scope.catalogRowCollection[i].od.p.ProductType_ID === 176) {
                                $scope.catalogRowCollection[i].ImageFile = "/img/70x70/DX.X-2FC1/DX.X-2FC1.png";
                            }
                            else if ($scope.catalogRowCollection[i].od.p.ProductType_ID === 170) {
                                $scope.catalogRowCollection[i].ImageFile = "/img/70x70/D2.1-1V/1STEP-TYPE2_a.png"
                            }
                            else if ($scope.catalogRowCollection[i].od.p.ProductType_ID === 169) {
                                $scope.catalogRowCollection[i].ImageFile = "/img/70x70/D2.1-1P29/MULTI_DRUG_PNL_10a_70.png";
                            }
                            else if ($scope.catalogRowCollection[i].od.p.ProductType_ID === 143) {
                                $scope.catalogRowCollection[i].ImageFile = "/img/70x70/FYL-1S48-100/FYL-1S48-100_A_70.png";
                            }
                            else {
                                $scope.catalogRowCollection[i].ImageFile = "/img/270x270/rapid-response_270x270.png";
                            }
                        } else {
                            $scope.catalogRowCollection[i].ImageFile = "/img/70x70/" + $scope.catalogRowCollection[i].od.p.ProductCode + "/" + $scope.catalogRowCollection[i].ImageFile;
                        }
                    }

                    //console.log(catalog_product_ids);
                    if ($scope.isagent !== '0') {
                        for (i = 0; i < $scope.catalogRowCollection.length; ++i) {
                            catalog_product_ids.push($scope.catalogRowCollection[i].od.p.Product_ID);
                        }
                        $http.post('/products/stock', catalog_product_ids)
                            .then(function (response) {
                                $scope.catalog_stock = response.data;
                                //console.log($scope.catalog_stock);
                            });
                    }
                    $http.get('/customer/' + $scope.accountid + '/getproductspecials')
                        .then(function (response) {
                            $scope.customerpromotions = '';
                            $scope.productspecials = response.data;
                            if ($scope.productspecials.length > 0 && $scope.productspecials[0].ProductSpecialType_ID === 1) {
                                $scope.orderspecialdescription = $scope.productspecials[0].Description;
                            } else if ($scope.productspecials.length > 0) {
                                for (var i = 0; i < $scope.productspecials.length; ++i) {
                                    for (var j = 0; j < $scope.catalogRowCollection.length; ++j) {
                                        if ($scope.productspecials[i].s.Product_ID === $scope.catalogRowCollection[j].od.p.Product_ID) {
                                            $scope.catalogRowCollection[j].specialdescription = $scope.productspecials[i].s.Description;
                                            $scope.customerpromotions += $scope.productspecials[i].s.Description + '<br/>';
                                        }
                                    }
                                }
                            }
                        });

                    ids = cart.id;
                    products = cart.product;
                    name = cart.name;
                    quantity = cart.quantity;
                    price = cart.price;
                    weight = cart.weight;
                    dimensions = cart.dimensions;

                    $scope.products = products;
                    $scope.quantity = quantity;
                });
        }

        var p = userservice.promisedata().then(function (data) {
            $scope.userid = data[0];
            $scope.username = data[1];
            $scope.accountid = data[3];
            $scope.businessname = data[4];
            $scope.contactspermissions = data[8];
            $scope.isagent = data[9];
            $scope.canorder = ($scope.contactspermissions.indexOf("2") === -1) ? false : true;
            $scope.count = 0;
            $scope.ponum = cart.ponum;
            $scope.hidecreditcard = data[12];
            $scope.hideponum = data[13];
            console.log($scope.hideponum);

            if (!$scope.contactspermissions.includes("7")) {
                $location.path('/home');
                return;
            }

            if ($routeParams.ContactID) {
                var customer = getcustomerinfo($routeParams.ContactID);
            } else {
                page_load();
            }
        });

        function init() {
            var ids = cart.id;
            var products = cart.product;
            var names = cart.name;
            var quantity = cart.quantity;
            var price = cart.price;
            var total = 0;
            $scope.len = products.length;

            $http.post('/products/stock', ids)
                .then(function (response) {
                    $scope.cart_stock = response.data;
                    $scope.cartRowCollection = [];
                    for (var i = 0; i < products.length; i++) {
                        if ($scope.cart_stock[i] < quantity[i] || quantity[i] == 0) {
                            cart.productstockwarning = "Backordered";
                        }
                        else {
                            cart.productstockwarning = "";
                        }
                        var t = { id: ids[i], code: products[i], name: names[i], amount: quantity[i], price: price[i], stockwarning: cart.productstockwarning };
                        $scope.cartRowCollection.push(t);
                        total += price[i] * quantity[i];
                        $scope.total = total;
                    }

                });
        }
        $scope.addToCart = function (id1, p, n, pr, pi, w, d, pt) {
            var q = document.getElementById("qnt" + id1).value;
            document.getElementById("qnt" + id1).value = 0;
            var i = 0;

            if (isNaN(parseInt(q)) || q <= 0) {
                growl.warning("Please enter a valid number", config);
                return;
            }
            else {
                if (pt === 170 || pt === 176) { // product type is cups - must be ordered in multiples of cupMultiples
                    if (q % cupMultiples !== 0) {
                        q = Math.ceil(q / cupMultiples) * cupMultiples;
                    }
                }

                if (products.length === 0) {
                    ids.push(id1);
                    products.push(p);
                    name.push(n);
                    quantity.push(parseInt(q));
                    price.push(pr);
                    weight.push(w);
                    dimensions.push(d);

                }
                else {
                    for (i = 0; i < products.length; i++) {
                        if (products[i] === p) {
                            quantity[i] = parseInt(quantity[i]) + parseInt(q);
                            break;
                        }
                        else if (i + 1 === products.length) {
                            ids.push(id1);
                            products.push(p);
                            name.push(n);
                            quantity.push(parseInt(q));
                            price.push(pr);
                            weight.push(w);
                            dimensions.push(d);
                            break;
                        }
                    }
                }
                init();
                return;
            }
        };
        $scope.addAllToCart = function () {
            for (var i = 0; i < $scope.catalogRowCollection.length; i++) {
                var catRow = $scope.catalogRowCollection[i];
                $scope.addToCart(catRow.od.p.Product_ID, catRow.od.p.ProductCode, catRow.od.p.ProductName, catRow.od.Price, catRow.od.p.PublicInventory,
                    catRow.od.p.Weight, [catRow.od.p.Length, catRow.od.p.Width, catRow.od.p.Height], catRow.od.p.ProductType_ID);
            }
        };
        $scope.changequantity = function (amount, product) {
            var config = {};
            if (amount === null || amount < 0 || isNaN(amount)) {
                growl.warning('Please enter a valid number', config);
                return;
            }
            for (var i = 0; i < cart.product.length; i++) {
                if (cart.product[i] === product && amount === 0) {
                    $scope.remove(i, false);
                    return;
                }
                if (cart.product[i] === product) {
                    var product_type = $scope.catalogRowCollection.concat($scope.recommendedRowCollection).find(({ od }) => od.p.ProductCode === product).od.p.ProductType_ID;

                    if (product_type === 170 || product_type === 176) {
                        if (amount % cupMultiples !== 0) {
                            amount = Math.ceil(amount / cupMultiples) * cupMultiples;
                        }
                    }
                    cart.quantity[i] = parseInt(amount);
                }
                init();
                growl.success('Quantity changed', config);
            }
        };
        $scope.remove = function (i, b) {
            if (b) {
                cart.id.splice(0);
                cart.product.splice(0);
                cart.name.splice(0);
                cart.price.splice(0);
                cart.quantity.splice(0);
                cart.weight.splice(0);
                cart.dimensions.splice(0);
                init();
                growl.success('Cart cleared');
            }
            else {
                cart.id.splice(i, 1);
                cart.product.splice(i, 1);
                cart.name.splice(i, 1);
                cart.price.splice(i, 1);
                cart.quantity.splice(i, 1);
                cart.weight.splice(i, 1);
                cart.dimensions.splice(i, 1);
                init();
                growl.success('Item removed');
            }
        };
        $scope.setpo = function () {
            cart.ponum = $scope.ponum;
            $scope.othercharges = 0;
            $scope.otherchargesdescription = '';
            // check for specials

            if ($scope.productspecials.length > 0 && $scope.productspecials[0].ProductSpecialType_ID !== 1) {
                for (var i = 0; i < products.length; ++i) {
                    for (var j = 0; j < $scope.productspecials.length; ++j) {
                        if ($scope.productspecials[j].s.Product_ID === ids[i]) {
                            switch ($scope.productspecials[j].s.ProductSpecialType_ID) {
                                case 2:
                                    if (quantity[i] >= $scope.productspecials[j].s.OrderedQuantity) {
                                        var freequantity = $scope.productspecials[j].s.FreeQuantity * Math.floor(quantity[i] / $scope.productspecials[j].s.OrderedQuantity);

                                        for (var k = 0; k < products.length; ++k) {
                                            if (ids[k] === $scope.productspecials[j].s.FreeProduct_ID) {
                                                quantity[k] += freequantity;
                                                $scope.othercharges -= freequantity * price[k];
                                                break;
                                            }
                                            if (k === products.length - 1) {    // product not already in cart, add it
                                                ids.push($scope.productspecials[j].s.FreeProduct_ID);
                                                products.push($scope.productspecials[j].f.ProductCode);
                                                name.push($scope.productspecials[j].f.ProductName);
                                                weight.push($scope.productspecials[j].f.Weight);
                                                quantity.push(freequantity);
                                                var productPrice = $scope.catalogRowCollection.find(({ od }) => od.p.Product_ID === $scope.productspecials[j].s.FreeProduct_ID).od.Price;
                                                price.push(productPrice);
                                                $scope.othercharges -= productPrice * freequantity;
                                                break;
                                            }
                                        }
                                        $scope.otherchargesdescription === '' ? $scope.otherchargesdescription += $scope.productspecials[j].s.Description : $scope.otherchargesdescription += ', ' + $scope.productspecials[j].s.Description;
                                    }
                                    break;
                                case 3:
                                    if (price[i] * quantity[i] >= $scope.productspecials[j].s.OrderedAmount) {
                                        $scope.othercharges -= parseFloat((price[i] * quantity[i] * $scope.productspecials[j].s.PercentageDiscount / 100).toFixed(2));
                                        $scope.otherchargesdescription === '' ? $scope.otherchargesdescription += $scope.productspecials[j].s.Description : $scope.otherchargesdescription += ', ' + $scope.productspecials[j].s.Description;
                                    }
                                    break;
                            }
                        }
                    }
                }
            }

            if ($scope.productspecials.length > 0 && $scope.productspecials[0].ProductSpecialType_ID === 1) {
                if ($scope.total >= $scope.productspecials[0].OrderedAmount) {
                    $scope.othercharges -= parseFloat(($scope.total * $scope.productspecials[0].PercentageDiscount / 100).toFixed(2));
                    $scope.otherchargesdescription === '' ? $scope.otherchargesdescription += $scope.productspecials[0].Description : $scope.otherchargesdescription += ', ' + $scope.productspecials[0].Description;
                }
            }

            cart.othercharges = $scope.othercharges;
            cart.otherchargesdescription = $scope.otherchargesdescription;
        };
        $scope.repeatorder = function () {
            $http.get('/orders/' + $scope.accountid + '/lastdetails')
                .then(function (response) {
                    var details = response.data;
                    cart.id.splice(0);
                    cart.product.splice(0);
                    cart.name.splice(0);
                    cart.price.splice(0);
                    cart.quantity.splice(0);
                    cart.weight.splice(0);
                    cart.dimensions.splice(0);

                    for (var i = 0; i < details.length; i++) {
                        cart.id.push(details[i].d.Product_ID);
                        cart.product.push(details[i].ProductCode);
                        cart.name.push(details[i].ProductName);
                        cart.quantity.push(details[i].d.Quantity);
                        cart.price.push(details[i].d.UnitPrice);
                        cart.weight.push(details[i].Weight);
                        cart.dimensions.push([details[i].Length, details[i].Width, details[i].Height]); //fix
                    }
                    init();
                    return;
                });
        }
        $scope.selectProduct = function (id, imgFile) {
            $http.get('/webproduct/' + id)
                .then(function (response) {
                    $scope.imgFile = imgFile;
                    $scope.selectedProduct = response.data;
                });
        }
    }
}());