<?php
	//dar acceso https://console.cloud.google.com/
	
	//hacer funcion de index.php en localhost con redirect de code
	//Si hay token
	//dar acceso
	//revocar token
	//tareas
	
	//este ejemplo realiza todo el proceso de una vez, pero si desea realizar algo mas especificio
	//https://developers.google.com/gmail/api/quickstart/php
	
	include ("../conexion.php"); 



$parametros = "SELECT * FROM web_0000 ";
       $result_parametros = $mysqli->query($parametros);
       $row_para = $result_parametros->fetch_array();
     
	  $username =  $row_para["COREMP"];         //  ruddyajm2018@gmail.com
	  $password =  $row_para["CLACOR"];         //  Rjmc0587
	  $hostname =  $row_para["SERIMAP"];        //  $hostname = '{imap.gmail.com:993/imap/ssl}INBOX'
	  
	  
	
	require_once __DIR__ . '/vendor/autoload.php';
	
	function getClient(){
		$client = new Google_Client();
		$client->setApplicationName('GmailBox');
		$client->setScopes([Google_Service_Gmail::MAIL_GOOGLE_COM]);
		$client->setAuthConfig( __DIR__.'/client_secret.json');
		$client->setAccessType('offline');
		
		$credentialsPath = expandHomeDirectory(__DIR__ . '/token.json');
		if(isset($_GET['code'])){
    		$authCode = trim($_GET['code']);		
			$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
			if (!file_exists(dirname($credentialsPath))) {
				mkdir(dirname($credentialsPath), 0700, true);
			}
			file_put_contents($credentialsPath, json_encode($accessToken));
			printf("Credentials saved to %s\n", $credentialsPath);
		}
		
		if (file_exists($credentialsPath)) {
			$accessToken = json_decode(file_get_contents($credentialsPath), true);
		} else {
		//	$client->setRedirectUri('http://softcomcr.com/wccr');
		//	$client->setRedirectUri('http://127.0.0.1');
			$authUrl = $client->createAuthUrl();
			echo '<a href="'.$authUrl.'">Dar acceso</a><br>';
			die;
		}
		
		$client->setAccessToken($accessToken);
		if ($client->isAccessTokenExpired()) {
			$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
			file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
		}
		return $client;
	}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path)
{
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}

$userId = $username;

	/************************/
	function getAttachment($messageId, $partId, $userId)
    {
        try {
            $client = getClient();
            $gmail = new Google_Service_Gmail($client);
            $message = $gmail->users_messages->get($userId, $messageId);
            $message_payload_details = $message->getPayload()->getParts();
            $attachmentDetails = array();
            $attachmentDetails['attachmentId'] = $message_payload_details[$partId]['body']['attachmentId'];
            $attachmentDetails['headers'] = $message_payload_details[$partId]['headers'];
            $attachment = $gmail->users_messages_attachments->get($userId, $messageId, $attachmentDetails['attachmentId']);
            $attachmentDetails['data'] = $attachment->data;
            return ['status' => true, 'data' => $attachmentDetails];
        } catch (\Google_Service_Exception $e) {
            return ['status' => false, 'message' => $e->getMessage()];
        }
    }
/*
    function base64_to_jpeg($base64_string, $content_type) {
        $find = ["_","-"]; $replace = ["/","+"];
        $base64_string = str_replace($find,$replace,$base64_string);
        $url_str = 'data:'.$content_type.','.$base64_string;
        $base64_string = "url(".$url_str.")";
        $data = explode(',', $base64_string);
        return base64_decode( $data[ 1 ] );
    }
	*/
	
	$client = getClient();
    $service = new Google_Service_Gmail($client);
    $opt_param = array();
    $opt_param['labelIds'] =  'INBOX';
    $opt_param['maxResults'] = 500;
	$opt_param['q'] = "after:2022/03/10 before:2022/03/24";
	
    $messages = $service->users_messages->listUsersMessages($userId, $opt_param);
	$files = array();
     
	$mnsPath = expandHomeDirectory(__DIR__ . '/attachments/');
	echo 'Cantidad: '.count($messages).'<br>';
	
    foreach ($messages as $message_thread) {
		$message = $service->users_messages->get($userId, $message_thread['id']);
		$message_parts = $message->getPayload()->getParts();
		
		
		if(count($message_parts)>0)
			if (array_key_exists(1,$message_parts))				
				$attachId = $message_parts[1]['body']['attachmentId'];
		
		if(!is_null($attachId)){			
			$attach = $service->users_messages_attachments->get($userId, $message['id'], $attachId);
			foreach ($message_parts as $key => $value) {
				if ( isset($value->body->attachmentId) && !isset($value->body->data)) {
					$messageId = $message['id'];
					$partId = $value['partId'];				
					$message_payload_details = $message->getPayload()->getParts();
					$attachmentDetails = array();
					$attachmentDetails['attachmentId'] = $message_payload_details[$partId]['body']['attachmentId'];
					$attachmentDetails['headers'] = $message_payload_details[$partId]['headers'];
					$attachment = $service->users_messages_attachments->get($userId, $messageId, $attachmentDetails['attachmentId']);
					$attachmentDetails['data'] = $attachment->data;
					$attachment = ['status' => true, 'data' => $attachmentDetails];
					
					$content_type = "";					
					foreach ($attachment['data']['headers'] as $key => $values) {
						if($values->name == 'Content-Type'){ 
							$content_type_val = current(explode("/",$values->value));							
							echo $values->value.'<br>';
							if(
								str_contains($values->value,'text/xml') ||
								str_contains($values->value,'application/xml')								
								){
								
								$findme   = 'name="';
								$pos = strpos($values->value, $findme);
								$endPos = strrpos($values->value, '"');
								
								$findme   = '"';
								$pos = strpos($values->value, $findme) + 1; //+6 es longitud de name="
								$endPos = strrpos($values->value, '"'); //-1 es longitud del simbolo "
								$nameAttach = substr($values->value, $pos, -1); // devuelve "d"
								echo $nameAttach. '<br><br><hr><br>'; 
								$decode = base64_decode(str_replace(array('-', '_'), array('+', '/'), $attachment['data']['data']));
								//file_put_contents($mnsPath.'xml-'.date('dmYGis').'-'.$key.'.xml',$decode);
								file_put_contents($mnsPath.$nameAttach,$decode);
						
							
								}
						}	
					}
				}
			}
		}
	}



