"use strict";

appCore.controller("projectForecastReportCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter",
    function ($state, $scope, $http, $timeout, vServices, filterFilter) {
        $scope.$root.page.title = "Project Weekly Timeline";
        $scope.btn = {name: "Set Project Info", icon: "fa-save", screen: "Add"};
        $scope.forecastProfile=[];
        $scope.revenueCenters = [];
        $scope.project = [];
        $scope.reportData=[];
        $scope.weeks=[];
        $scope.totalAmt=0;
        $scope.lenColSpan=0;
        $scope.reportData = [];
        $scope.reportDataDetail=[];
        $scope.dTable=null;
        $scope.dTable2=null;
        $scope.filter = {
            rc_name:'0',
            proj_id:0,
        };

        $scope.projectByRevenue = (rev_id) => {
            vServices.callApi("myDiary/allmyDiaryProjects?rev_id="+ rev_id, "GET", {}).then(res => convertDataForProject(res));
        };

        const convertDataForProject = res => {
            if (res) {
              $scope.project = [];
              $scope.project.push({id: 0, name: " Select Project", proj_status: "active"});
              res = $scope.$root.sort(res, "proj_name");
              res = res.filter(proj => proj.proj_status === "active");
              res.map((o) => $scope.project.push({id: o.projectid, name: o.proj_name, proj_status: o.proj_status, proj_mydiaryLockDate: o.proj_mydiaryLockDate}));
              $scope.filter.project = $scope.project[0];
            }
        };

        $scope.tmpForecastData = [];
        $scope.fetchReport = (proj_id)=>{
            if($scope.dTable)$scope.dTable.destroy();
            $scope.showLoader = true;
            $scope.tmpForecastData = [];
            $scope.reportData = [];
            $scope.reportDataDetail = [];
            $scope.$root.callDataTable("#forecastreport", 100);
            vServices.callApi("project/project_forecast_dtl?projectid=" + proj_id, "GET").then(function (res) {
                if(res){
                    $scope.tmpForecastData = res;
                    vServices.callApi("project/getForecastReport?proj_id="+proj_id, "GET").then(function (result) {
                        if(result){
                            var returnArray = $scope.convertData(result.weeksData);
                            var totalAmt = 0;
                            returnArray.forEach(i=>{
                                var x = 0,Hours=0;
                                res.forEach(j=>{
                                    j.weekly_rate = parseFloat(j.weekly_rate);
                                    j.profile_id = parseInt(j.profile_id);
                                    if(parseInt(i.profile_id)==j.profile_id){
                                        var actualHours=0;
                                        i.weeks.forEach(element=>{
                                            actualHours+=parseFloat(element.total_hours);
                                            if(j.week_number==parseInt(element.week)){
                                                element.forecastHour = j.weekly_rate ? j.weekly_rate:0;
                                            }
                                        });
                                        i.actualHours=actualHours;
                                        Hours+=j.weekly_rate?parseFloat(j.weekly_rate):0;
                                        x = actualHours;
                                    }
                                })
                                i.Hours=Hours;
                                totalAmt+=x;
                            });
                            $scope.reportData = returnArray;
                            $scope.totalAmt = totalAmt;
                            // Extracting unique weeks from the data
                            
                            result.weeks.forEach(wk => {
                                let s = moment(wk.start_date_of_week,'YYYY-MM-DD').format('YYYY-MM-DD');
                                let e = moment(wk.end_date_of_week,'YYYY-MM-DD').format('YYYY-MM-DD');
                                wk.start_day = moment(s).format('DD');
                                wk.end_day = moment(e).format('DD');
                            });
                            $scope.weeks = result.weeks;
                            console.log(result.weeks);

                            $scope.lenColSpan = ($scope.weeks.length * 2) + 3;
                            // $scope.$root.callDataTable("#", 100, (t) => {
                            //     $scope.reportData.push(t);
                            // }, {orientation: "landscape"});
                            $scope.$root.callDataTable("#forecastreport", 500, (t) => {
                                $scope.dTable = t;
                            }, {orientation: "landscape"});	
                            // Sorting weeks array
                            // $scope.weeks.sort((a, b) => a - b);
                        }
                    });
                }
            });
            $scope.showLoader = false;
        }

        $scope.convertData=(inputData)=>{
            // Creating an array of objects according to profile IDs
            const result = inputData.reduce((acc, currentWeek) => {
                currentWeek["0"].forEach(entry => {
                    const profileId = parseInt(entry.profile_id);
                    const existingEntry = acc.find(item => parseInt(item.profile_id) === profileId);
                    if (existingEntry) {
                        existingEntry.weeks.push({
                            week: currentWeek.week,
                            total_hours: entry.total_hours,
                            name:entry.profile_name,
                            start:currentWeek.start,
                            end:currentWeek.end,
                        });
                    } else {
                        acc.push({
                            profile_id: profileId,
                            name:entry.profile_name,
                            weeks: [{
                                week: currentWeek.week,
                                total_hours: entry.total_hours,
                                start:currentWeek.start,
                                end:currentWeek.end,
                            }]
                        });
                    }
                });
                return acc;
            }, []);
            console.log(result);
            return result;
        }

        $scope.convertDataDetail2=(inputData)=>{
            // Creating an array of objects according to profile IDs
            const result = inputData.reduce((acc, currentWeek) => {
                currentWeek["0"].forEach(entry => {
                    const profileId = parseInt(entry.profile_id);
                    const existingEntry = acc.find(item => parseInt(item.emp_id));
                    if (existingEntry) {
                        acc.weeks.push({
                            week: currentWeek.week,
                            total_hours: entry.total_hours,
                            name:entry.emp_first_name,
                            billing_rate:parseFloat(entry.billing_rate),
                        });
                    } else {
                        acc.push({
                            profile_id: profileId,
                            name:entry.emp_first_name,
                            billing_rate:parseFloat(entry.billing_rate),
                            weeks: [{
                                week: currentWeek.week,
                                total_hours: entry.total_hours,
                            }]
                        });
                    }
                });
                return acc;
            }, []);
            return result;
        }

        $scope.convertDataDetail = (jsonData)=>{
            // Iterate through weeks
            var employeeData = [];
            var employeeData2 = [];
            jsonData.forEach(weekData => {
                const weekNumber = weekData.week;
                weekData['0'].forEach(employeeRecord => {
                    const empId = employeeRecord.emp_id;
                    if (!employeeData[empId]) {
                        employeeData[empId] = [];
                    }
                    employeeData[empId].push({
                        week: weekNumber,
                        total_hours: parseFloat(employeeRecord.total_hours),
                        billing_rate: parseFloat(employeeRecord.billing_rate)
                    });

                    if(!employeeData2.find(x=>x.emp_id==empId))
                        employeeData2.push({'emp_id':empId,name:employeeRecord.emp_first_name,weeks:employeeData[empId]});
                });
            });
            return employeeData2;
        }

        $scope.getProfileDetail = (profileId)=>{
            if($scope.dTable2)$scope.dTable2.destroy();
            $scope.reportDataDetail = [];
            $scope.$root.callDataTable("#forecastreportdetail", 100);
            vServices.callApi("project/getForecastReportDetail?profile_id="+profileId+'&proj_id='+$scope.filter.proj_id, "GET").then(function (result) {
                if(result){
                    var returnArray = $scope.convertDataDetail(result);
                    var totalAmt = 0;
                    console.log($scope.tmpForecastData);
                    returnArray.forEach(i=>{
                        var x = 0;
                        $scope.tmpForecastData.forEach(j=>{
                            j.weekly_rate = parseFloat(j.weekly_rate);
                            if(profileId==parseInt(j.profile_id)){
                                var actualHours=0;
                                i.weeks.forEach(element=>{
                                    actualHours+=parseFloat(element.total_hours);
                                    if(j.week_number==element.week){
                                        element.forecastHour = j.weekly_rate ? j.weekly_rate:0;
                                    }else{
                                        element.forecastHour = 0;
                                    }
                                });
                                i.actualHours=actualHours;
                                i.Hours = actualHours+j.weekly_rate;
                                x = actualHours;
                            }
                        })
                        totalAmt+=x;
                    });
                    $scope.reportDataDetail = returnArray;
                    $scope.totalAmt = totalAmt;
                    console.log($scope.reportDataDetail);

                    // $scope.$root.callDataTable("#forecastreportdetail", 100, (t) => {
                    //     $scope.reportDataDetail.push(t);
                    // }, {orientation: "landscape"});
                    $scope.$root.callDataTable("#forecastreportdetail", 500, (t) => {
                        $scope.dTable2 = t;
                    }, {orientation: "landscape"});	

                    $scope.lenColSpan = ($scope.weeks.length * 2) + 3;
                }
            });
        }

        const init = function () {
            vServices.callApi("/account/all_revenue_centers", "GET", {}).then(function (res) {
                if (res && res.length > 0) {
                    $scope.revenueCenters = res;
                }
              });
            vServices.callApi("project/projectForecastProfile", "GET").then(function (res) {
                if (res.length>0){
                    $scope.forecastProfile = res;
                }
            });
        };
        init();
    }
]);
