middleware('auth'); $this->_service = 'ums'; $this->_module = 'group'; $this->_viewname = 'grid'; $this->_title = 'Summary'; $this->_base_url = '/report'; } public function summary(Request $request) { return view('grid.list')->with(['title' => $this->_title]); } public function activitywise(Request $request) { return view('grid.activitywise')->with(['title' => 'Activity Wise']); } public function bdesummary(Request $request){ $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bdesummaryreport', ["month" => "November 2023"]); return view('report.bdesummary')->with(['days' => $response->data->days, 'ems' => $response->data->ems, 'zbms' => $response->data->zbms, 'rbms' => $response->data->rbms, 'totals' => $response->data->totals]); } public function rbmwiseweekly(Request $request){ $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bderbmwiseweekly', ["month" => "November 2023"]); return view('report.bdesummary')->with(['days' => $response->data->days, 'ems' => $response->data->ems, 'zbms' => $response->data->zbms, 'rbms' => $response->data->rbms]); } public function drreferralanalysis(Request $request){ $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bdedrreferralanalysis', ["month" => "November 2023"]); //echo '
'; print_r($response); exit;
        return view('report.drreferralanalysis')->with(['doctors' => $response->data->doctors, 'days' => $response->data->days]);
    }
    public function drreferralsummary(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bdedrreferralsummary', ["month" => "November 2023"]);
        //echo '
'; print_r($response); exit;
        return view('report.drreferralsummary')->with(['regions' => $response->data->regions, 'days' => $response->data->days]);
    }
    public function bdedevicewise(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bdedevicewise', ["month" => "November 2023"]);
        //echo '
'; print_r($response); exit;
        return view('report.bdedevicewise')->with(['metrics' => $response->data->metrics]);
    }
    public function bderbmwise(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bderbmwise', ["month" => "November 2023"]);
        //echo '
'; print_r($response); exit;
        return view('report.bderbmwise')->with(['rbms' => $response->data->rbms, 'weeks' => $response->data->weeks]);
    }
    public function bdeeducatorwiseaverage(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bdeeducatorwiseaverage', ["month" => "November 2023"]);
        //echo '
'; print_r($response); exit;
        return view('report.bdeeducatorwiseaverage')->with(['rbms' => $response->data->rbms, 'days' => $response->data->days]);
    }

    public function bdedevicedashboard(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bdedevicedashboard', ["month" => "November 2023"]);
        //echo '
'; print_r($response); exit;
        //return view('report.bdedevicewise')->with(['metrics' => $response->data->metrics]);
        return response()->json( $response->data );
    }

    protected function getmonths(){
        $month = date("m",strtotime("now")) >= 4 ? 'April '.date("Y", strtotime("now")) : 'April '.date("Y", strtotime("last year"));
        $thismonth = strtotime("now");
        $month = strtotime($month);
        $months = [];
        while($month <= $thismonth) {
            $months[] = date("F Y", $month);
            $month = $month + (60*60*24)*date("t", $month);
        }
        return $months;
    }

    public function bfactivitywise(Request $request){
        $teams = DB::connection('primary')->table('breathefree_team')->select('team')->distinct()->get();
        $regions = DB::connection('primary')->table('breathefree_team')->select('region')->distinct()->get();
        $months = $this->getmonths();
        //echo '
'; print_r($regions);print_r($teams); exit;
        return view('report.bfactivitywise')->with(['teams' => $teams, 'regions' => $regions, 'months' => $months]);
    }
    public function postajaxdatabfactivitywise(Request $request){
        $params = $request->except('_token');
        if(isset($params['team'])) {
            $params['team'] = json_encode($params['team']);
        }
        if(isset($params['brand'])) {
            $params['brand'] = json_encode($params['brand']);
        }
        Log::debug(print_r($params, true));
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bfactivitywise', $params);
        $request->session()->put('bfactivitywise_files', $response->data->files);
        return response()->json(["total" => $response->data->total_count , "jsondata" => json_decode(file_get_contents( $response->data->jsonfile ), true)] );
    }
    public function ajaxdatabfactivitywise(Request $request){
        $files = $request->session()->get('bfactivitywise_files');
        $fileno = $request->input('fileno', '0');
        return response()->json(json_decode(file_get_contents( $files[$fileno] ), true));
    }

    public function bfedudoctorwise(Request $request){
        // $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bfedudoctorwise');
        // echo '
'; print_r($response); exit;
        return view('report.bfedudoctorwise');
    }
    public function ajaxdatabfedudoctorwise(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bfedudoctorwise', ["month" => "July 2023"]);
        //echo '
'; print_r($response); exit;
        return response()->json( json_decode(file_get_contents( $response->data->jsonfile ), true) );
    }
    public function bfdoctorwise(Request $request){
        return view('report.bfdoctorwise');
    }
    
    public function bfeducatorwise(Request $request){
        $specialities = DB::table("bfdashboard_contacts")->select("speciality")->distinct()->get();
        //print_r($specialities); exit;
        return view('report.bfeducatorwise')->with(["specialities" => $specialities]);
    }
    public function ajaxdatabfeducatorwise(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bfeducatorwise', ["month" => "July 2023"]);
        //echo '
'; print_r($response); exit;
        return response()->json( json_decode(file_get_contents( $response->data->jsonfile ), true) );
    }

    public function bfsummary(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bfsummary', ["startmonth" => "April 2023", "endmonth" => "December 2023"]);
        foreach((array)$response->data->days as $t => $d) {
            $response->data->days->{$t} = date("j M Y", strtotime( str_replace('T00:00:00.000Z', '', $d) ) );
        }
        //echo '
'; print_r($response); exit;
        //$specialities = DB::table("bfdashboard_contacts")->select("speciality")->distinct()->get();
        $request->session()->put('bfsummary_jsonfile', $response->data->jsonfile);
        return view('report.bfsummary')->with(['days' => (array)$response->data->days, 'specialities' => (array)$response->data->specialities, 'devices' => (array)$response->data->devices, 'brands' => (array)$response->data->brands, 'teams' => (array)$response->data->teams ]);
    }
    public function ajaxdatabfsummary(Request $request){
        $jsonfile =  $request->session()->get('bfsummary_jsonfile');
        return response()->json( json_decode(file_get_contents( $jsonfile ), true) );
    }

    public function bfsummary2(Request $request){
        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bfsummary2', ["month" => "August 2023"]);
        //echo '
'; print_r($response); exit;
        $specialities = DB::table("bfdashboard_contacts")->select("speciality")->distinct()->get();
        //$request->session()->put('bfsummary_jsonfile', $response->data->jsonfile);
        return view('report.bfsummary2')->with(['days' => $response->data->days, 'specialities' => $specialities, 'metrics' => $response->data->metrics ]);
    }

    public function bfzonewise(Request $request)
    {
        $startmonth = $request->input('startmonth', date("m",strtotime("now")) >= 4 ? 'April '.date("Y", strtotime("now")) : 'April '.date("Y", strtotime("last year"))  );
        $endmonth = $request->input('endmonth', date("F Y", strtotime("last month") ) );
        $brand = $request->input('brand', 'Seroflo' );

        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bfzonewise', ["startmonth" => $startmonth, "endmonth" => $endmonth, "brand" => $brand ]);
        $response->data->{'startmonth'} = $startmonth;
        $response->data->{'endmonth'} = $endmonth;
        $response->data->{'brand'} = $brand;

        //echo '
'; print_r((array)$response->data); exit;

        $month = date("m",strtotime("now")) >= 4 ? 'April '.date("Y", strtotime("now")) : 'April '.date("Y", strtotime("last year"));
        $thismonth = strtotime("now");
        $month = strtotime($month);
        $months = [];
        while($month <= $thismonth) {
            $months[] = date("F Y", $month);
            $month = $month + (60*60*24)*date("t", $month);
        }
        $response->data->{'months'} = $months;

        //echo '
';print_r($response->data); exit;

        return view('report.bfzonewise')->with((array)$response->data);
    }

    public function downloadrxbers(Request $request)
    {
        $startmonth = $request->input('startmonth', date("m",strtotime("now")) >= 4 ? 'April '.date("Y", strtotime("now")) : 'April '.date("Y", strtotime("last year"))  );
        $endmonth = $request->input('endmonth', date("F Y", strtotime("last month") ) );
        $brand = $request->input('brand', '' );
        $zones = $request->input('zones', '' );
        $regions = $request->input('regions', '' );

        $zones = explode(',', $zones);
        $regions = explode(',', $regions);

        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/downloadrxbers', ["startmonth" => $startmonth, "endmonth" => $endmonth, "brand" => $brand, "zones" => json_encode($zones), "regions" => json_encode($regions)]);

        //echo '
'; print_r($response); exit;

        $headers = ['Doctor Name', 'MSL Code', 'Speciality', 'Zone', 'State', 'Region'];
        $exceldata[] = $headers;
        foreach($response->data->doctors as $doctor) {
            $csv = [$doctor->doctor_name, $doctor->msl_code, $doctor->doctor_speciality, $doctor->zone, $doctor->state, $doctor->region ];
            $exceldata[] = $csv;
        }
        return Excel::download(new InvoicesExport($exceldata), 'Doctors.xlsx');



        // $headers = ['Doctor Name', 'MSL Code', 'Speciality', 'Educator Name', 'Educator Manager', 'ABM', 'RBM', 'Zone', 'State', 'Region', 'Work Location', 'Pincode'];
        // $exceldata[] = $headers;
        // foreach($response->data->doctors as $doctor) {
        //     $exceldata[] = [$doctor->doctor_name, $doctor->new_msl_code, $doctor->doctor_speciality, $doctor->educator_name, $doctor->edm, $doctor->am, $doctor->rm, $doctor->zone, $doctor->state_name, $doctor->mini_region_name, $doctor->work_location, $doctor->pincode, ];
        // }
        // return Excel::download(new InvoicesExport($exceldata), 'doctors.xlsx');


        // echo '
';print_r($response->data); exit;

        // return view('index')->with((array)$response->data);
    } 

    protected function getMonthsInRange($startDate, $endDate){
        $months = array();

        while (strtotime($startDate) <= strtotime($endDate)) {
            $months[] = array(
                'year' => date('Y', strtotime($startDate)),
                'month' => date('m', strtotime($startDate)),
                'date' => date('Y-m-01', strtotime($startDate))
            );
            $startDate = date('01 M Y', strtotime($startDate . '+ 1 month'));
        }
        return $months;
    }

    public function downloadfbbizdocs(Request $request)
    {
        $month = $request->input('month', '' );
        $brand = $request->input('brand', '' );
        $zones = $request->input('zones', '' );
        $regions = $request->input('regions', '' );

        $startmonth = $request->input('startmonth', '' );
        $endmonth = $request->input('endmonth', '' );

        $zones = explode(',', $zones);
        $regions = explode(',', $regions);

        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/downloadfbbizdocs', ["month"=>$month,"startmonth"=>$startmonth, "endmonth"=>$endmonth,"brand"=>$brand, "zones"=> json_encode($zones), "regions" => json_encode($regions)]);
        $doctors = json_decode(file_get_contents( $response->data->json ), false);

        $headers = ['Doctor Name', 'MSL Code', 'Speciality', 'Zone', 'State', 'Region'];
        foreach($doctors->doctors[0]->business as $da => $buss) {
            $headers[] = date('M Y', strtotime($da)) . ' Business';
        }
        $exceldata[] = $headers;
        foreach($doctors->doctors as $doctor) {
            $csv = [$doctor->doctor_name, $doctor->msl_code, $doctor->doctor_speciality, $doctor->zone, $doctor->state, $doctor->region ];
            foreach($doctor->business as $buss) {
                $csv[] = $buss;
            }
            $exceldata[] = $csv;
        }
        return Excel::download(new InvoicesExport($exceldata), $month . '-' . $brand . '-doctors.xlsx');


        if($month == '') {
            $startmonth = $request->input('startmonth', '' );
            $endmonth = $request->input('endmonth', '' );
            $months = $this->getMonthsInRange($startmonth, $endmonth);
            
            $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/downloadfbbizdocs', ["startmonth"=>$startmonth, "endmonth"=>$endmonth, "brand"=>$brand, "zones"=> json_encode($zones), "regions" => json_encode($regions)]);
            $doctors = json_decode(file_get_contents( $response->data->json ), false);
            //echo '
'; print_r($doctors); exit;
            $headers = ['Doctor Name', 'MSL Code', 'Speciality', $brand.' Business'];

            foreach($months as $mon) {
                $headers[] = date("M Y", strtotime($mon['date'])).' Business';
            }
            $headers = array_merge($headers, ['No of Activity', 'Educator Name', 'Educator Manager', 'ABM', 'RBM', 'Zone', 'State', 'Region', 'Work Location', 'Pincode']);
            $exceldata[] = $headers;
            foreach($doctors->doctors as $doctor) {
                $exceld = [$doctor->doctor_name, $doctor->new_msl_code, $doctor->doctor_speciality, $doctor->business];
                foreach($months as $mon) {
                    $exceld[] = isset($doctor->months->{$mon['date']}) ? number_format( ((int)$doctor->months->{$mon['date']}->business), 2, '.','') : '-';
                }
                $exceldata[] = array_merge($exceld, [$doctor->count, $doctor->educator_name, $doctor->edm, $doctor->am, $doctor->rm, $doctor->zone, $doctor->state_name, $doctor->mini_region_name, $doctor->work_location, $doctor->pincode]);
                //echo '
'; print_r($exceldata); exit;
            }

        } else {
            $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/downloadfbbizdocs', ["month"=>$month, "brand"=>$brand, "zones"=> json_encode($zones), "regions" => json_encode($regions)]);
            $doctors = json_decode(file_get_contents( $response->data->json ), false);

            $headers = ['Doctor Name', 'MSL Code', 'Speciality', $brand.' Business', 'No of Activity', 'Educator Name', 'Educator Manager', 'ABM', 'RBM', 'Zone', 'State', 'Region', 'Work Location', 'Pincode'];
            $exceldata[] = $headers;
            foreach($doctors->doctors as $doctor) {
                $exceldata[] = [$doctor->doctor_name, $doctor->new_msl_code, $doctor->doctor_speciality, $doctor->business, $doctor->count, $doctor->educator_name, $doctor->edm, $doctor->am, $doctor->rm, $doctor->zone, $doctor->state_name, $doctor->mini_region_name, $doctor->work_location, $doctor->pincode, ];
            }
        }
        return Excel::download(new InvoicesExport($exceldata), $month . '-' . $brand . '-doctors.xlsx');


        echo '
';print_r($response->data); exit;

        return view('index')->with((array)$response->data);
    }

    public function downloadsourcezip(Request $request) {
        $startmonth = $request->input('startmonth', 'April 2023' );
        $endmonth = $request->input('endmonth', date("F Y", strtotime("last month") ) );
        $team = $request->input('team', "Team 1" );
        $zipFilekey =  Str::slug($team.'_'.$startmonth.'_'.$endmonth);
        $folder = storage_path('app/public/downloads');
        if(file_exists($folder.'/'.$zipFilekey.'.zip')) {
            return response()->download($folder.'/'.$zipFilekey.'.zip');
        }
        $zfiles = ['Sales_Connect_Mar24.xlsb', 'Quadrant_Analysis_Mar24.xlsb', 'SalesConnect_Apr24.xlsb', 'QuadrantAnalysis_May24.xlsx', 'SalesConnect_May24.xlsb', 'PTE_TP_RM_Wise_Dec_24.xlsx', 'Sales_Connect_FY24_Apr_to_Feb.xlsx', 'Quadrant_Analysis_FY24_Apr_to_Aug.xlsx', 'Base_LY_vs_CY.xlsb', 'Monthly_Trend_till_july25.xlsb', 'ZM_TP_of_Dec.xlsx', 'RM_TP_of_Dec.xlsx','BF_Educator_PT_TP_Jan_25.xlsb'];

        exec('mkdir '.$folder.'/'.$zipFilekey);
        foreach ($zfiles as $i => $zf) {
            exec('cp '.$folder.'/'.$zf.' '.$folder.'/'.$zipFilekey.'/'.basename($folder.'/'.$zf) );
        }
        exec('cd '.$folder.'/; zip -r '.$zipFilekey.'.zip '.$zipFilekey.'/');
        return response()->download($folder.'/'.$zipFilekey.'.zip');
    }

    public function bfdashboards(Request $request) {
        $startmonth = $request->input('startmonth', 'March 2025' );
        $endmonth = $request->input('endmonth', date("F Y", strtotime("last month") ) );
        $team = $request->input('team', "Team 1" );
        $brands = $request->input('brands', '' );
        $zones = $request->input('zones', '' );
        $regions = $request->input('regions', '' );
        $speciality = $request->input('speciality', '' );
        $states = $request->input('states', '' );

        $brands = explode(',', $brands);
        $zones = explode(',', $zones);
        $regions = explode(',', $regions);
        $speciality = explode(',', $speciality);
        $states = explode(',', $states);

        $response = LambdaRequest::signedrequest('get', 'catalog', 'activity/bfdashboards_new', ["startmonth" => $startmonth, "endmonth" => $endmonth, "team" => $team, "brands" => json_encode($brands), "zones" => json_encode($zones), "regions" => json_encode($regions), "states" => json_encode($states), "speciality" => json_encode($speciality)]);
        $response->data->{'startmonth'} = $startmonth;
        $response->data->{'endmonth'} = $endmonth;
        $response->data->{'team'} = $team;
        $response->data->{'zones'} = $zones;
        $response->data->{'regions'} = $regions;
        $response->data->{'brands'} = $brands;
        $response->data->{'speciality'} = $speciality;
        $response->data->{'states'} = $states;

        //$month = date("m",strtotime("now")) >= 4 ? 'April '.date("Y", strtotime("now")) : 'April '.date("Y", strtotime("last year"));
        $month = 'April 2023';
        $thismonth = strtotime("-1 month");
        $month = strtotime($month);
        $months = [];
        while($month <= $thismonth) {
            $months[] = date("F Y", $month);
            $month = $month + (60*60*24)*date("t", $month);
        }
        $response->data->{'months'} = $months;
        //echo '
'; print_r($response->data); exit;
        return view('index_new')->with((array)$response->data);
    }
}