RootApp = angular.module('RootApp', ['angularMoment','ui.router',"ngMask","tooltips",'angular.chosen']);
RootApp.controller('RootCtr', function ($rootScope, $scope, $http,  $timeout, $state,$compile, $location,moment,$interval) {
    $rootScope.server = "/api";
});
RootApp.directive('rate', function () {
    return {
        restrict: 'E',
        scope: {
            ngModel: '=',
            ngValue: '=',
            label:  '='
        },
        template: `
`,
        controller: function ($rootScope, $scope, $element) {
            if ($scope.ngValue) $scope.ngModel = angular.copy($scope.ngValue)
            $scope.change = (e)=>{
                $scope.ngModel=e;
            }
            console.log($element);
        }
    }
});
RootApp.directive('info', function () {
    return {
        restrict: 'E',
        scope: { text: '='},
        template: `{{text}} `
    }
});
RootApp.directive('file', function () {
    return {
        restrict: 'E',
        scope: { src: '=' },
        template: ``,
        controller: function ($scope, $element) {
            $scope.src?.split(",").forEach(fileId => {
                const size = $element.attr('size') || 20;
                $($element[0]).append(`
                    
                         `);
            });
        }
    }
});
RootApp.directive('fileChange', [function () {
    return {
        restrict: 'A',
        scope: {
            fileChange: '&'
        },
        link: function (scope, element) {
            element.on('change', function (event) {
                scope.$apply(function () {
                    scope.fileChange({ $files: event.target.files });
                });
            });
        }
    };
}]);
RootApp.directive('fileInput', ['$http', '$timeout', function ($http, $timeout) {
    return {
        restrict: 'E',
        template: `
      
    `,
        scope: {
            ngModel: '=',
        },
        controller: ['$scope', '$http', '$element','$attrs', function ($scope, $http, $element) {
            $scope.files = [];
            $scope.isDragOver = false;
            $scope.ngModel = '';
            function resizeImage(file, callback) {
                const MAX_WIDTH = 1024;
                const MAX_HEIGHT = 1024;
                const img = new Image();
                const reader = new FileReader();
                reader.onload = function (e) {
                    img.src = e.target.result;
                    img.onload = function () {
                        let width = img.width;
                        let height = img.height;
                        // Calculate the new dimensions if the image is too large
                        if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                            if (width > height) {
                                height = Math.round((MAX_WIDTH / width) * height);
                                width = MAX_WIDTH;
                            } else {
                                width = Math.round((MAX_HEIGHT / height) * width);
                                height = MAX_HEIGHT;
                            }
                        }
                        // Create a canvas to resize the image
                        const canvas = document.createElement('canvas');
                        canvas.width = width;
                        canvas.height = height;
                        const ctx = canvas.getContext('2d');
                        // Draw the image to the canvas
                        ctx.drawImage(img, 0, 0, width, height);
                        // Convert canvas to blob and pass it to callback
                        canvas.toBlob(function (blob) {
                            const resizedFile = new File([blob], file.name, { type: file.type });
                            callback(resizedFile);
                        }, file.type);
                    };
                };
                reader.readAsDataURL(file);
            }
            // Open the file dialog
            $scope.openFileDialog = function () {
                $element.find('input[type="file"]').click();
            };
            // Handle file selection
            $scope.onFileSelect = function (files) {
                angular.forEach(files, function (file) {
                    if (file.type.startsWith('image/')) {
                        // Check if the file needs to be resized
                        resizeImage(file, function (resizedFile) {
                            const reader = new FileReader();
                            reader.onload = function (e) {
                                $timeout(function () {
                                    resizedFile.preview = e.target.result;
                                    resizedFile.isUploading = false;
                                    resizedFile.uploadProgress = 0;
                                    resizedFile.errorMessage = '';
                                    resizedFile.unic = false; // Placeholder for unic value from server
                                    $scope.files.push(resizedFile);
                                });
                            };
                            reader.readAsDataURL(resizedFile);
                        });
                    }
                });
            };
            // Check if all files are uploaded
            $scope.allUploaded = function () {
                return $scope.files.every(function(file) {
                    return file.unic || file.isUploading;
                });
            };
            // Upload a single file
            $scope.uploadFile = function (file) {
                file.isUploading = true;
                const formData = new FormData();
                formData.append('file', file);
                $http.post('/api/file/upload_code', formData, {
                    headers: { 'Content-Type': undefined },
                    transformRequest: angular.identity,
                    uploadEventHandlers: {
                        progress: function (e) {
                            if (e.lengthComputable) {
                                $timeout(function () {
                                    file.uploadProgress = Math.round((e.loaded / e.total) * 100);
                                });
                            }
                        }
                    }
                }).then(function (response) {
                    file.isUploading = false;
                   // file.isUploaded = true;
                    if (response.data && response.data.unic) {
                        file.unic = response.data.unic;
                        $scope.updateNgModel();
                    }
                }).catch(function () {
                    file.isUploading = false;
                    file.uploadProgress = 0;
                    file.errorMessage = 'Upload failed. Please try again.';
                });
            };
            // Upload all files
            $scope.uploadAll = function () {
                angular.forEach($scope.files, function (file) {
                    if (!file.unic && !file.isUploading) {
                        $scope.uploadFile(file);
                    }
                });
            };
            // Remove a file
            $scope.removeFile = function (file) {
                if (file.isUploading) {
                    alert('Cannot delete a file that is currently uploading.');
                    return;
                }
                const index = $scope.files.indexOf(file);
                if (index > -1) {
                    // If the file has been uploaded, optionally delete it from the server
                    if (file.unic && 0) {
                        $http.post('/api/file/delete', { unic: file.unic })
                            .then(function () {
                                // Successfully deleted on server
                            })
                            .catch(function () {
                                // Handle deletion error if necessary
                            });
                    }
                    $scope.files.splice(index, 1);
                    $scope.updateNgModel();
                }
            };
            // Update ngModel with comma-separated unic values
            $scope.updateNgModel = function () {
                const unicValues = $scope.files
                    .filter(file => file.unic)
                    .map(file => file.unic);
                $scope.ngModel = unicValues.join(',');
            };
            // Handle drag and drop
            const dropzone = $element[0].querySelector('.dropzone');
            dropzone.addEventListener('dragover', function (event) {
                event.preventDefault();
                $timeout(function () {
                    $scope.isDragOver = true;
                });
            });
            dropzone.addEventListener('dragleave', function (event) {
                event.preventDefault();
                $timeout(function () {
                    $scope.isDragOver = false;
                });
            });
            dropzone.addEventListener('drop', function (event) {
                event.preventDefault();
                const files = event.dataTransfer.files;
                $scope.isDragOver = false;
                $scope.onFileSelect(files);
            });
        }]
    };
}]);
RootApp.directive('chart', function () {
    return {scope: { data: '=', chart:'=' },
        template: '.',
        controller: function ($rootScope, $scope, $element,$timeout) {
            $timeout(()=>{
                $scope.chart.chart = $scope.chart.chart ?? {};
                $scope.chart.chart.renderTo=$element[0];
                new Highcharts.Chart($scope.chart);
            },300)
        }
    }});
