<?php 
/**
 * Create cedato supply (html players) for all arb campaigns
 * 
 * @author Janaki
 * 12/22/2017
 */

include_once 'lib/php/include/db.php';

include_once 'lib/php/api/cedato/cedato.php';

$error_msg_string = array();

//get all active demand
function updateDemandInDB(){
    global $error_msg_string;
    $db = ConnectToAdmin();
    
    $obj = new Cedato();
    $obj->getDemandListing();
    //$obj->getDemandDetails(array('demandId'=>1644754999));
    if(!empty($obj->error)){
        $error_msg_string[] = "Error getting demand listing: ".print_r($obj->error, true);
    }else {
        //print_r($obj);
        $all_demand = $obj->_api_response['data'];
        
        //force update on every odd hour to pull updates to existing demand
        if(date('H')%2 == 0){
            //update when the count changes.
            $count_in_db = 0;
            $sql = "SELECT count(*) as c from cedato_demand";
            $res = mysql_query($sql, $db);
            while ($row = mysql_fetch_array($res)){
                $count_in_db  = $row['c'];
            }
            
            if(count($all_demand) === $count_in_db){
                println("Same demand count in db. Nothing to update.");
                return;
            }
        }
        
        foreach ($all_demand as $d){
            $id = $d['vastId'];
            $obj = new Cedato();
            $obj->getDemandDetails(array('demandId'=>$id));
            if(!empty($obj->error)){
                println("Error getting demand details for $id");
            }
            else{
                //print_r($obj->_api_response['data']);
                $name = addslashes($obj->_api_response['data']['demand']['name']);
                $active = $obj->_api_response['data']['demand']['active'];
                $is_mobile_web = $obj->_api_response['data']['demand']['is_mobile_web'];
                $is_mobile_app = $obj->_api_response['data']['demand']['is_mobile_app'];
                $is_desktop = $obj->_api_response['data']['demand']['is_desktop'];
                
                $sql = "INSERT INTO `cedato_demand`(`id`, `name`, `active`, `is_mobile_web`, `is_mobile_app`, `is_desktop`)
                    VALUES ($id, '$name', $active, $is_mobile_web, $is_mobile_app, $is_desktop )
                    ON DUPLICATE KEY UPDATE name='$name', active=$active, is_mobile_web=$is_mobile_web, is_mobile_app=$is_mobile_app, is_desktop=$is_desktop";
                if(!mysql_query($sql, $db)){
                    $error_msg_string[] = " Error adding demand to table: $sql ".mysql_error();
                }
            }
            if($d['active'] == 1){
                $assigned_vasts[] = array('is_active_on_player'=>1,'useDefaultCPM'=>'true','vastId'=>$d['vastId'], 'vast_cpm_on_player'=>null);
            }
        }
    }
}

function getDemand(){
    global $error_msg_string;
    $assigned_vasts = array();
    $premium_vasts = array();
    $db = ConnectToAdmin();
    $sql = "SELECT * FROM `cedato_demand` where active=1 ";
    $res = mysql_query($sql, $db);
    if(mysql_num_rows($res) == 0){
        $error_msg_string[] = "Empty results from cedato_demand";
        return false;
    }
    while ($row = mysql_fetch_array($res)){
        if($row['is_desktop'] == 1){
            //desktop demand
            if($row['premium'] == 1){
                $premium_vasts['desktop'][] = array('is_active_on_player'=>1,'useDefaultCPM'=>'true','vastId'=>$row['id'], 'vast_cpm_on_player'=>null);
            }
            else{
                $assigned_vasts['desktop'][] = array('is_active_on_player'=>1,'useDefaultCPM'=>'true','vastId'=>$row['id'], 'vast_cpm_on_player'=>null);
            }
        }
        if($row['is_mobile_web'] == 1){
            if($row['premium'] == 1){
                $premium_vasts['mobile_web'][] = array('is_active_on_player'=>1,'useDefaultCPM'=>'true','vastId'=>$row['id'], 'vast_cpm_on_player'=>null);
            }
            else{
                $assigned_vasts['mobile_web'][] = array('is_active_on_player'=>1,'useDefaultCPM'=>'true','vastId'=>$row['id'], 'vast_cpm_on_player'=>null);
            }
        }
        if($row['is_mobile_app'] == 1){
            if($row['premium'] == 1){
                $premium_vasts['mobile_app'][] = array('is_active_on_player'=>1,'useDefaultCPM'=>'true','vastId'=>$row['id'], 'vast_cpm_on_player'=>null);
            }
            else{
                $assigned_vasts['mobile_app'][] = array('is_active_on_player'=>1,'useDefaultCPM'=>'true','vastId'=>$row['id'], 'vast_cpm_on_player'=>null);
            }
        }
        
        $assigned_vasts['all_devives'][] = array('is_active_on_player'=>1,'useDefaultCPM'=>'true','vastId'=>$row['id'], 'vast_cpm_on_player'=>null);
    }
    return array("non_premium"=>$assigned_vasts, "premium"=>$premium_vasts);
}

