<?php



namespace App\Controllers;

use App\Models\User_model;

use App\Models\Dashboard_model;

use App\Models\Common_model;

use App\Models\Member_credits_model;

use App\Models\Packages_and_pricing_model;

use App\Models\Credits_usage_tracking_model;

use App\Models\Email_template_model;

use App\Models\Variable_model;

use App\Models\Rule_model;

use App\Models\Cart_token_model;

use App\Models\Cart_model;

use App\Models\Transaction_model;

use Google_Client;
use Google_Service_Gmail;
use Google_Service_Gmail_Message;
use Google_Service_Gmail_ModifyMessageRequest;
use GuzzleHttp\Client as GuzzleClient;
use Google_Service_Gmail_MessagePart;
use Google_Service_Gmail_MessagePartHeader;
use Google_Service_Gmail_MessagePartBody;
class Test_controller extends BaseController

{

	public $session;

	public function __construct()

	{

		$this->session = session();

		$this->UserModel = new User_model();

		$this->dModel = new Dashboard_model();

		$this->cModel = new Common_model();

		$this->creditsModel = new Member_credits_model();

		$this->PackagesModel = new Packages_and_pricing_model();

		$this->CreditsUsageTrackingModel = new Credits_usage_tracking_model();

		$this->MailModel = new Email_template_model();

		$this->VariableModel = new Variable_model();

		$this->RuleModel = new Rule_model();

		$this->Cart_token_model = new Cart_token_model();

		$this->cartModel = new Cart_model();

		$this->TransactionModel = new Transaction_model();

		helper(['form', 'url']);

	}

    public function index($token = null)

    {

	

    }
	public function test2()
	{
		if($this->request->getVar('code')) {
			try {
				$capi = new Google_Client();
				
				// Get the access token 
				$data = $capi->GetAccessToken(CLIENT_ID, CLIENT_REDIRECT_URL, CLIENT_SECRET, $this->request->getVar('code'));
				
				// Save the access token as a session variable
				$_SESSION['access_token'] = $data['access_token'];
		
				// Redirect to the page where user can create event
				header('Location: home.php');
				exit();
			}
			catch(Exception $e) {
				echo $e->getMessage();
				exit();
			}
		}
	}

	public function sendEmail()
	{
		$credentialsPath = 'credentials.json';
		$tokensPath = 'token.json';
		$accessToken = $this->getAccessToken($tokensPath); // Retrieve access token from storage
		$refreshToken = $this->getRefreshToken($tokensPath); // Retrieve refresh token from storage
		$recipientEmail = 'gowtham.manavalan.la@gmail.com';
		$subject = 'Test email';
		$messageBody = 'This is a test email sent using the Gmail API';
	
		$client = new Google_Client();
		$client->setAuthConfig($credentialsPath);
	
		// Set the access token and refresh token
		// $client->setAccessToken([
		// 	'access_token' => $accessToken,
		// 	'refresh_token' => $refreshToken,
		// 	'expires_in' => 3600, // Expiration time in seconds (adjust if necessary)
		// 	'created' => time()
		// ]);
	
		// if ($client->isAccessTokenExpired()) {
			if (false) {
			// Refresh the access token if expired
			$newAccessToken = $this->refreshAccessToken($client, $refreshToken); // Implement your own method to refresh the token
			$client->setAccessToken([
				'access_token' => $newAccessToken,
				'refresh_token' => $refreshToken,
				'expires_in' => 3600,
				'created' => time()
			]);
	
			// Update the access token in storage if necessary
			$this->updateAccessToken($newAccessToken, $tokensPath); // Implement your own method to update the token
		} else {
			// Request authorization from the user.
			$authUrl = $client->createAuthUrl();
			echo "Open the following link in your browser:\n%s\n", $authUrl;
			print 'Enter verification code: ';
			$authCode = trim(fgets(STDIN));

			// Exchange authorization code for an access token.
			$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
			$client->setAccessToken($accessToken);

			// Check to see if there was an error.
			if (array_key_exists('error', $accessToken)) {
				throw new Exception(join(', ', $accessToken));
			}
		}
	// Save the token to a file.
	if (!file_exists(dirname($tokenPath))) {
		mkdir(dirname($tokensPath), 0700, true);
	}
	file_put_contents($tokensPath, json_encode($this->client->getAccessToken()));
		$service = new Google_Service_Gmail($client);
	
		$message = $this->createMessage('me', $recipientEmail, $subject, $messageBody);
	
		$service->users_messages->send('me', $message);
	
		echo 'Email sent successfully';
	}
	
