<?php

function login($token)
{
    $username = trim(IMO_USER);
    $password = trim(IMO_PASS);
    //set the directory for the cookie using defined document root var
    $path = DOC_ROOT."/ctemp";
    //build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
    //$path = build_unique_path($path); // this was for my use case

    //login form action url
    $url="https://partner.imonetizeit.com/signin"; 
    $params = array(
        'LoginForm[username]' => $username,
        'LoginForm[password]' => $password,
        'YII_CSRF_TOKEN' => $token,
        'LoginForm[hiddenField]' => '27546a4780e9dd7057cd7ddd3de2b0d6'
    );
    $postinfo = http_build_query($params);

    $cookie_file_path = $path."/cookie.txt";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
    //set the cookie the site has for certain features, this is optional
    // curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
    curl_setopt($ch, CURLOPT_USERAGENT,
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, "https://partner.imonetizeit.com/signin");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
    $login = curl_exec($ch);

    curl_close($ch);

    return $login;
}

function getReqId($page = 1, $date = '', $type = '')
{
    $token = getToken();
    $page = ($page == "") ? 1: $page;
    $today = ($date == "") ? date("Y-m-d"): $date;
    // Prepare the URL and headers
    if ( $type == 'list' ) {
        $url = "https://partner.imonetizeit.com/async/campaignsGet".ucfirst($type);
        $params = array(
            'Filter[vertical]' => 0,
            'Filter[utc]' => '+00:00',
            'Filter[dateFrom]' => $today,
            'Filter[dateTo]' => $today,
            'Filter[id_name]' => '',
            'Filter[pageSize]' > 25,
            'Filter[include_archive]' => 0,
            'Filter[creative]' => 0,
            'Filter[type]' => 0,
            'Filter[offer_type]' => 0,
            'Filter[epu]' => 0,
            'Filter[holds]' => 0,
            'Filter[isproxy]' => 0,
            'Filter[withCountries]' => 0,
            'Filter[force]' => 1,
            'YII_CSRF_TOKEN' => $token
        );
    } else {
        $url = "https://partner.imonetizeit.com/async/statisticsGet";
        $params = array(
            'is_offer' => 0,
            'filter[campaignId]' => 'all',
            'filter[vertical]' => 0,
            'filter[utc]' => '+00:00',
            'filter[dateFrom]' => $today,
            'filter[dateTo]' => $today,
            'filter[groupBy]' => 'total',
            'filter[subId1]' => 1,
            'filter[subId2]' => 0,
            'filter[showGraph]' => 0,
            'filter[include_archive]' => 0,
            'filter[creative]' => 0,
            'filter[type]' => 1,
            'filter[offer_type]' => 0,
            'filter[epu]' => 0,
            'filter[holds]' => 0,
            'filter[isproxy]' => 0,
            'filter[withCountries]' => 0,
            'filter[main][]' => 'campaign_name',
            'filter[force]' => 1,
            'filter[tab]' => 'campaign_name',
            'page' => $page,
            'recalculate' => 1,
            'YII_CSRF_TOKEN' => $token
        );
    }
    
    
    $data = http_build_query($params, '', '&');
    // echo $data;
    return fetch($url, $data, "POST", $token);
}

function getData($reqid, $page = 1, $date = '')
{
    $token = getToken();
    $page = ($page == "") ? 1: $page;
    $today = ($date == "") ? date("Y-m-d"): $date;
    $url = "https://partner.imonetizeit.com/statistics/get";
    $params = array(
        'is_offer' => 0,
        'filter[campaignId]' => 'all',
        'filter[vertical]' => 0,
        'filter[utc]' => '+00:00',
        'filter[dateFrom]' => $today,
        'filter[dateTo]' => $today,
        'filter[groupBy]' => 'total',
        'filter[subId1]' => 1,
        'filter[subId2]' => 0,
        'filter[showGraph]' => 0,
        'filter[include_archive]' => 0,
        'filter[creative]' => 0,
        'filter[type]' => 1,
        'filter[offer_type]' => 0,
        'filter[epu]' => 0,
        'filter[holds]' => 0,
        'filter[isproxy]' => 0,
        'filter[withCountries]' => 0,
        'filter[main][]' => 'campaign_name',
        'filter[force]' => 1,
        'filter[tab]' => 'campaign_name',
        'page' => $page,
        'recalculate' => 1,
        'requestId' => $reqid,
        'YII_CSRF_TOKEN' => $token
    );
    $data = http_build_query($params, '', '&');
    return fetch($url, $data, "POST", $token);
}

