<?php
defined('BASEPATH') or exit('Not allowed direct access');
class Api extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('publisher');
$this->load->library('encrypt');
}

public function index(){

if(!empty($this->input->post('api_key')) && !empty($this->input->post('api_url'))){
    $this->getApiOffer($this->input->post());
}
if(!empty($this->input->post('dapi_key')) && !empty($this->input->post('dapi_url'))){
    if($this->input->post('dapi_url')==1){
    $this->gettrackierOffer($this->input->post('dapi_key'));
    }
    if($this->input->post('dapi_url')==2){
    $this->get18Offer($this->input->post('dapi_key'));
    }    
    if($this->input->post('dapi_url')==3){
    $this->getAffiseOffer($this->input->post('dapi_key'),$this->input->post('dapi_url'));
    }
    if($this->input->post('dapi_url')==4){
    $this->getHasOffer($this->input->post('dapi_key'),$this->input->post('dapi_url'));
    }
}
$this->load->view('publisher/pubapi');
}
public function Offer(){
$this->encrypt->encode('1');    
$API_KEY=$this->input->get('apiKey');    
if($API_KEY){
$enc=$this->input->get('apiKey');
$dec=$this->encrypt->decode($enc);    
$pullDown=$this->getCOffers('9');
$json=json_encode($pullDown);
print $json;
}
}


function getApiOffer($url){
$title=$url['offer_title'];
$desc=$url['offer_desc'];
$pre=$url['offer_pre'];
$track=$url['offer_track'];
$type=$url['offer_paytype'];
$pay=$url['offer_pay'];
$category=$url['offer_category'];
$note=$url['offer_note'];
$cap=$url['offer_cap'];
$expiry=$url['offer_expiry'];
$ofrids=$url['offer_id'];
$ocurrency=$url['offer_curr'];
$key=$url['api_key'];
$url=$url['api_url'];
$ch = curl_init();
$ul=$url."=".$key;
curl_setopt($ch, CURLOPT_URL, $ul);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
if(json_last_error()!==JSON_ERROR_NONE){
	throw new RuntimeException(
		'API response not well-formed (json error code: '.json_last_error().')'
	);
}

if(isset($response['success']) && $response['success']==1){
$data=$response['data']['campaigns'];
$count=0;
foreach($data as $pulled){
    if($count==0){
    $name=$pulled[$title];
    $desc=$pulled[$desc];
    if($pulled[$ocurrency]=='INR'){
    $currency='₹';    
    }else{
    $currency='$';    
    }
    //$currency=$pulled['currency'];
    $preview=$pulled[$pre];
    $tracking_link=$pulled[$track];
    $paytype=$pulled[$type];
    $payout=!empty($pulled[$pay])?$pulled[$pay]:'0';
    $count++;
	$currentdate=date("Y-m-d");
	$mnth=date("m",strtotime("+1 month",strtotime($currentdate)));
	$dayy=date("d",strtotime("+1 day",strtotime($currentdate)));
	$yr=date("Y");
	if($paytype=="cpa"){
	$revenue_type="cpa_flat";
	$revenue_conver_type="RPCN";
	$payout_type="cpa_flat";
	$payout_conver_type="CPCN";
	}elseif($paytype=="cps"){
	$revenue_type="cps";
	$revenue_conver_type="RPS";
	$payout_type="cpa_flat";
	$payout_conver_type="CPS";	
	}elseif($paytype=="cpl"){
	$revenue_type="cpl";
	$revenue_conver_type="RPL";
	$payout_type="cpl";
	$payout_conver_type="CPL";
	}
	$revenue_value=$payout;
	$payperc=.3*$payout;
	$payout_value=$payout-$payperc;
	$ofrid=$pulled[$ofrids];
    $data_arr=array("aname"=>$name,"desc"=>$desc,"purl"=>$preview,"status"=>'active',
					"currency"=>$currency,"ourl"=>$tracking_link,"cat"=>0,"clurl"=>"","ctr"=>"server","om"=>$mnth,"od"=>$dayy,"oy"=>$yr,'rev_value'=>$revenue_value,'rev_type'=>$revenue_type,'rev_conversion_type'=>$revenue_conver_type,'pay_value'=>$payout,'pay_type'=>$paytype,'pay_conversion_type'=>$payout_conver_type);	
    $id=$this->AddNewOffer($data_arr);
	$cid=2;
    $this->AddNewRevenue($id,$cid,$data_arr,$ofrid);
    }
    $count++;
}

}else{
	print 'API call failed'.(isset($response['errorMessage'])?' ('.$response['errorMessage'].')':'').'';
	print PHP_EOL;
	print 'Errors: <pre>'.print_r($response['errors'], true).'';
	print PHP_EOL;
}
}


