<?php

namespace App\Http\Controllers;

use DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use App\Account;
use Auth;
use Cache;
use Config;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class ReportController extends Controller {

    public function __construct() {
        $this->session = SESSION::All();
        date_default_timezone_set("Asia/Calcutta");
        $this->dimensions = '["advertiser","campaign","domain"]';
        //$this->nextDimensions = '["bundle"]';        
        $this->measures = '["rtbRequests","rtbRequestsIntents","bids","bidEcpm","bidEcpmDeviation","bidfloorEcpm","bidfloorEcpmDeviation","wins","impressions","clicks","ctr","cpc","cpcv","pretargetingRequests","exchangeWinCost","winCost","conversionCount1","conversionCount2","conversionCount3","conversionValue1","conversionValue2","conversionValue3","winEcpm","winEcpmDeviation","cpa1","cpa2","cpa3","convRate1","convRate2","convRate3","bidRate","winRate","measurableImpressions","measurabilityRate","viewableImpressions","viewabilityRate","conversionCount","conversionValue","served","videoImpressionsRate","firstQuartile","midpoint","thirdQuartile","complete","mute","unmute","pause","resume","fullscreen","exitFullscreen","skip","close","fail","dataSegmentUsage","dataSegmentCost","campaignNewUsers","campaignDailyUniqueUsers","dailyAvgUserWins","goalCompletionCost","totalCost","dailyAvgUserCost","clicksOnFirstImpression","clicksFiltered","winsFiltered","exchangeWinCostFiltered","impressionsFiltered","impTracked","impHidden","impCookieEnabled","impIframe","impMobileBrowser","impJavaEnabled","impFlashEnabled","impLanguageMismatchPercent","impDocumentWidthSq","impDocumentHeightSq","impWindowWidthSq","impWindowHeightSq","impScreenWidthSq","impScreenHeightSq","impDomainMismatch","impLanguageMismatch","impTrackedPercent","impHiddenPercent","impCookieEnabledPercent","impIframePercent","impMobileBrowserPercent","impJavaEnabledPercent","impJava5AndLowerPercent","impJava6Percent","impJava7Percent","impJava8AndGreaterPercent","impFlashEnabledPercent","impFlash9AndLowerPercent","impFlash10To11Percent","impFlash12To15Percent","impFlash16To20Percent","impFlash21AndGreaterPercent","impDocumentWidthAvg","impDocumentWidthDeviation","impDocumentHeightAvg","impDocumentHeightDeviation","impWindowWidthAvg","impWindowWidthDeviation","impWindowHeightAvg","impWindowHeightDeviation","impScreenWidthAvg","impScreenWidthDeviation","impScreenHeightAvg","impScreenHeightDeviation","impColorDepthAvg","impDomainMismatchPercent","impIpMismatchPercent","contentBids","retargetingBids","rtbRequestsSite","rtbRequestsUserSyncedPercent","rtbRequestsApp","rtbRequestsWithIfaPercent","impRequestsBanner","impRequestsNative","impRequestsVideo","impRequestsAudio","impRequestsSecurePercent","impRequestsWithViewability","impRequestsWithViewabilityPercent","impRequestsViewabilityAvg","impressionsWithViewability","impressionsWithViewabilityPercent","impressionsViewabilityAvg","keywordRequests","landingClicks","landingClicksDelayAvg","landingClickCtr","landingClickThroughRate","dataSegmentUsage","dataSegmentCost","pubAppRequests","campaignNewUsers","campaignDailyUniqueUsers","dailyAvgUserWins","goalCompletionCost","totalCost","dailyAvgUserCost","clicksOnFirstImpression"]';
        
    }
    /**
     * @param void
     * created by : Anurag Dubey
     * Date: 9 Nov 2021
     * Description : Fetches the reports data from adkernal API and insert/update the same in our vola ads DB.
    */
    public function getAdkernalReportDataAndSave(){
        /*ini_set("memory_limit", "-1");
        set_time_limit(0);
        try {
            //find actual campaign ids using adkernal ids
            $campaign_data = DB::table('dl_campaigns')
                    ->where('admin_status', '=', 'approved')
                    ->where('status', '=', 'running')
                    ->where('campaign_pricing_model','=','CPM')
                    ->where('ad_kernal_id','!=','0')
                    ->whereNotNull('ad_kernal_id')
                    ->pluck('campaign_id','ad_kernal_id');
                    
                    //echo"<pre>";print_r($campaign_data);
            //check if capiagns exists then proceed
            if(!empty($campaign_data)){
            
                foreach($campaign_data as $keys=>$vals){
                    //get data from s2s API via below curl request
                    $data = $this->sendHttpCurlRequest($vals);
                    //echo date('YmdHIs');die;
                    //echo"<pre>";print_r($data);die;
                    //if records from the API is found then proceed accordingly.
                    if(!empty($data) && $data['records']){
                        $ad_id = $pb_id = $ad_spot_id = $advrtsr_id = $brwsr_id = $oprtr_id = $os_id = $device_id = $url_id = $creative_id = 0;
                        $adkernal_campaign_id = array();
                        $cost_type = $revenue_type = 'CPM';
                        $report_date = date('Y-m-d');
                        $stat_date = date('md',strtotime($report_date));
                        $stat_hour = sprintf("%02d", date('H'));
                        if($stat_hour>=0 && $stat_hour<12){
                            $slot = "1";
                        } else {
                            $slot = "2";
                        }
                        //logic to generate the targetting key
                        
                        foreach($data['records'] as $key=>$val){
                            //the insertion/update logic goes here
                            if(isset($campaign_data[$val['campaign']])){
                                
                                $campaign_data_all= "";                            
                                $campaign_data_all = $this->getCampaignDataByCampaignId($campaign_data[$val['campaign']]);
                                $campaign_data_all = (array)$campaign_data_all;
                                //get campaign budget
                                $campaign_budget = $campaign_data_all['campaign_budget'];
                                //total spend calculation campaign wise
                                $total_spend = 0;
                                $total_spend = $this->getTotalSpendByCampaignId($campaign_data_all['campaign_id']);
                                //budget left calculation
                                $budget_left = $campaign_budget-$total_spend;
                                //check if budget to run campaign is left then proceed else pause the campaign
                                if($budget_left>0){
                                    $bundle = "";
                                    if(isset($val['bundle'])){
                                       $bundle = $val['bundle'];  
                                    } else if(isset($val['domain'])){
                                       $bundle = $val['domain'];  
                                    }
                                    
                                    $adkernal_campaign_id[] = $campaign_data[$val['campaign']];
                                    $targetting_key = $stat_date.$stat_hour.sprintf("%02d", $slot).sprintf("%05d", $ad_id).sprintf("%03d", $pb_id).sprintf("%05d", $ad_spot_id).sprintf("%02d", $brwsr_id).sprintf("%02d", $oprtr_id).sprintf("%02d", $os_id).sprintf("%02d", $device_id).sprintf("%05d", $url_id).sprintf("%05d", $creative_id).$campaign_data[$val['campaign']].$bundle;
                                    $buffer_imp_count = $buffer_clicks_count = $buffer_bid_count = $buffer_win_count = $buffer_conversions_count = $buffer_total_win_cost = $buffer_total_cost = $buffer_spend = 0;
                                    $get_hourly_buffer_data = DB::table('hourly_stat_buffer')->where('campaign_id', $campaign_data[$val['campaign']])->where('stat_date',date('Y-m-d'))->first();
                                    if(!empty($get_hourly_buffer_data)){
                                        $buffer_imp_count = $get_hourly_buffer_data->impression_count;
                                        $buffer_clicks_count = $get_hourly_buffer_data->clicks_count;
                                        $buffer_bid_count = $get_hourly_buffer_data->bid_count;
                                        $buffer_win_count = $get_hourly_buffer_data->win_count;
                                        $buffer_conversions_count = $get_hourly_buffer_data->conversions_count;
                                        $buffer_total_win_cost = $get_hourly_buffer_data->total_win_cost;
                                        $buffer_total_cost = $get_hourly_buffer_data->total_cost;
                                        $buffer_spend = $get_hourly_buffer_data->revenue_value;
                                    }
                                    //echo $buffer_imp_count;die;
                                    $advertiser_id = $this->getAdvertiserIdByCampaignId($campaign_data[$val['campaign']]);
                                    //spend calculations
                                    
                                    $campaign_pricing_model = "";
                                    $target_budget_type = "";
                                    $spend = 0;
                                    $target_bit_type_value=0;
                                    $campaign_data[$val['campaign']];
                                        //echo "<pre>";print_r($campaign_data_all);                            
                                    if(!empty($campaign_data_all)){
                                        $campaign_pricing_model = $campaign_data_all['campaign_pricing_model'];
                                        $target_bit_type = $campaign_data_all['target_bit_type'];
                                        $target_bit_type_value = $campaign_data_all['target_bit_type_value'];
                                        if($campaign_pricing_model=='CPI'){
                                            $spend = $target_bit_type_value*$val['conversionCount'];
                                        } else if($campaign_pricing_model=='CPM'){
                                            if($target_bit_type=='CPM'){
                                                $spend = (($val['impressions']/1000)*$target_bit_type_value);
                                            } else if($target_bit_type=='CPC'){
                                                $spend = $val['clicks']*$target_bit_type_value;
                                            }
                                        }
                                    }
                                     
                                    if (DB::table('hourly_stat')->where('campaign_id', $campaign_data[$val['campaign']])->where('stat_date',date('Y-m-d'))->where('source','=',$bundle)->exists()) {
                                       //echo "update:".$bundle."<br/>";
                                        //update the record basis campaign id
                                        DB::table('hourly_stat')
                                          ->where('campaign_id', $campaign_data[$val['campaign']])
                                          ->where('stat_date',date('Y-m-d'))
                                          ->where('source','=',$bundle)
                                          ->update([
                                            'advertiser_id'=>$advertiser_id,
                                            'impression_count'=>($val['impressions']+$buffer_imp_count),
                                            'clicks_count'=>($val['clicks']+$buffer_clicks_count),
                                            'bid_count'=>($val['bids']+$buffer_bid_count),
                                            'win_count'=>($val['wins']+$buffer_win_count),
                                            'conversions_count'=>($val['conversionCount']+$buffer_conversions_count),
                                            'total_win_cost'=>($val['winCost']+$buffer_total_win_cost),
                                            'total_cost'=>(round($val['totalCost'],4)+$buffer_total_cost),
                                            'revenue_value'=>($spend + $buffer_spend),
                                            'source'=> $bundle,
                                            'update_datetime'=>date('Y-m-d H:i:s')
                                          ]);
                                    } else {
                                        //echo $bundle."<br/>";
                                        //echo $targetting_key."<br/>";
                                        //insert the record basis campaign id
                                        DB::table('hourly_stat')->insert([
                                            'targetting_key' => $targetting_key,
                                            'ad_id' => $ad_id,
                                            'ad_spot_id' => $ad_spot_id,
                                            'publisher_id' => $pb_id,
                                            'campaign_id' => $campaign_data[$val['campaign']],
                                            'advertiser_id' => $advertiser_id,
                                            'url_id' => $url_id,
                                            'creativeid' => $creative_id,
                                            'browser_id' => $brwsr_id,
                                            'os_id' => $os_id,
                                            'operator_id'=>$oprtr_id,
                                            'device_id'=>$device_id,
                                            'revenue_type'=>$revenue_type,
                                            'cost_type'=>$cost_type,
                                            'impression_count'=>($val['impressions']+$buffer_imp_count),
                                            'clicks_count'=>($val['clicks']+$buffer_clicks_count),
                                            'bid_count'=>($val['bids']+$buffer_bid_count),
                                            'win_count'=>($val['wins']+$buffer_win_count),
                                            'conversions_count'=>($val['conversionCount']+$buffer_conversions_count),
                                            'total_win_cost'=>($val['winCost']+$buffer_total_win_cost),
                                            'total_cost'=>(round($val['totalCost'],4)+$buffer_total_cost),
                                            'stat_date'=>$report_date,
                                            'stat_hour'=>$stat_hour,
                                            'stat_slot'=>$slot,
                                            'revenue_value'=>$spend ,
                                            'source'=>$bundle,
                                            'update_datetime'=>date('Y-m-d H:i:s')
                                        ]);
                                   } 
                               
                               } else{
                                //pause the campaign on adkernal as well as on our vola panel as budget is over.
                                    DB::table('dl_campaigns')
                                    ->where('campaign_id','=', $campaign_data_all['campaign_id'])  
                                    ->update(['ad_status' => '0']);
                                    $this->makeAdkernalCampaignPausePlay($campaign_data_all['ad_kernal_id'],false);
                               }
                            } else {
                                continue;
                            }
                        }
                        //die;
                        //saving non ad kernal buffer table to hourly data
                        $non_adkernal_buffer_data = DB::table('hourly_stat_buffer')
                                            ->join('dl_campaigns','dl_campaigns.campaign_id', '=', 'hourly_stat_buffer.campaign_id')
                                            ->where('stat_date',date('Y-m-d'))
                                            ->where('dl_campaigns.campaign_pricing_model','=','CPM')
                                            ->where('dl_campaigns.status','=','running')
                                            ->where('dl_campaigns.is_automate','=','1')
                                            ->whereNotIn('hourly_stat_buffer.campaign_id',$adkernal_campaign_id)
                                            ->get();
                                            //echo"<pre>";print_r($non_adkernal_buffer_data);die;
                        if(!empty($non_adkernal_buffer_data)){
                          
                            foreach($non_adkernal_buffer_data as $k=>$v){
    
                                $targetting_key_new = $stat_date.$stat_hour.sprintf("%02d", $slot).sprintf("%05d", $ad_id).sprintf("%03d", $pb_id).sprintf("%05d", $ad_spot_id).sprintf("%02d", $brwsr_id).sprintf("%02d", $oprtr_id).sprintf("%02d", $os_id).sprintf("%02d", $device_id).sprintf("%05d", $url_id).sprintf("%05d", $creative_id).$v->campaign_id;
                                //echo $targetting_key_new;die;
                                if (DB::table('hourly_stat')->where('campaign_id', $v->campaign_id)->where('stat_date',date('Y-m-d'))->where('source','=',$v->source)->exists()) {
                                    //update the record basis campaign id
                                    DB::table('hourly_stat')
                                      ->where('campaign_id', $v->campaign_id)
                                      ->where('stat_date',date('Y-m-d'))                                  
                                      ->update([
                                        'advertiser_id'=>$v->advertiser_id,
                                        'impression_count'=>$v->impression_count,
                                        'clicks_count'=>$v->clicks_count,
                                        'bid_count'=>$v->bid_count,
                                        'win_count'=>$v->win_count,
                                        'conversions_count'=>$v->conversions_count,
                                        'total_win_cost'=>$v->total_win_cost,
                                        'total_cost'=>$v->total_cost,
                                        'revenue_value'=>$v->revenue_value ,
                                        'source'=>$v->source, 
                                        'update_datetime'=>date('Y-m-d H:i:s')
                                      ]);
                                } else {
                                    //insert the record basis campaign id
                                    DB::table('hourly_stat')->insert([
                                        'targetting_key' => $targetting_key_new,
                                        'ad_id' => $v->ad_id,
                                        'ad_spot_id' => $v->ad_spot_id,
                                        'publisher_id' => $v->publisher_id,
                                        'campaign_id' => $v->campaign_id,
                                        'advertiser_id' => $v->advertiser_id,
                                        'url_id' => $v->url_id,
                                        'creativeid' => $v->creativeid,
                                        'browser_id' => $v->browser_id,
                                        'os_id' => $v->os_id,
                                        'operator_id'=>$v->operator_id,
                                        'device_id'=>$v->device_id,
                                        'request_count'=>$v->request_count,
                                        'revenue_type'=>$v->revenue_type,
                                        'cost_type'=>$v->cost_type,
                                        'impression_count'=>$v->impression_count,
                                        'clicks_count'=>$v->clicks_count,
                                        'bid_count'=>$v->bid_count,
                                        'win_count'=>$v->win_count,
                                        'conversions_count'=>$v->conversions_count,
                                        'total_win_cost'=>$v->total_win_cost,
                                        'total_cost'=>$v->total_cost,
                                        'total_profit'=>$v->total_profit,
                                        'stat_date'=>$v->stat_date,
                                        'stat_hour'=>$v->stat_hour,
                                        'stat_slot'=>$v->stat_slot,
                                        'date_key'=>$v->date_key,
                                        'revenue_value'=>$v->revenue_value,
                                        'source'=>$v->source,
                                        'revenue_value_currency'=>$v->revenue_value_currency,
                                        'cost_value'=>$v->cost_value,
                                        'cost_value_currency'=>$v->cost_value_currency,
                                        'update_datetime'=>date('Y-m-d H:i:s')
                                    ]);
                                }
                            }
                        }
                        echo "Records imported successfully";
                    } else {
                        echo"Sorry! No records found from adkernal API";
                    }
                }
            } else {
                echo"Sorry! No active campaign records found";
            }
        
        } catch (\Exception $e) {

            echo $e->getMessage();
        }
        exit;*/
    }
    
    /**
     * @param void
     * created by : Anurag Dubey
     * Date: 9 Nov 2021
     * Description : sends HTTP curl request for get methods and generates the response.
    */
    private function sendHttpCurlRequest($campaign_id){
        try {
            $env_data = $this->getSourceEnvByCampaignId($campaign_id);
            if($env_data=='app'){
                $this->dimensions = '["advertiser","campaign","bundle"]';
            } else {
                $this->dimensions = '["advertiser","campaign","domain"]';
            }
            //echo $this->dimensions;die;
            $additionalHeaders = array();
            $username = Config::get('app.AdKernalApiConfig.username');
            $password = Config::get('app.AdKernalApiConfig.password');
            $start_date = date('Y-m-d', strtotime(' -1 day'));
            $end_date = date('Y-m-d', strtotime(' +1 day'));
            $filter = json_encode(array("account"=>"","date" => array (0 => 'between',1 =>array (0 => $start_date,1 => $end_date),),));//to get all data from API for campaign this must be passed as empty
            //echo $filter;die;
            $url = Config::get('app.AdKernalApiConfig.base_url')."reports?dimensions=".$this->dimensions."&measures=".$this->measures."&filters=".$filter;
            //echo $url;die;
            $log_arr = [];
            $log_arr['request'] = $url;
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
            curl_setopt($ch, CURLOPT_TIMEOUT, 300);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $output = curl_exec($ch);
            
            curl_close($ch);
            //print_r($output);die;
            $log_arr['response']=$output;
            $this->log($log_arr);
            return json_decode($output,true);
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
    
    /**
     * @param void
     * created by : Anurag Dubey
     * Date: 9 Nov 2021
     * Description : sends HTTP curl request for all methods and generates the response.
    */
    private function makeAdkernalCampaignPausePlay($campaign_id,$campaign_status){
        //echo $campaign_id."<br/>";
        //echo $campaign_status."<br/>"; die;
        try {
            $additionalHeaders = array();
            $username = Config::get('app.AdKernalApiConfig.username');
            $password = Config::get('app.AdKernalApiConfig.password');
            $request_body = array (0 => array (0 => $campaign_id,1 => array ('isActive' => $campaign_status,
    ),),);
            $url = Config::get('app.AdKernalApiConfig.base_url_s')."campaigns/";
            //echo $url;die;
            //echo json_encode($request_body);die;
            $log_arr = [];
            $log_arr['request'] = $url;
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
            curl_setopt($ch, CURLOPT_TIMEOUT, 300);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($request_body));
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $output = curl_exec($ch);
            //print_r($output);die;
            curl_close($ch);
            $log_arr['response']=$output;
            //$this->log($log_arr);
            //echo"<pre>";print_r(json_decode($output,true));die;
            return json_decode($output,true);
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
    /**
     * @param void
     * created by : Anurag Dubey
     * Date: 22 Nov 2021
     * Description : gets total spend by campaign id and returns the same.
    */
    private function getTotalSpendByCampaignId($campaign_id){
        try {
            $ttl_spd = 0;
            //find actual campaign ids using adkernal ids
            $campaign_data = DB::table('hourly_stat')
                    ->selectRaw("round(sum(revenue_value_currency),3)as spend_currency")
                    ->groupBy('hourly_stat.campaign_id')
                    ->where('campaign_id', $campaign_id)
                    ->first();
            if(!empty($campaign_data)){
                
                $ttl_spd = $campaign_data->spend_currency;
            }
            return $ttl_spd;
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
    /**
     * @param void
     * created by : Anurag Dubey
     * Date: 22 Nov 2021
     * Description : gets advertiser id by campaign id and returns the same.
    */
    private function getAdvertiserIdByCampaignId($campaign_id){
        try {
            $advertiser_id = "";
            //find actual campaign ids using adkernal ids
            $campaign_data = DB::table('dl_campaigns')
                    ->select('advertiser_id')
                    ->where('campaign_id', $campaign_id)
                    ->first();
                    //
            if(!empty($campaign_data)){
                
                $advertiser_id = $campaign_data->advertiser_id;
            }
            return $advertiser_id;
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
    
    /**
     * @param void
     * created by : Anurag Dubey
     * Date: 22 Nov 2021
     * Description : gets advertiser id by campaign id and returns the same.
    */
    private function getSourceEnvByCampaignId($campaign_id){
        try {
            $env_type = "";
            //find actual campaign ids using adkernal ids
            $campaign_data = DB::table('dl_campaigns')
                    ->select('target_env_type')
                    ->where('campaign_id', $campaign_id)
                    ->first();
                    //
                    //echo"<pre>";print_r($campaign_data);die;
            if(!empty($campaign_data)){
                
                $env_type = $campaign_data->target_env_type;
            }
            return $env_type;
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
    /**
     * @param void
     * created by : Anurag Dubey
     * Date: 22 Nov 2021
     * Description : gets advertiser id by campaign id and returns the same.
    */
    private function getCampaignDataByCampaignId($campaign_id){
        try {
            $campaign_data_arr = array();
            //find actual campaign ids using adkernal ids
            $campaign_data = DB::table('dl_campaigns')
                    ->where('campaign_id', $campaign_id)
                    ->first();
                    //
            if(!empty($campaign_data)){
                
                $campaign_data_arr = $campaign_data;
            }
            return $campaign_data_arr;
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
    /**
     * @param params
     * created by : Anurag Dubey
     * Date: 22 Nov 2021
     * Description : generates log file for APIs request and response.
    */
    private function log($params){
        if(!empty($params)){
            //first parameter passed to Monolog\Logger sets the logging channel name
            $orderLog = new Logger('api_log');
            $orderLog->pushHandler(new StreamHandler(storage_path('logs/api_log_'.date("Y-m-d").'.log')), Logger::INFO);
            $orderLog->info('ApiLog', $params);
        }

    }
    
    public function add_manual_data(Request $request){
         $params = array();
        
         $site_id_over_all_arr = array("trfc.collectcent.com");
         $cpc = 0;
         $ad_id = $request->campaign_id;
	     $advrtsr_id = $request->advertiser_id;
         $start_date = $request->start_date;
         $end_date = $request->end_date;
         $cpc = $request->cpc;
         $drange = $request->drange;
                                     
        $campaign_data_all = $this->getCampaignDataByCampaignId($ad_id);
        $campaign_data_all = (array)$campaign_data_all;
        
        $ads_id = $pb_id = $ad_spot_id = $brwsr_id = $oprtr_id = $os_id = $device_id = $url_id = $creative_id = 0;

		$stat_hour = sprintf("%02d",date("H", time()-720));
		
        if($stat_hour>=0 && $stat_hour<12){
            $slot = "1";
        } else {
            $slot = "2";
        }
		if(isset($request->submit)){

          $ad_id = $request->campaign_id;
          $advrtsr_id = $request->advertiser_id;
          $start_date = $request->start_date;
          $end_date = $request->end_date;
          $cpc = $request->cpc;
          $drange = $request->drange;
         
echo"<br/> :".$ad_id ;
echo"<br/> :".$advrtsr_id ;
echo"<br/> :".$start_date ;
echo"<br/> :".$end_date ;
echo"<br/> :".$cpc ;
echo"<br/> :".$drange ;

         
 
            $diff=($request->click*0.05);
            $low_range =  ceil($request->click-$diff);
            $top_range = ceil($request->click+$diff);
            echo"Clicks-range-low:".$low_range."<br/>";
            echo"Clicks-range-high:".$low_range."<br/>";
            $diff_cn=($request->imp*0.05);
            $low_range_cn =  ceil($request->imp-$diff_cn);
            $top_range_cn = ceil($request->imp+$diff_cn);
            echo"imp-range-low:".$low_range_cn."<br/>";
            echo"imp-range-high:".$top_range_cn."<br/>";
            

              

            for ($i = 0;$i<$drange;$i++){

                echo $request->start_date. " + ".$i." days";

                $report_date = date('Y-m-d', strtotime($request->start_date. " + ".$i." days"));    
                echo"<br/> report_date:".$report_date;
                $clicks_count = rand($low_range, $top_range);
                $imp_count = rand($low_range_cn,$top_range_cn);
                $spend = 0;

                if(!empty($campaign_data_all)){
                    $campaign_pricing_model = $campaign_data_all['campaign_pricing_model'];
                    $target_bit_type = $campaign_data_all['target_bit_type'];
                    $target_bit_type_value = $campaign_data_all['target_bit_type_value'];
                    

                    if($campaign_pricing_model=='CPM'){
                        if($target_bit_type=='CPM'){
                            $spend = (($imp_count/1000)*$target_bit_type_value);
                        } else if($target_bit_type=='CPC'){

                            if ($cpc>0){
                                $spend = $clicks_count*$cpc;
                            } else {
                                $spend = $clicks_count*$target_bit_type_value;    
                            }
                            
                        }
                    }
                }
                
                
                echo"<br/> Spend:". $spend;
                
                $targetting_key = str_replace('-', '', $report_date).$stat_hour.sprintf("%02d", $slot).sprintf("%05d", $ad_id).sprintf("%03d", $pb_id).sprintf("%05d", $ad_spot_id).sprintf("%02d", $brwsr_id).sprintf("%02d", $oprtr_id).sprintf("%02d", $os_id).sprintf("%02d", $device_id).sprintf("%05d", $url_id).sprintf("%05d", $creative_id).$site_id_over_all_arr[0].$clicks_count.$imp_count;
                
                $ids[] = DB::table('hourly_stat')->insertGetId([
                                        'targetting_key' => $targetting_key,
                                        'ad_id' => $ads_id,
                                        'ad_spot_id' => $ad_spot_id,
                                        'publisher_id' => $pb_id,
                                        'campaign_id' => $ad_id,
                                        'advertiser_id' => $advrtsr_id,
                                        'url_id' => $url_id,
                                        'creativeid' => $creative_id,
                                        
                                        'os_id' => $os_id,
                                        
                                        'device_id'=>$device_id,
                                        
                                        'impression_count'=>$imp_count,
                                        'clicks_count'=>$clicks_count,
                                        
                                        
                                        
                                        'stat_date'=>$report_date,
                                        'stat_hour'=>$stat_hour,
                                        'stat_slot'=>$slot,
                                        
                                        'source'=>$site_id_over_all_arr[0],
                                        'revenue_value'=> $spend,
                                        
                                        'update_datetime'=>date('Y-m-d H:i:s')
                                    ]);
                
            }
            
        }
        return View('admin_add_manual_data', $params);
    }
    
    public function add_manual_data_cpi(Request $request){
        $params = array();
        
        $site_id_over_all_arr = array("com.soccermanagerltd.arena","com.bsense.stockwatch","com.facebeauty.Facemakeupsalon","com.engrows.army.commando.jungle.mission","com.ironwoodstudio.diggyloot","com.StylishPhotoLab.RacingBikePhotoEditor.photoeditor","com.gmail.dayoffgames.picross2","com.ayurvedichomeremedies","com.imaginf46.start.chemistrydictionari","com.gameloft.android.ANMP.GloftSEHM","wallpapers.magic.touch","com.alvina.mynamepics","maps.formcpe.modernhouses","com.yamunashtak.app");

        $ad_id = $request->campaign_id;
	    $advrtsr_id = $request->advertiser_id;
        $report_date = $request->stat_date;
        
        if(!empty($request->cn_cost)){
            $request->cn_cost = $request->cn_cost;
        } else {
            $request->cn_cost = 0;
        }
        
        /*$data_zero_status_obj = DB::select(DB::raw('select id,clicks,install from vola_af_crc where status=0 and date(date)=date(now())  order by id desc limit 1'));
        $data_one_status_obj = DB::select(DB::raw('select id,clicks,install from vola_af_crc where status=1 and date(date)=date(now()) order by id desc limit 1'));
        if(!empty($data_zero_status_obj) && !empty($data_one_status_obj)){
            $request->click=($data_zero_status_obj[0]->clicks-$data_one_status_obj[0]->clicks);
            $request->imp=($data_zero_status_obj[0]->install-$data_one_status_obj[0]->install);
        }else if(!empty($data_zero_status_obj) && empty($data_one_status_obj)){
		
		$request->click=($data_zero_status_obj[0]->clicks);
            $request->imp=($data_zero_status_obj[0]->install);
	} else {
            $request->click = 0;
            $request->imp = 0;
        }*/
        //$site_id = $request->source;
        //echo"<pre>";print_r($data_zero_status_obj);
        //echo"<pre>";print_r($request);
        echo $request->click;
        echo "<br/>".$request->imp;
        //die;
	    $ads_id = $pb_id = $ad_spot_id = $brwsr_id = $oprtr_id = $os_id = $device_id = $url_id = $creative_id = 0;

		$stat_hour = sprintf("%02d",date("H", time()-720));
		
        if($stat_hour>=0 && $stat_hour<12){
            $slot = "1";
        } else {
            $slot = "2";
        }
		if(($request->click>0)||($request->imp>0)){
            $total_clicks = 0;
            $total_cnvrsn = 0;
            
            $diff=($request->click/count($site_id_over_all_arr)*0.1);
            $low_range =  ceil($request->click/count($site_id_over_all_arr)-$diff);
            $top_range = ceil($request->click/count($site_id_over_all_arr)+$diff);
            echo"Clicks-range-low:".$low_range."<br/>";
            echo"Clicks-range-high:".$low_range."<br/>";
            $diff_cn=($request->imp/count($site_id_over_all_arr)*0.1);
            $low_range_cn =  ceil($request->imp/count($site_id_over_all_arr)-$diff_cn);
            $top_range_cn = ceil($request->imp/count($site_id_over_all_arr)+$diff_cn);
            echo"imp-range-low:".$low_range_cn."<br/>";
            echo"imp-range-high:".$top_range_cn."<br/>";
            
            
            /*$diff=($request->click/count($site_id_over_all_arr));
            $low_range =  ceil($request->click/count($site_id_over_all_arr));
            $top_range = ceil($request->click/count($site_id_over_all_arr));
            
            $diff_cn=($request->imp/count($site_id_over_all_arr));
            $low_range_cn = ceil ($request->imp/count($site_id_over_all_arr));
            $top_range_cn = ceil($request->imp/count($site_id_over_all_arr));*/
            
            for ($i = 0;$i<count($site_id_over_all_arr);$i++){  
                
                
                echo $clicks_count = rand($low_range, $top_range);
                //echo ceil($request->click/count($site_id_over_all_arr));die;
                echo $cnvrsn_count = rand($low_range_cn,$top_range_cn);
                /*$total_clicks = $total_clicks+$clicks_count;
                $total_cnvrsn  =   $total_cnvrsn+$cnvrsn_count;*/
                $targetting_key = str_replace('-', '', $report_date).$stat_hour.sprintf("%02d", $slot).sprintf("%05d", $ad_id).sprintf("%03d", $pb_id).sprintf("%05d", $ad_spot_id).sprintf("%02d", $brwsr_id).sprintf("%02d", $oprtr_id).sprintf("%02d", $os_id).sprintf("%02d", $device_id).sprintf("%05d", $url_id).sprintf("%05d", $creative_id).$site_id_over_all_arr[$i].$clicks_count.$cnvrsn_count.time();
                
                $ids[] = DB::table('hourly_stat')->updateOrInsert([
                                        'targetting_key' => $targetting_key,
                                        'ad_id' => $ads_id,
                                        'ad_spot_id' => $ad_spot_id,
                                        'publisher_id' => $pb_id,
                                        'campaign_id' => $ad_id,
                                        'advertiser_id' => $advrtsr_id,
                                        'url_id' => $url_id,
                                        'creativeid' => $creative_id,
                                        
                                        'os_id' => $os_id,
                                        
                                        'device_id'=>$device_id,
                                        
                                        
                                        
                                        'conversions_count'=>$cnvrsn_count,
                                        'clicks_count'=>$clicks_count,
                                        
                                        
                                        
                                        'stat_date'=>$report_date,
                                        'stat_hour'=>$stat_hour,
                                        'stat_slot'=>$slot,
                                        
                                        'source'=>$site_id_over_all_arr[$i],
                                        'revenue_value'=> ($cnvrsn_count*$request->cn_cost),
                                        
                                        'update_datetime'=>date('Y-m-d H:i:s')
                                    ]);
                                    
                               
                                    
                
            }
            
            //status update
            /*if($ids){
                //revenue value
                DB::table('vola_af_crc')
                                          ->where('id', $data_zero_status_obj[0]->id)
                                          ->update([ 'status'=>'1']);
            }*/
            
           //die;
        }
        //echo "data inserted successfully";
        return View('admin_add_manual_data_cpi', $params);
    }




    public function get_hybrid_token(Request $request){
            
       $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://api.hybrid.ai/token',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => 'client_id=63bbf5c47bc72fd99c30f208&client_secret=Os0Br836e4ZoelgWzSMuZHMr52HRx6BWE8PX7yLBShQ6LyeUj5u4nHgqvROtGlBZlCgIzhQ3HoYIjEUTW6c2IunLSV0%3D&grant_type=client_credentials',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/x-www-form-urlencoded'
          ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        echo "<pre>";print_r(json_decode($response));die;
        return $offerDetails;
    }


    public function get_hybrid_data(Request $request){
        

        $hybrid_cam_map=array("63c1154a7bc72f30e8515501"=>"10128");

        //$campaign_data_all = $this->getCampaignDataByCampaignId($ad_id);
        //$campaign_data_all = (array)$campaign_data_all;




        $curl = curl_init();
        $date =  date("Y-m-d");
        $sdate = $date."T00:00:00";
        $edate = $date."T23:59:59";
        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://api.hybrid.ai/v3.0/advertiser/Folder?from=".$sdate."&to=".$edate."&advertiserId=63bbf4434d506e2420cbd1ea",
           //CURLOPT_URL => 'https://api.hybrid.ai/v3.0/advertiser/Folder?from=2023-01-12T00:00:00&to=2023-01-13T23:59:59&advertiserId=63bbf4434d506e2420cbd1ea',  
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'GET',
          CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer glZlThTmhhsjy_Oq7kGc5tmDWyOKV2H7ON0kTrTr3E6K0D71bndxQZ23hOum9cT6gw6gP500HU9K6YwquPoHpPm5gGIIKQMFkU9WamjqHjw8VKILeRaUWKTtstM83Sxcwi3JnhTlfpt29BB0gqYQLWjKTEWYgjyYhbsaJTxOVx8WlVQni9c_bmd_CmV4Oc5J0e9AoCTjWNv5vKCSzKTIYGeXl2fb0rtIwS0whANtvp0_LxICj229IOdp1VCLJ2-vJTMnNJYJALoFas-tyCbCAjv4Pwul6Nw09YbxxCP1MAcfQsWoqvZ3z-taHpKYhEIei-2Upj-ukJXQAx6LwVZPVRX2Jmo'
          ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        //echo "<pre>"; print_r(json_decode($response));die;
        $data = json_decode($response,true);
        //echo "<pre>";print_r($data['Statistic']);die;

            if(count($data['Statistic']) > 0){

            foreach ($data['Statistic'] as $value) {
                    
                    $clicks_count = $value['ClickCount'];
                    
                    $imp_count = $value['ImpressionCount'];
                    $spend = (($imp_count/1000)*1);
                    
                    
                    //echo"<br/> Spend:".$spend;
                    
                   $ads_id = $pb_id = $ad_spot_id = $brwsr_id = $oprtr_id = $os_id = $device_id = $url_id = $creative_id = 0;
                   $slot=  $stat_hour =1;
                    $targetting_key = str_replace('-', '', $date).$stat_hour.sprintf("%02d", $slot).sprintf("%05d", $hybrid_cam_map[$value['FolderId']]).sprintf("%03d", $pb_id).sprintf("%05d", $ad_spot_id).sprintf("%02d", $brwsr_id).sprintf("%02d", $oprtr_id).sprintf("%02d", $os_id).sprintf("%02d", $device_id).sprintf("%05d", $url_id).sprintf("%05d", $creative_id).$value['FolderId'];
                    
                    $ids[] = DB::table('hourly_stat')->insertGetId([
                                            'targetting_key' => $targetting_key,
                                            'ad_id' => 0,
                                            'ad_spot_id' => 0,
                                            'publisher_id' => 0,
                                            'campaign_id' => $hybrid_cam_map[$value['FolderId']],
                                            'advertiser_id' => 1072,
                                            'url_id' => 0,
                                            'creativeid' => 0,
                                            
                                            'os_id' => 0,
                                            
                                            'device_id'=>0,
                                            
                                            
                                            
                                            'impression_count'=>$imp_count,
                                            'clicks_count'=>$clicks_count,
                                            
                                            
                                            
                                            'stat_date'=> $date,
                                            'stat_hour'=>$stat_hour,
                                            'stat_slot'=>$slot,
                                            
                                            'source'=>'',
                                            'revenue_value'=> $spend,
                                            
                                            'update_datetime'=>date('Y-m-d H:i:s')
                                        ]);
                    
                    }

                }
    }

}