function createCedatoSupplyForArbCampaings(){
    global $error_msg_string;
    $db = ConnectToAdmin();
    
    //get demand to map from the db
    $demand_arr = getDemand();
    $assigned_vasts = $demand_arr['non_premium'];
    $premium_demand = $demand_arr['premium'];
    if(!is_array($assigned_vasts)){
        $error_msg_string[] = "Could not get assigned vasts from the db";
        return false;
    }
    
    //get campaings without existing cedato id
    $sql = "SELECT * FROM `campaign` c, campaign_targeting d where advertiser_id=8144 and status='A' and name not like '%novideo%' and c.id=d.campaign_id  and description not in (SELECT aid FROM `rep_aid_cedato_map`) ";
    $res = mysql_query($sql, $db);
    while ($row = mysql_fetch_array($res)){
        $campaign_id = $row['id'];
        $aid = $row['description'];
        $name = $row['name'];
        $json = $row['json'];
        $targeting = json_decode($json);
        
        $is_300x250 = false;
        //check the creative size
        $sql = "SELECT * from creatives where id in (SELECT creative_id from campaign_creative_link where campaign_id=$campaign_id)";
        $cr_res = mysql_query($sql, $db);
        while ($cr_row = mysql_fetch_array($cr_res)){
            if($cr_row['img_width'] == 300 && $cr_row['img_height'] == 250){
                $is_300x250 = true;
            }
        }
        
        /* 
        if(is_array($targeting->supply_type_targets)){
            if(count($targeting->supply_type_targets)>1){
                $env_tag = "_ALLDEVICES";
            }
            else if($targeting->supply_type_targets[0]=="web"){
                $env_tag = "_DESKTOP";
            }
            else if($targeting->supply_type_targets[0]=="mobile_app"){
                $env_tag = "_MAPP";
            }
            else{
                $env_tag = "_MWEB";
            }
        }
         */
        
        $is_desktop = $is_mobile_web = $is_mobile_app = 0;
        
        if(is_array($targeting->supplies)){
            if(in_array("web", $targeting->supplies) && in_array("mobile", $targeting->supplies) && in_array("app", $targeting->supplies)){
                $env_tag = "_ALLDEVICES";
                $is_desktop = $is_mobile_web = 1;
            }
            elseif(in_array("mobile", $targeting->supplies) && in_array("app", $targeting->supplies)){
                $env_tag = "_MOBILE";
                $is_mobile_web = $is_mobile_app = 1;
            }
            elseif(count($targeting->supplies) > 1){    //web && {mobile|app}
                $env_tag = "_ALLDEVICES";
                $is_desktop = $is_mobile_web = 1;
            }
            else if($targeting->supplies[0] == "web"){
                $env_tag = "_DESKTOP";
                $is_desktop = 1;
            }
            else if($targeting->supplies[0]=="app"){
                $env_tag = "_MAPP";
                $is_mobile_app = 1;
            }
            else{
                $env_tag = "_MWEB";
                $is_mobile_web = 1;
            }
        }
        else{
            $env_tag = "_ALLDEVICES";
            $is_desktop = $is_mobile_web = 1;
        }
        
        /* 
        if(stripos($name, "_US") === false && stripos($name, "_INTL") === false && stripos($name, "_US/CA") === false){
            $geo_tag = "_ALLGEOS"; 
        }
        elseif(stripos($name, "_INTL") !== false){
            $geo_tag = "_INTL";
        }
        else{
            $geo_tag = "_US";
        }
         */
        
        if(is_array($targeting->countries)){
            if(count($targeting->countries) <= 2 && in_array("USA", $targeting->countries)){ //US | US,CA
                $geo_tag = "_US";
            }
            elseif(count($targeting->countries) > 2 && !in_array("USA", $targeting->countries)){    //all but US
                $geo_tag = "_INTL";
            }
            else{
                $geo_tag = "_ALLGEOS";
            }
        }
        else{
            $geo_tag = "_ALLGEOS";
        }
        
        $supply_name = "IBV_C:{$campaign_id}_A:{$aid}{$env_tag}{$geo_tag}";
        
        $video_url = "http://s.leisure.com/1310.mp4";
        
        $input = array(
            'player_name' => $supply_name,
            'is_active' => 1,
            'player_type' => 0,
            'content_url' => $video_url,
            'autoplay' => 1,
            'is_desktop' => $is_desktop,
            'rotate' => 1,
            'rotate_number' => 0,
            'is_mobile_web' => $is_mobile_web,
            'is_mobile_app' => $is_mobile_app,
            'cost_type' => 1,
            'cost_value' => 100,
            'loader_image_url'=> "http://s.leisure.com/1310.jpeg",
            "click_url" => "http://www.movieclip.com/video-details/1310-FAIRY-DUTY-trailer/",
            "isMuted" => true,
            "loop"=>true,
            /* "content_loop"=>true, */
            "content_allow_click" => 1
        );
        
        //print_r($input);
        
        if($env_tag == "_ALLDEVICES"){
            $arr_key = 'all_devives';
        }
        elseif($env_tag == "_DESKTOP"){
            $arr_key = 'desktop';
        }
        elseif($env_tag == "_MWEB"){
            $arr_key = 'mobile_web';
        }
        else{
            $arr_key = 'mobile_app';
        }
                
        
        if($is_300x250 && count($premium_demand[$arr_key])>0){
            //assign premium demand
            $input['assigned_vasts'] = array_merge($premium_demand[$arr_key], $assigned_vasts[$arr_key]);
        }
        else{
            $input['assigned_vasts'] = $assigned_vasts[$arr_key];
        }
        
        //println($name." ====> ".$supply_name ." ====> ".json_encode($targeting->supplies). " ====> " .json_encode($targeting->countries));
        //println(json_encode($input));
        //echo "<hr>";
        //continue;
        
        $cedato_id = create_cedato_supply($aid, $input);
        
        if(!($cedato_id > 0)){
            $error_msg_string[] = "Error creating cedato id for $supply_name";
        }
        else{
            println("$name ====> $supply_name Created successfully: $cedato_id");
        }
        
        if(rand(0,1) == 1){
            sleep(1);
        }
    }
}


function create_cedato_supply($aid, $input){
    global $error_msg_string;
    $db = ConnectToAdmin();
    $obj = new Cedato();
    $obj->createSupply($input);
    if(!empty($obj->error)){
       $error_msg_string[] = "Error creating supply for $aid : ".print_r($obj->error, true);
    }else {
        //print_r($obj->_api_response);
        $cedato_id = $obj->_api_response['data']['player']['playerId'];
        if($cedato_id > 0){
            $name = addslashes($input['player_name']);
            $type = $input['player_type'];
            $sql = "INSERT INTO `rep_aid_cedato_map`(`aid`, `cedato_id`, `name`, `type`) VALUES ($aid, $cedato_id, '$name', '$type')";
            if(!mysql_query($sql, $db)){
                $error_msg_string[] = "Error updating cedato id $sql ".mysql_error();
                echo "Error updating cedato id $sql ".mysql_error();
            }
            return $cedato_id;
        }
    }
    
    return 0;
}

function println ($string_message) {
    isset($_SERVER['SERVER_PROTOCOL']) ? print "$string_message<br />" : print "$string_message\n";
}


//call this function in the cron
//createCedatoSupplyForArbCampaings();
?>