function gettrackierOffer($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.trackier.com/v2/publisher/campaigns?apiKey='.$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
if(json_last_error()!==JSON_ERROR_NONE){
	throw new RuntimeException(
		'API response not well-formed (json error code: '.json_last_error().')'
	);
}

if(isset($response['success']) && $response['success']==1){
$data=$response['data']['campaigns'];
$count=0;

foreach($data as $pulled){
    if($count==0){
    $ofrid=$pulled['id'];    
    $name=$pulled['title'];
    $desc=$pulled['description'];
    if($pulled['currency']=='INR'){
    $currency='₹';    
    }else{
    $currency='$';    
    }
    //$currency=$pulled['currency'];
    $preview=$pulled['preview_url'];
    $tracking_link=$pulled['tracking_link'];
    $paytype=$pulled['model'];
    $payout=$pulled['payouts'][0]['payout'];
    $count++;
	$currentdate=date("Y-m-d");
	$mnth=date("m",strtotime("+1 month",strtotime($currentdate)));
	$dayy=date("d",strtotime("+1 day",strtotime($currentdate)));
	$yr=date("Y");
	if($paytype=="cpa"){
	$revenue_type="cpa_flat";
	$revenue_conver_type="RPCN";
	$payout_type="cpa_flat";
	$payout_conver_type="CPCN";
	}elseif($paytype=="cps"){
	$revenue_type="cps";
	$revenue_conver_type="RPS";
	$payout_type="cpa_flat";
	$payout_conver_type="CPS";	
	}elseif($paytype=="cpl"){
	$revenue_type="cpl";
	$revenue_conver_type="RPL";
	$payout_type="cpl";
	$payout_conver_type="CPL";
	}
	$revenue_value=$payout;
	$payperc=.3*$payout;
	$payout_value=$payout-$payperc;
    $data_arr=array("aname"=>$name,"desc"=>$desc,"purl"=>$preview,"status"=>'active',
					"currency"=>$currency,"ourl"=>$tracking_link,"cat"=>0,"clurl"=>"","ctr"=>"server","om"=>$mnth,"od"=>$dayy,"oy"=>$yr,'rev_value'=>$revenue_value,'rev_type'=>$revenue_type,'rev_conversion_type'=>$revenue_conver_type,'pay_value'=>$payout,'pay_type'=>$paytype,'pay_conversion_type'=>$payout_conver_type);	
    $id=$this->AddNewOffer($data_arr);
	$cid=2;
    $this->AddNewRevenue($id,$cid,$data_arr,$ofrid);
    
    }
    $count++;
}

}else{
	print 'API call failed'.(isset($response['errorMessage'])?' ('.$response['errorMessage'].')':'').'';
	print PHP_EOL;
	print 'Errors: <pre>'.print_r($response['errors'], true).'';
	print PHP_EOL;
}
}