function getPayment($reqid, $date = '')
{
    $token = getToken();
    $today = ($date == "") ? date("Y-m-d", strtotime("Yesterday")): $date;
    // echo $today;
    $url = "https://partner.imonetizeit.com/campaign/get/part/1";
    $params = array(
        'Filter[vertical]' => 0,
        'Filter[utc]' => '+00:00',
        'Filter[dateFrom]' => $today,
        'Filter[dateTo]' => $today,
        'Filter[id_name]' => '',
        'Filter[pageSize]' > 25,
        'Filter[include_archive]' => 0,
        'Filter[creative]' => 0,
        'Filter[type]' => 0,
        'Filter[offer_type]' => 0,
        'Filter[epu]' => 0,
        'Filter[holds]' => 0,
        'Filter[isproxy]' => 0,
        'Filter[withCountries]' => 0,
        'Filter[force]' => 1,
        'requestId' => $reqid,
        'YII_CSRF_TOKEN' => $token
    );
    $data = http_build_query($params, '', '&');
    return fetch($url, $data, "GET", $token, $ref = 'https://partner.imonetizeit.com/campaign/list');
}

function getToken(){
    
    $url = "https://partner.imonetizeit.com/signin";
    $ch2 = curl_init($url);
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
    // get headers too with this line
    curl_setopt($ch2, CURLOPT_HEADER, 0);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    // curl_setopt($ch2, CURLOPT_COOKIEJAR, $cookie_file_path);
    // curl_setopt($ch, CURLOPT_COOKIE, $cookie_file_path);
    curl_setopt($ch2, CURLOPT_REFERER, 'https://partner.imonetizeit.com/signin');
    curl_setopt($ch2, CURLOPT_USERAGENT,
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36");
    curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, 20);
    curl_setopt($ch2,CURLOPT_VERBOSE,1);
    $result = curl_exec($ch2);
    
    preg_match_all('/value="(.*)" name="YII_CSRF_TOKEN"/Usi', $result, $matches);
    // $fh = fopen('token.txt', 'w');
    // fwrite($fh, $matches[1][0]);
    // fclose($fh);
    return $matches[1][0];
}

