<?php

require_once 'vendor/autoload.php';

$client = new Google_Client();
$client->setApplicationName('Sign In with Google Ads Account');
$client->setClientId('66754600165-r28h5jkvqv7qihdo5d2tsaf7v00a5ju1.apps.googleusercontent.com');
$client->setClientSecret('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');
//$client->setAccessType('offline');
$client->setRedirectUri('https://kt001.us/mcc_connect/google_ads.php');
$client->addScope("https://www.googleapis.com/auth/adwords");

if ($_GET['code']!='' && $_GET['customer_id']=='') {
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  if(isset($token['access_token'])) {
    
    $accessToken = $token['access_token'];
      print_r($accessToken);die;
    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://googleads.googleapis.com/v14/customers:listAccessibleCustomers',
      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(
        'developer-token: z3hk1LyjmH5uSDg9HS-XoQ',
        'Authorization: Bearer '.$token['access_token']
      ),
    ));
    
    $response = curl_exec($curl);
    $result = json_decode($response);
    
    print_r($result);
    
    if(!empty($result) && $result->resourceNames) {
        
        echo "<div class='customers-list-view'>";
        foreach($result->resourceNames as $resource) {
            $customers = array();
            $customer = getAccountDetails($resource, $token['access_token']);
            $customers[] = $customer;
            
            foreach($customers as $customer) {
                echo "<div class='customers-list'>".$customer[0]->customer->descriptiveName." <span>".$customer[0]->customer->id."</span></div>";
                echo "========================";
                echo "<br/>";
                //print accounts under this account
                $curl = curl_init();
                curl_setopt_array($curl, array(
                  CURLOPT_URL => 'https://googleads.googleapis.com/v14/customers/'.$customer[0]->customer->id.'/googleAds:searchStream',
                  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 =>'{"query":"SELECT customer_client.id , customer_client.resource_name , customer_client.descriptive_name FROM customer_client"}',
                  CURLOPT_HTTPHEADER => array(
                    'developer-token: z3hk1LyjmH5uSDg9HS-XoQ',
                    'Content-Type: application/json',
                    'Authorization: Bearer '.$token['access_token']
                  ),
                ));
                
                $response = curl_exec($curl);
                
                curl_close($curl);
                $datas = json_decode($response)[0]->results;
                if(!empty($datas)) {
                    foreach($datas as $Key => $data) {
                        
                         $resourcesArray =  getManagerLink($data->customerClient->id,$customer[0]->customer->id);
                         
                         $resourcesName = $resourcesArray['resourcesName'];
                         
                         $managerLinkId = $resourcesArray['managerLinkId'];
                         
                        $Key++;
                        echo "<a target='_blank' href='https://kt001.us/mcc_connect/CustomerClientLink.php?access_token=".$token['access_token']."&resourcesName=".$resourcesName."&managerLinkid=".$managerLinkId."&prev=".$customer[0]->customer->id."&customer_id=".$data->customerClient->id."'>".$data->customerClient->descriptiveName.'-- ID - '.$data->customerClient->id."- Send Invitation</a>";
                        echo "<br/>";
                        //http://ec2-13-53-200-146.eu-north-1.compute.amazonaws.com/
                        echo "<a target='_blank' href='campaigns.php?access_token=".$token['access_token']."&resourcesName=".$resourcesName."&managerLinkid=".$managerLinkId."&prev=".$customer[0]->customer->id."&customer_id=".$data->customerClient->id."'>".$data->customerClient->descriptiveName.'-- ID - '.$data->customerClient->id."- Show All Campaigns</a>";
                        echo "<br/>";
                        echo "<a target='_blank' href='google_ads_mcc_connect.php?access_token=".$token['access_token']."&resourcesName=".$resourcesName."&managerLinkid=".$managerLinkId."&prev=".$customer[0]->customer->id."&customer_id=".$data->customerClient->id."'>".$data->customerClient->descriptiveName.'-- ID - '.$data->customerClient->id." - Connect To MCC</a>";
                        ;
                        print_r("<br>");
                    }
                }
                
                //end print accounts under this account
                echo "<br/>";
            }
        }
         echo "</div>";
        
           
        //}
    }

    
    curl_close($curl);
                    
              
}

} 
else {
?>
<a href="<?php echo $client->createAuthUrl(); ?>"><input type="button" value="Sign In with Google Ads Account"></a>
<?php } ?>
<?php

function getAccountDetails($resourceName, $token) {
        $curl = curl_init();
        
        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://googleads.googleapis.com/v14/'.$resourceName.'/googleAds:searchStream',
        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 =>'{"query":"SELECT customer.id, customer.descriptive_name, customer.status FROM customer LIMIT 1"}',
        CURLOPT_HTTPHEADER => array(
        'developer-token: z3hk1LyjmH5uSDg9HS-XoQ',
        'Content-Type: application/json',
        'Authorization: Bearer '.$token
        ),
        ));
        
        $response = curl_exec($curl);
        
        curl_close($curl);
        
        $result = json_decode($response);
        if(!empty($result) && $result[0]->results){
            return $result[0]->results;
        } else {
            return false;
        }
    }
    
function getManagerLink($customerId , $Manager){

    global $accessToken;
    
    global $developerToken;
    
    //echo $query = " SELECT customer_client_link.manager_link_id FROM customer_client_link WHERE customer_client_link.client_customer = 'customers/$customerId'";
    $query = "SELECT customer_manager_link.resource_name , customer_manager_link.manager_link_id FROM customer_manager_link";
      echo "<br/>";
                //print accounts under this account
                $curl = curl_init();
                curl_setopt_array($curl, array(
                  CURLOPT_URL => 'https://googleads.googleapis.com/v14/customers/'.$customerId.'/googleAds:searchStream',
                  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_HTTPHEADER => array(
                    'developer-token: z3hk1LyjmH5uSDg9HS-XoQ',
                    'Content-Type: application/json',
                    'Authorization: Bearer '.$accessToken,
                    'login-customer-id: ' . $Manager
                  ),
                ));
                
                                // Construct the request body with the query
                $requestBody = json_encode([
                    'customerId' => $customerId,
                    'query' => $query,
                ]);
                
                curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody);

                $response = curl_exec($curl);
                 curl_close($curl);
                
                $res = json_decode($response);
             
                $resourcesName = $res[0]->results[0]->customerManagerLink->resourceName;
                
                $managerLinkId = $res[0]->results[0]->customerManagerLink->managerLinkId;
                
                return array('resourcesName'=> $resourcesName , 'managerLinkId'=>$managerLinkId);
                 
}    
?>