public function get18Offer($url){
    
// for advertiser url  https://api.offer18.com/api/m/offers    
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.offer18.com/api/af/offers?key='.$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
if(json_last_error()!==JSON_ERROR_NONE){
	throw new RuntimeException(
		'API response not well-formed (json error code: '.json_last_error().')'
	);
}

if(isset($response['response']) && $response['response']==200){
$data=$response['data'];
$count=0;

foreach($data as $pulled){
    if($count==0){
    $ofrid=$pulled['id'];    
    $name=$pulled['name'];
    $desc=!empty($pulled['description'])?$pulled['description']:'NA';
    if($pulled['currency']=='INR'){
    $currency='₹';    
    }else{
    $currency='$';    
    }
    //$currency=$pulled['currency'];
    $preview=$pulled['preview_url'];
    $tracking_link=$pulled['click_url'];
    $paytype=$pulled['model'];
    $payout=$pulled['price'];
    $count++;
	$currentdate=date("Y-m-d");
	$mnth=date("m",strtotime("+1 month",strtotime($currentdate)));
	$dayy=date("d",strtotime("+1 day",strtotime($currentdate)));
	$yr=date("Y");
	if($paytype=="cpa"){
	$revenue_type="cpa_flat";
	$revenue_conver_type="RPCN";
	$payout_type="cpa_flat";
	$payout_conver_type="CPCN";
	}elseif($paytype=="cps"){
	$revenue_type="cps";
	$revenue_conver_type="RPS";
	$payout_type="cpa_flat";
	$payout_conver_type="CPS";	
	}elseif($paytype=="cpl"){
	$revenue_type="cpl";
	$revenue_conver_type="RPL";
	$payout_type="cpl";
	$payout_conver_type="CPL";
	}
	$revenue_value=$payout;
	$payperc=.3*$payout;
	$payout_value=$payout-$payperc;
    $data_arr=array("aname"=>$name,"desc"=>$desc,"purl"=>$preview,"status"=>'active',
					"currency"=>$currency,"ourl"=>$tracking_link,"cat"=>0,"clurl"=>"","ctr"=>"server","om"=>$mnth,"od"=>$dayy,"oy"=>$yr,'rev_value'=>$revenue_value,'rev_type'=>$revenue_type,'rev_conversion_type'=>$revenue_conver_type,'pay_value'=>$payout,'pay_type'=>$paytype,'pay_conversion_type'=>$payout_conver_type);	
    $id=$this->AddNewOffer($data_arr);
	$cid=2;
    $this->AddNewRevenue($id,$cid,$data_arr,$ofrid);
    }
    $count++;
}

}else{
	print 'API call failed'.(isset($response)?' ('.$response.')':'').'';
	print PHP_EOL;
	print 'Errors: <pre>'.print_r($response, true).'';
	print PHP_EOL;
}
}

public function getAffiseOffer($url,$domain){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $domain.$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
if(json_last_error()!==JSON_ERROR_NONE){
	throw new RuntimeException(
		'API response not well-formed (json error code: '.json_last_error().')'
	);
}

if(isset($response['status']) && $response['status']==1){
$data=$response['data']['offers'];
$count=0;

foreach($data as $pulled){
    if($count==0){
    $ofrid=$pulled['id'];    
    $name=$pulled['title'];
    $desc=!empty($pulled['description'])?$pulled['description']:'NA';
    if(strtoupper($pulled['payments'][0]['currency'])=='INR'){
    $currency='₹';    
    }else{
    $currency='$';    
    }
    //$currency=$pulled['currency'];
    $preview=$pulled['preview_url'];
    $tracking_link=$pulled['trafficback_url'];
    $paytype='NA';
    $payout=$pulled['payments'][0]['revenue'];
    $count++;
	$currentdate=date("Y-m-d");
	$mnth=date("m",strtotime("+1 month",strtotime($currentdate)));
	$dayy=date("d",strtotime("+1 day",strtotime($currentdate)));
	$yr=date("Y");
	if($paytype=="cpa"){
	$revenue_type="cpa_flat";
	$revenue_conver_type="RPCN";
	$payout_type="cpa_flat";
	$payout_conver_type="CPCN";
	}elseif($paytype=="cps"){
	$revenue_type="cps";
	$revenue_conver_type="RPS";
	$payout_type="cpa_flat";
	$payout_conver_type="CPS";	
	}elseif($paytype=="cpl"){
	$revenue_type="cpl";
	$revenue_conver_type="RPL";
	$payout_type="cpl";
	$payout_conver_type="CPL";
	}
	$revenue_value=$payout;
	$payperc=.3*$payout;
	$payout_value=$payout-$payperc;
    $data_arr=array("aname"=>$name,"desc"=>$desc,"purl"=>$preview,"status"=>'active',
					"currency"=>$currency,"ourl"=>$tracking_link,"cat"=>0,"clurl"=>"","ctr"=>"server","om"=>$mnth,"od"=>$dayy,"oy"=>$yr,'rev_value'=>$revenue_value,'rev_type'=>$revenue_type,'rev_conversion_type'=>$revenue_conver_type,'pay_value'=>$payout,'pay_type'=>$paytype,'pay_conversion_type'=>$payout_conver_type);	
    $id=$this->AddNewOffer($data_arr);
	$cid=2;
    $this->AddNewRevenue($id,$cid,$data_arr,$ofrid);
    }
    $count++;
}

}else{
	print 'API call failed'.(isset($response['errorMessage'])?' ('.$response['errorMessage'].')':'').'';
	print PHP_EOL;
	print 'Errors: <pre>'.print_r($response['errors'], true).'';
	print PHP_EOL;
}
}