RootApp.run(function (amMoment) { amMoment.changeLocale('ka');});
RootApp.config(function ($stateProvider,$locationProvider,$urlRouterProvider) {
    $stateProvider
            .state("/login", {
            url         : '/login',
            templateUrl: "/app/templates/login.php",
            controller: function ($scope,$rootScope,$http) {
                $scope.login=(u)=>{
                    $http.post($rootScope.server + "/login", u).then(function () {
                       // $rootScope.data_loaded = false;
                        Swal.fire("","თქვენ წარმატებით გაიარეთ ავტორიზაცია","success")
                        setTimeout(()=>{
                           location.href=`/`;
                        },200);
                    },()=>{
                        Swal.fire("","მომხმარებელი არ მოიძებნა","error")
                    });
                }
            }
        })
        .state("/", { url: '/',
            templateUrl: "/app/templates/main.php",
            controller: function ($state) {
                $state.go('/login');
        }})
        
    $urlRouterProvider.otherwise("/");
    $locationProvider.html5Mode({ enabled: true,  requireBase: false });
});
                    
                `);
            });
        }
    }
});
RootApp.directive('fileChange', [function () {
    return {
        restrict: 'A',
        scope: {
            fileChange: '&'
        },
        link: function (scope, element) {
            element.on('change', function (event) {
                scope.$apply(function () {
                    scope.fileChange({ $files: event.target.files });
                });
            });
        }
    };
}]);
RootApp.directive('fileInput', ['$http', '$timeout', function ($http, $timeout) {
    return {
        restrict: 'E',
        template: `
      
    `,
        scope: {
            ngModel: '=',
        },
        controller: ['$scope', '$http', '$element','$attrs', function ($scope, $http, $element) {
            $scope.files = [];
            $scope.isDragOver = false;
            $scope.ngModel = '';
            function resizeImage(file, callback) {
                const MAX_WIDTH = 1024;
                const MAX_HEIGHT = 1024;
                const img = new Image();
                const reader = new FileReader();
                reader.onload = function (e) {
                    img.src = e.target.result;
                    img.onload = function () {
                        let width = img.width;
                        let height = img.height;
                        // Calculate the new dimensions if the image is too large
                        if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                            if (width > height) {
                                height = Math.round((MAX_WIDTH / width) * height);
                                width = MAX_WIDTH;
                            } else {
                                width = Math.round((MAX_HEIGHT / height) * width);
                                height = MAX_HEIGHT;
                            }
                        }
                        // Create a canvas to resize the image
                        const canvas = document.createElement('canvas');
                        canvas.width = width;
                        canvas.height = height;
                        const ctx = canvas.getContext('2d');
                        // Draw the image to the canvas
                        ctx.drawImage(img, 0, 0, width, height);
                        // Convert canvas to blob and pass it to callback
                        canvas.toBlob(function (blob) {
                            const resizedFile = new File([blob], file.name, { type: file.type });
                            callback(resizedFile);
                        }, file.type);
                    };
                };
                reader.readAsDataURL(file);
            }
            // Open the file dialog
            $scope.openFileDialog = function () {
                $element.find('input[type="file"]').click();
            };
            // Handle file selection
            $scope.onFileSelect = function (files) {
                angular.forEach(files, function (file) {
                    if (file.type.startsWith('image/')) {
                        // Check if the file needs to be resized
                        resizeImage(file, function (resizedFile) {
                            const reader = new FileReader();
                            reader.onload = function (e) {
                                $timeout(function () {
                                    resizedFile.preview = e.target.result;
                                    resizedFile.isUploading = false;
                                    resizedFile.uploadProgress = 0;
                                    resizedFile.errorMessage = '';
                                    resizedFile.unic = false; // Placeholder for unic value from server
                                    $scope.files.push(resizedFile);
                                });
                            };
                            reader.readAsDataURL(resizedFile);
                        });
                    }
                });
            };
            // Check if all files are uploaded
            $scope.allUploaded = function () {
                return $scope.files.every(function(file) {
                    return file.unic || file.isUploading;
                });
            };
            // Upload a single file
            $scope.uploadFile = function (file) {
                file.isUploading = true;
                const formData = new FormData();
                formData.append('file', file);
                $http.post('/api/file/upload_code', formData, {
                    headers: { 'Content-Type': undefined },
                    transformRequest: angular.identity,
                    uploadEventHandlers: {
                        progress: function (e) {
                            if (e.lengthComputable) {
                                $timeout(function () {
                                    file.uploadProgress = Math.round((e.loaded / e.total) * 100);
                                });
                            }
                        }
                    }
                }).then(function (response) {
                    file.isUploading = false;
                   // file.isUploaded = true;
                    if (response.data && response.data.unic) {
                        file.unic = response.data.unic;
                        $scope.updateNgModel();
                    }
                }).catch(function () {
                    file.isUploading = false;
                    file.uploadProgress = 0;
                    file.errorMessage = 'Upload failed. Please try again.';
                });
            };
            // Upload all files
            $scope.uploadAll = function () {
                angular.forEach($scope.files, function (file) {
                    if (!file.unic && !file.isUploading) {
                        $scope.uploadFile(file);
                    }
                });
            };
            // Remove a file
            $scope.removeFile = function (file) {
                if (file.isUploading) {
                    alert('Cannot delete a file that is currently uploading.');
                    return;
                }
                const index = $scope.files.indexOf(file);
                if (index > -1) {
                    // If the file has been uploaded, optionally delete it from the server
                    if (file.unic && 0) {
                        $http.post('/api/file/delete', { unic: file.unic })
                            .then(function () {
                                // Successfully deleted on server
                            })
                            .catch(function () {
                                // Handle deletion error if necessary
                            });
                    }
                    $scope.files.splice(index, 1);
                    $scope.updateNgModel();
                }
            };
            // Update ngModel with comma-separated unic values
            $scope.updateNgModel = function () {
                const unicValues = $scope.files
                    .filter(file => file.unic)
                    .map(file => file.unic);
                $scope.ngModel = unicValues.join(',');
            };
            // Handle drag and drop
            const dropzone = $element[0].querySelector('.dropzone');
            dropzone.addEventListener('dragover', function (event) {
                event.preventDefault();
                $timeout(function () {
                    $scope.isDragOver = true;
                });
            });
            dropzone.addEventListener('dragleave', function (event) {
                event.preventDefault();
                $timeout(function () {
                    $scope.isDragOver = false;
                });
            });
            dropzone.addEventListener('drop', function (event) {
                event.preventDefault();
                const files = event.dataTransfer.files;
                $scope.isDragOver = false;
                $scope.onFileSelect(files);
            });
        }]
    };
}]);
RootApp.directive('chart', function () {
    return {scope: { data: '=', chart:'=' },
        template: '.',
        controller: function ($rootScope, $scope, $element,$timeout) {
            $timeout(()=>{
                $scope.chart.chart = $scope.chart.chart ?? {};
                $scope.chart.chart.renderTo=$element[0];
                new Highcharts.Chart($scope.chart);
            },300)
        }
    }});
RootApp.run(function (amMoment) { amMoment.changeLocale('ka');});
RootApp.config(function ($stateProvider,$locationProvider,$urlRouterProvider) {
    $stateProvider
            .state("/login", {
            url         : '/login',
            templateUrl: "/app/templates/login.php",
            controller: function ($scope,$rootScope,$http) {
                $scope.login=(u)=>{
                    $http.post($rootScope.server + "/login", u).then(function () {
                       // $rootScope.data_loaded = false;
                        Swal.fire("","თქვენ წარმატებით გაიარეთ ავტორიზაცია","success")
                        setTimeout(()=>{
                           location.href=`/`;
                        },200);
                    },()=>{
                        Swal.fire("","მომხმარებელი არ მოიძებნა","error")
                    });
                }
            }
        })
        .state("/", { url: '/',
            templateUrl: "/app/templates/main.php",
            controller: function ($state) {
                $state.go('/login');
        }})
        
    $urlRouterProvider.otherwise("/");
    $locationProvider.html5Mode({ enabled: true,  requireBase: false });
});