function fetch($url, $token, $data = "", $type = "GET", $ref = '')
{
    
    // Execute via CURL
    $response = null;
    if(extension_loaded('curl')) {
        // $ch = curl_init();
        //username and password of account
        $username = trim(IMO_USER);
        $password = trim(IMO_PASS);

        //set the directory for the cookie using defined document root var
        $path = DOC_ROOT."/ctemp";
        //build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
        //$path = build_unique_path($path); // this was for my use case

        //login form action url
        $urlsign="https://partner.imonetizeit.com/signin"; 
        $postinfo = "LoginForm[username]=".$username."&LoginForm[password]=".$password."&YII_CSRF_TOKEN=".$token."&LoginForm[hiddenField]=27546a4780e9dd7057cd7ddd3de2b0d6&rtc_ip=&yt0=Log+in";

        $cookie_file_path = $path."/cookie.txt";

        $ch = curl_init();
        // $headers = array(
        //     'Accept: application/x-www-form-urlencoded',
        //     'Set-Cookie: _u_hash=uo%2BcJfK1VBNGKPfABNqKRIncOy9eXzuRniGXmTggBX5aRMJpFEAtYEd%2FbQNAmLRYuqkBw1h%2FMWiXGncfF88kH2sjEOtiiRRBfrcedApuvPRAEhl2ZEoTs2YvMk%2BVg2GPH6Hy7jSvaHEVFTkzwAjCdtsZ1fHoUPjyujVRWiAN8lEboR4axRWYqMEvHH6ROp0GS3uOVKWeHxT%2FF6e6Wgf60tYAx82cRfK5ZVfIbbWtgFhE5iflTwzfeKQBwVOcPZLn; expires=Wed, 19-Aug-2022 02:26:31 GMT; Max-Age=63072000; path=/; HttpOnly',
        //     'Cookie: _uudtl=6c7ab40d9854c19f4201828ccb550650; _gcl_au=1.1.2063259659.1595682284; _ga=GA1.2.1664565309.1595682284; _fbp=fb.1.1595682284423.727305908; SL_C_23361dd035530_VID=sN98lOeFYKM; SL_C_23361dd035530_KEY=5355d7c0a4f4a85e3328520e52dbfae1e6e3eedd; intercom_status=hided; PHPSESSID=jj73gmcl47cuqip19fa1fqino1; YII_CSRF_TOKEN='.$token.'; _r_i=; _gid=GA1.2.774219806.1597546863; _uudtl_st=1; intercom-session-kw36b1vg=WDlhekdlTk52L1lDZTd5ZDlUcjJtbDhkZCszU0VsOFJzd2NaUG5UdUdVbFQxZjdlb2JBQjNyN3FBSHQ0YVZZOS0taWhpY3duYU5XWDFpT1ljaHNEbzRWUT09--68d5df8f18f654b828944e54aaaca845190c02dc; _dc_gtm_UA-116119154-1=1'
        // );
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // curl_setopt($ch, CURLOPT_HEADER, true);
        // // curl_setopt($ch, CURLOPT_NOBODY, false);
        // curl_setopt($ch, CURLOPT_URL, $urlsign);
        // // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        // curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
        // //set the cookie the site has for certain features, this is optional
        // // curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
        // curl_setopt($ch, CURLOPT_USERAGENT,
        //     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36");
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // // curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        // curl_setopt($ch, CURLOPT_REFERER, 'https://partner.imonetizeit.com/signin');

        // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
        // $login = curl_exec($ch);
        // echo $login;

        $headers = array(
            'Accept: application/json',
            'Cookie: PHPSESSID=stbvlfdalfh66nc6af17jub2i7; YII_CSRF_TOKEN='.$token.'; _r_i=; _gcl_au=1.1.1988767741.1597661964; _ga=GA1.2.1244719170.1597661964; _gid=GA1.2.392994710.1597661964; _fbp=fb.1.1597661964470.1845657912; _uudtl=6c7ab40d9854c19f4201828ccb550650; _uudtl=6c7ab40d9854c19f4201828ccb550650; _uudtl_st=1; SL_C_23361dd035530_KEY=5355d7c0a4f4a85e3328520e52dbfae1e6e3eedd; intercom-session-kw36b1vg=OENSNExOdUpEMFBKa3ZzTjJXeXdOc2tYdHJsaDFVQTd6RVpLLyt3SjA0K2NlL1RDU3NYbFQzNlk3YUJoajU5eS0tb1I4REgyeGNjTU5mS3U1WGVvZG5zZz09--3367acf772b4bc6244b81d08f5420f5f5a19960f; _u_hash=3x2K80N8wOdLHv5o%2BG8Oo0FbiP1EEnGSO0dG4NSSDuLt4EX6IiADNAmyF55Ydt%2BeJ507qTOKOZ8Jum7uKfd7Rh9nwjonWChbLNbet2j8yBuUMFRzHTDp9VVEaCpY%2F%2BlyHGuNamNiNVkjkhcPAiLaDXdmNXjdZckqpuDUE0r2hLHH8nfuVAZrlmyJgqg2w8CsWqR9meinuc055rwiiYmOzlOQ6DMQ%2Boq%2BueRftI%2FTHFNA%2BgajMmUpEr2VxExNJemT'
        );
        $reff = ($ref != "") ? $ref: 'https://partner.imonetizeit.com/statistics/campaigns'; 
        $urlc = ( $type == 'POST' ) ? $url: $url.'?'.$data;
        // echo $urlc;
        curl_setopt($ch, CURLOPT_URL, $urlc);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
        // curl_setopt($ch, CURLOPT_COOKIE, $cookie_file_path);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_USERAGENT,
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36");
        curl_setopt($ch, CURLOPT_REFERER, $reff);
        if( $type == "POST" ){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $response = curl_exec($ch);

        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        $body = substr($response, $headerSize);
        $errorNumber = curl_errno($ch);
        $errorMessage = curl_error($ch);
        if($errorNumber > 0)
        {
            throw new Exception('Method failed: : ' . $errorMessage);
        }
        curl_close($ch);
    } else {
        throw new Exception('CURL library not loaded!');
    }

    // Try and cadge the results into a half-decent array
    $results = (isJson($body)) ? json_decode($body, 1): $body;
    // throw new Exception('Server error on "' . $url . '": ' . $errorMessage);
    // print_r($response);
    if($results !== null) {
        // Cache & return results
        return $results;
    } else {
        throw new Exception('Server error on "' . $url . '": ' . $response);
    }
}

function addPerf($data, $network)
{
    print_r($data);
    
    // $today = ($date == "") ? date("Y-m-d"): $date;
    
    // preg_match('/<a(.+)>(.*)<\/a>/Us', $data[1], $nm);
    if( $data['smartlink'] != "Unknown" ) {
        $data['payouts'] = ($data['payouts'] == "") ? 0: $data['payouts'];
        # make hash code
        $hash = md5($data['date'].$data['smartlink'].$data['smartlink_id']);
        echo $hash;
        // check if hash exist 
        $cr = ($data['payouts'] != 0 )? "1/".ceil($data['clicks']/$data['payouts']): 0;
        if(false !== hashExist($hash, $data['date'])) {
            echo "<br>Exist";
            Db::update(array(
                'table' => 'link_report',
                'where' => array(
                    'hash' => $hash,
                    'date' => $data['date'],
                ),
                'key' => array(
                    'hits' => $data['visits'],
                    'uniques' => $data['unigue'],
                    'clicks' => $data['clicks'],
                    'conversions' => $data['leads'],
                    'cr' => "{$cr}",
                    'earnings' => $data['payouts']
                )
            ));
        } else {
            echo "<br>Not Exist";
            $q = Db::insert(array(
                'table' => 'link_report',
                'key' => array(
                    'date' => $data['date'],
                    'name' => $data['smartlink'],
                    'sub1' => $data['smartlink'],
                    'hits' => $data['visits'],
                    'uniques' => $data['unigue'],
                    'clicks' => $data['clicks'],
                    'conversions' => $data['leads'],
                    'cr' => "{$cr}",
                    'earnings' => $data['payouts'],
                    'hash' => $hash,
                    'network' => $network
                )
            ));

            var_dump($q);
        }
    }
}



function hashExist($hash, $date)
{
    $q = Db::result("SELECT `id` FROM `link_report` WHERE `hash` = '{$hash}' AND `date` LIKE '%{$date}%' ");
    $n = Db::$num_rows;

    if( $n > 0 ) {
        return true;
    } else {
        return false;
    }
}

function isJson($string) {
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}


function addPayment($data, $date = '')
{
    // print_r($data);
       
    $today = ($date == "") ? date("Y-m-d", strtotime("Yesterday")): $date;
    // preg_match('/<a(.+)>(.*)<\/a>/Us', $data[1], $nm);

    # make hash code
    // $hash = md5($date.$nm[2].$data[2].$data[3]);
    if( $data['smartlink'] != "Unknown" ) {
        $q = Db::insert(array(
            'table' => 'payment',
            'key' => array(
                'date' => $today,
                'name' => $data['smartlink'],
                'conversions' => $data['leads'],
                'earning' => $data['payouts']
            )
        ));
    }
    
}

function APIFetch($path, $token, $data, $type) {
    $url = "https://api.imonetizeit.com/v1".$path;
    $headers = array(
        'Accept: application/json',
        'Authorization: Bearer '.$token
    );

    $urlc = ( $type == 'POST' ) ? $url: $url.'?'.$data;
    // echo $urlc;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $urlc);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    // curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    
    if( $type == "POST" ){
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $response = curl_exec($ch);
    curl_close($ch);

    // Try and cadge the results into a half-decent array
    $results = (isJson($response)) ? json_decode($response, 1): $response;
    if($results !== null) {
        return $results;
    } else {
        throw new Exception('Server error on "' . $url . '": ' . $response);
    }
}

function authToken($client_id, $api_key) {
    $url = "https://api.imonetizeit.com/v1/auth/session";
    $headers = array(
        'Accept: application/json'
    );
    $data = array(
        'client_id' => $client_id,
        'api_key' => $api_key
    );
    $data = http_build_query($data);
    // echo $urlc;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    // curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($ch);
    curl_close($ch);

    // Try and cadge the results into a half-decent array
    $results = (isJson($response)) ? json_decode($response, 1): $response;
    if($results !== null) {
        return $results;
    } else {
        throw new Exception('Server error on "' . $url . '": ' . $response);
    }
}

function topEarning($date = '') {
    $date = ($date != "") ? $date: date("Y-m-d");
    $q = Db::result("SELECT `name` FROM `link_report` WHERE `date` = '{$date}' ORDER BY `earnings` DESC ");
    // print_r($q);
    if ( !isset($q['error']) ) {
        return $q[0]->name;
    } else {
        return "";
    }
}