public function getHasOffer($url,$domain){
$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, 'https://abc.api.hasoffers.com/Apiv3/json?NetworkToken=xyz&Target=Offer&Method=findAll&fields[]=offer_url&fields[]=max_payout&fields[]=expiration_date&fields[]=email_instructions&fields[]=description&fields[]=currency&fields[]=require_approval&fields[]=name&fields[]=id&filters[status]=active&sort[expiration_date]=desc');
curl_setopt($ch, CURLOPT_URL, $domain.$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

// Decode the response into a PHP associative array
$response = json_decode($response, true);

// Make sure that there wasn't a problem decoding the repsonse
if(json_last_error()!==JSON_ERROR_NONE){
	throw new RuntimeException(
		'API response not well-formed (json error code: '.json_last_error().')'
	);
}


if(isset($response['status']) && $response['status']==1){
$data=$response['data']['data'];
$count=0;

foreach($data as $pulled){
    if($count==0){
    $ofrid=$pulled['id'];    
    $name=$pulled['title'];
    $desc=!empty($pulled['description'])?$pulled['description']:'NA';
    if(strtoupper($pulled['currency'])=='INR'){
    $currency='₹';    
    }else{
    $currency='$';    
    }
    $currency=$pulled['currency'];
    $preview=$pulled['preview_url'];
    $tracking_link=$pulled['tracking_link'];
    $paytype=$pulled['model'];
    $payout=$pulled['revenue'];
    $count++;
	$currentdate=date("Y-m-d");
	$mnth=date("m",strtotime("+1 month",strtotime($currentdate)));
	$dayy=date("d",strtotime("+1 day",strtotime($currentdate)));
	$yr=date("Y");
	if($paytype=="cpa"){
	$revenue_type="cpa_flat";
	$revenue_conver_type="RPCN";
	$payout_type="cpa_flat";
	$payout_conver_type="CPCN";
	}elseif($paytype=="cps"){
	$revenue_type="cps";
	$revenue_conver_type="RPS";
	$payout_type="cpa_flat";
	$payout_conver_type="CPS";	
	}elseif($paytype=="cpl"){
	$revenue_type="cpl";
	$revenue_conver_type="RPL";
	$payout_type="cpl";
	$payout_conver_type="CPL";
	}
	$revenue_value=$payout;
	$payperc=.3*$payout;
	$payout_value=$payout-$payperc;
    $data_arr=array("aname"=>$name,"desc"=>$desc,"purl"=>$preview,"status"=>'active',
					"currency"=>$currency,"ourl"=>$tracking_link,"cat"=>0,"clurl"=>"","ctr"=>"server","om"=>$mnth,"od"=>$dayy,"oy"=>$yr,'rev_value'=>$revenue_value,'rev_type'=>$revenue_type,'rev_conversion_type'=>$revenue_conver_type,'pay_value'=>$payout,'pay_type'=>$paytype,'pay_conversion_type'=>$payout_conver_type);	
    $id=$this->AddNewOffer($data_arr);
	$cid=2;
    $this->AddNewRevenue($id,$cid,$data_arr,$ofrid);
    }
    $count++;
}

}else{
	print 'API call failed'.(isset($response['errorMessage'])?' ('.$response['errorMessage'].')':'').'';
	print PHP_EOL;
	print 'Errors: <pre>'.print_r($response['errors'], true).'';
	print PHP_EOL;
}
}