	private function getAccessToken($tokensPath)
	{
		$tokens = $this->loadTokens($tokensPath);
		return $tokens['access_token'] ?? null;
	}
	
	private function getRefreshToken($tokensPath)
	{
		$tokens = $this->loadTokens($tokensPath);
		return $tokens['refresh_token'] ?? null;
	}
	
	private function refreshAccessToken($client, $refreshToken)
	{
		$client->fetchAccessTokenWithRefreshToken($refreshToken);
		return $client->getAccessToken()['access_token'];
	}
	
	private function updateAccessToken($accessToken, $tokensPath)
	{
		$tokens = $this->loadTokens($tokensPath);
		$tokens['access_token'] = $accessToken;
		$this->saveTokens($tokens, $tokensPath);
	}
	
	private function loadTokens($tokensPath)
	{
		if (file_exists($tokensPath)) {
			$tokensData = file_get_contents($tokensPath);
			return json_decode($tokensData, true);
		}
		return [];
	}
	
	private function saveTokens($tokens, $tokensPath)
	{
		$tokensData = json_encode($tokens);
		file_put_contents($tokensPath, $tokensData);
	}
	
	private function createMessage($sender, $recipient, $subject, $messageBody)
	{
		$message = new Google_Service_Gmail_Message();
		$email = new Google_Service_Gmail_MessagePartHeader();
		$email->setName('To');
		$email->setValue($recipient);
		$message->setPayload(new Google_Service_Gmail_MessagePart());
		$message->getPayload()->setHeaders([$email]);
	
		$body = new Google_Service_Gmail_MessagePartBody();
		$body->setData(base64_encode($messageBody));
		$message->getPayload()->setBody($body);
	
		return $message;
	}
	
















	// public function sendEmail()
	// {
	// 	$credentialsPath = 'credentials.json';
	// 	$accessToken = 'your-access-token';
	// 	$refreshToken = 'your-refresh-token';
	// 	$recipientEmail = 'gowtham.manavalan.la@gmail.com';
	// 	$subject = 'Test email';
	// 	$messageBody = 'This is a test email sent using the Gmail API';
	
	// 	$client = new Google_Client();
	// 	$client->setAuthConfig($credentialsPath);
	
	// 	// Set the access token and refresh token
	// 	$client->setAccessToken([
	// 		'access_token' => $accessToken,
	// 		'refresh_token' => $refreshToken,
	// 		'expires_in' => 3600, // Expiration time in seconds (adjust if necessary)
	// 		'created' => time()
	// 	]);
	
	// 	if ($client->isAccessTokenExpired()) {
	// 		// Refresh the access token if expired
	// 		$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
	// 	}
	
	// 	$service = new Google_Service_Gmail($client);
	
	// 	$message = $this->createMessage('me', $recipientEmail, $subject, $messageBody);
	
	// 	$service->users_messages->send('me', $message);
	
	// 	echo 'Email sent successfully';
	// }
	
	// private function createMessage($sender, $recipient, $subject, $messageBody)
	// {
	// 	$message = new Google_Service_Gmail_Message();
	// 	$email = new Google_Service_Gmail_MessagePartHeader();
	// 	$email->setName('To');
	// 	$email->setValue($recipient);
	// 	$message->setPayload(new Google_Service_Gmail_MessagePart());
	// 	$message->getPayload()->setHeaders([$email]);
	
	// 	$body = new Google_Service_Gmail_MessagePartBody();
	// 	$body->setData(base64_encode($messageBody));
	// 	$message->getPayload()->setBody($body);
	
	// 	return $message;
	// }

	
	
	
	
	
	
	
	// -----------------------------------------------

}

