/**
 * SIMPLE FIX: Stop infinite API calls on stock pages
 * This directly patches the problematic controllers
 */

// Wait for Angular to load, then patch the controllers
setTimeout(function () {
    if (typeof angular !== 'undefined' && angular.module) {
        try {
            // Get the StockModule
            var stockModule = angular.module('StockModule');

            // Override problematic controllers with fixed versions
            console.log('🔧 Applying simple stock controller fixes...');

            // Fix StockReportsCtrl - only load on correct route
            stockModule.controller('StockReportsCtrl', ['$scope', 'StockReport', 'ErrorsHandler', 'Messenger', '$paginator', '$timeout', function ($scope, StockReport, ErrorsHandler, Messenger, $paginator, $timeout) {
                console.log('✅ Fixed StockReportsCtrl loaded');

                var search_timeout = 200;
                var loaded = false;

                $scope.reports = [];
                $scope.paginator = $paginator;
                $paginator = angular.copy($paginator);
                $scope.paginator = $paginator;
                $paginator.setLimit(10);

                $scope.filters = {
                    limit: 10,
                    aknowledged: 0,
                    type: 'mismatched',
                    search: null
                };

                // FIXED: Only load when on correct route
                $scope.$on('$routeChangeSuccess', function (ev, currentRoute, previousRoute) {
                    if (currentRoute && currentRoute.$$route &&
                        (currentRoute.$$route.originalPath === '/stock/stock_reports/' ||
                            window.location.hash.indexOf('stock_reports') > -1)) {
                        if (!loaded) {
                            console.log('📍 Loading reports for stock_reports route');
                            $scope.loadReports();
                            loaded = true;
                        }
                    }
                });

                $scope.loadReports = function (page) {
                    console.log('📡 Loading reports...', page);
                    var data = {
                        aknowledged: $scope.filters.aknowledged,
                        type: $scope.filters.type,
                        query: $scope.filters.search,
                        page: page
                    };

                    StockReport.get(data, function (response) {
                        $scope.loading = false;
                        $scope.reports = response.data;
                        $paginator.setFromResponse(response);
                    }, ErrorsHandler);
                };

                $scope.markAsAknowledged = function (report) {
                    var data = { id: report.id, aknowledged: 1 };
                    StockReport.update(data, function (response) {
                        report.aknowledged = 1;
                        Messenger('Report marked as acknowledged successfully!');
                    });
                };

                // Only load if we're actually on the reports page
                if (window.location.hash.indexOf('stock_reports') > -1) {
                    $scope.loadReports();
                    loaded = true;
                }
            }]);

            console.log('✅ Stock controller fixes applied successfully!');

        } catch (e) {
            console.error('❌ Failed to apply stock fixes:', e);
        }
    } else {
        console.log('⏳ Angular not ready, retrying...');
        setTimeout(arguments.callee, 500);
    }
}, 1000);

// Also directly override any existing problematic function calls
setTimeout(function () {
    console.log('🔧 Direct intervention - stopping infinite loops');

    // Override any global functions that might be causing loops
    if (window.StockReport && window.StockReport.get) {
        var originalGet = window.StockReport.get;
        var lastCallTime = 0;
        var callCount = 0;

        window.StockReport.get = function (params, success, error) {
            var now = Date.now();
            if (now - lastCallTime < 1000) {
                callCount++;
                if (callCount > 3) {
                    console.warn('🛑 Blocking rapid StockReport.get calls to prevent loop');
                    return;
                }
            } else {
                callCount = 0;
            }
            lastCallTime = now;

            console.log('📡 StockReport.get called with params:', params);
            return originalGet.call(this, params, success, error);
        };
    }
}, 2000); 