function getCOffers($id){
$alloffer=array();
$cond=array('aff_id'=>$id,'status'=>'1');
$this->db->order_by('offer_id','desc');
$qoffer=$this->db->get_where('htbl_aff_ofr_status',$cond);
if($qoffer->num_rows()>0)
{
	foreach($qoffer->result_array() as $ofval)
	{
	$offer_id=$ofval['offer_id'];
	$this->db->select("*");
	$this->db->from('hoffer_detail');
	$this->db->where('ofr_id',$offer_id);
	$this->db->join('htbl_category', 'htbl_category.cat_id = hoffer_detail.ofr_cat','left');
	$this->db->join('htbl_revenue', 'htbl_revenue.rev_refid = hoffer_detail.ofr_id','left');
	$this->db->join('htbl_payout', 'htbl_payout.pay_refid = hoffer_detail.ofr_id','left');
	$this->db->order_by('hoffer_detail.ofr_id','desc');
	$qgetoffer=$this->db->get();	
	if($qgetoffer->num_rows()>0){
        foreach($qgetoffer->result_array() as $ofrval){
        $alloffer[]=array('id'=>$ofrval['ofr_id'],'name'=>$ofrval['ofr_name'],'description'=>str_replace(array("\r\n","\r"),"",strip_tags($ofrval['ofr_desc'])),'url'=>$ofrval['ofr_url'],'preview_url'=>$ofrval['ofr_purl'],'tracking_url'=>strip_tags($ofrval['ofr_track_url']),'currency'=>$ofrval['ofr_currency'],'payout_type'=>$ofrval['pay_conversion_type'],'payout'=>$ofrval['pay_value']);
        }
	}
	}
}
return $alloffer;	
}

    public function AddNewOffer($request)
    {
        
        $adv_id="500001";
        $name=$request['aname'];
        $desc=$request['desc'];
        $priview_url=$request['purl'];
        $offer_url=$request['ourl'];
        $offer_cat=$request['cat'];
        $server_click_url=$request['clurl'];
        $tracking=$request['ctr'];
        if($tracking=='iframe'){
        $tracking="https_img";
        }
        $status=$request['status'];
        $currency=$request['currency'];
        $expirym=$request['om'];
        $expiryd=$request['od'];
        $expiryy=$request['oy'];
        $note=$request['onote'];
        $refid=$request['refid'];
        $expiry=$expiryy."-".$expirym."-".$expiryd;
	    $isgoal=$request['show_goal'];	
	    $goalname=($isgoal==1)?$request['show_goal2']:'NA';	
	    $goaltype=($isgoal==1)?$request['show_goal3']:'NA';	
	    $goalcustz_value=($isgoal==1)?$request['show_goal4']:'NA';	
        $data_value=array('ofr_cid'=>$adv_id,'ofr_name'=>$name,
                            'ofr_desc'=>$desc,'ofr_purl'=>$priview_url,
                            'ofr_url'=>$offer_url,'ofr_serverclick'=>$server_click_url,
                            'ofr_track'=>$tracking,'ofr_status'=>$status,'ofr_expiry'=>$expiry,
                            'ofr_note'=>$note,'ofr_refid'=>$refid,'ofr_cat'=>$offer_cat,'ofr_currency'=>$currency);


                            $this->db->insert('hoffer_detail',$data_value);
							$oid=$this->db->insert_id();
							$dataq=$this->db->select('ofr_track')
								     ->from('hoffer_detail')
									 ->where('ofr_id',$oid)
									 ->get();		
							$getrow=$dataq->row();
							if($getrow->ofr_track=='server')
							{
								$ofr_track_url="https://".$_SERVER['HTTP_HOST']."/trackcn/?offer_id=".$oid."&transaction_id=TRANSACTION_ID";
								
							}
							else
							{
								if($request['ctr']=='iframe'){
								$ofr_track_url="&lt;iframe src='https://".$_SERVER['HTTP_HOST']."/trackcn/?offer_id=".$oid."' scrolling='no' frameborder='0' height='1' width='1'&gt;&lt;/iframe&gt;";
								}else{
								$ofr_track_url="&lt;img src='https://".$_SERVER['HTTP_HOST']."/trackcn/?offer_id=".$oid."' height='1' width='1'&gt;";
								}
							}			
							$this->db->set('ofr_track_url',$ofr_track_url)					
							->where('ofr_id',$oid)				
							->update('hoffer_detail');
							return $oid;
							


    }

	public function AddNewRevenue($id,$cid,$request,$ofrid)
    {
        
        $data_value=array('rev_type'=>$request['rev_type'],'rev_value'=>$request['rev_value'],
                            'rev_conversion_type'=>$request['rev_conversion_type'],'rev_refid'=>$id);
        $dt=date('Y-m-d H:i:s');
        $data_value_import=array('offer_id'=>$id,'cid'=>$cid,'status'=>'1','timedate'=>$dt,'client_offer_id'=>$ofrid);                    
        $data_value_pay=array('pay_type'=>$request['pay_type'],'pay_value'=>$request['pay_value'],
                            'pay_conversion_type'=>$request['pay_conversion_type'],'pay_refid'=>$id,'is_goal'=>'0',
			    'goal_name'=>'NA','goal_type'=>'0','goal_cust_id'=>'NA');
		$data_value_setting=array('set_private'=>'1','set_req_approval'=>'1','set_refid'=>$id);							
		$data_value_track=array('trk_default_url'=>$track_hostname,'trk_ssl'=>$track_enforce_secure_tracking_link,
                            'trk_redirect_offer_id'=>$track_redirect_offer_id,'trk_secondary_offer'=>$track_secondary_offer_type,
							'trk_scondary_offer_url'=>$track_secondary_offer_id,'trk_sessionlife_hours'=>$track_session_hours,
                            'trk_impression_hours'=>$track_session_impression_hours,'trk_custom_var'=>$track_show_custom_variables,'trk_direct_link'=>$track_allow_direct_links,
							'trk_deep_link'=>$track_allow_website_links,'trk_copy_parameter'=>$track_website_links_copy_static_params,
							'trk_approve_conv'=>$track_approve_conversions,'trk_refid'=>$id,'set_session_on_impression'=>$track_set_session_on_impression);
                            $this->db->insert('htbl_revenue',$data_value);
                            $this->db->insert('htbl_payout',$data_value_pay);
                            $this->db->insert('htbl_offer_setting',$data_value_setting);
                            $this->getset->setAffaccess($cid,$id);
                            $ofr_id=$id;
                            $aff_id=$cid;
                            $gen_url="";
                            $gen_url=$_SERVER['HTTP_ORIGIN']."/track/?aff_id=$aff_id&offer_id=$ofr_id$trck_url";
                            if(!empty($gen_url)){
                            $updaterecord=$this->getset->setRecordt($aff_id,$ofr_id,$gen_url);
                            }
                            $this->db->insert('htbl_tracking',$data_value_track);
                            $this->db->insert('tbl_offer_import',$data_value_import);
							
    }
}



//$encs=$this->encrypt->encode('1');
