<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Load the Google API PHP Client autoloader
require_once CPBGD_ROOT_PATH.'/includes/google-doc-api/vendor/autoload.php';

// Import the necessary Google classes
use Google\Client;


if (!class_exists('CPBGD_Admin')) {

	class CPBGD_Admin {

		private $plugin_name;
		private $version;


		/**
		 * Constructor for the main plugin class.
		 *
		 * Initializes the plugin by setting its name and version, and registering
		 * the admin menu setup hook.
		 *
		 * @param string $plugin_name The unique name/slug of the plugin.
		 * @param string $version     The current version of the plugin.
		 */
		public function __construct( $plugin_name, $version ) {

			$this->plugin_name = $plugin_name;
			$this->version = $version;

			add_action('init', array( $this, 'cpbgd_start_session' ), 1);

			add_action( 'admin_menu', array( $this, 'cpbgd_add_plugin_admin_menu' ) );

		}

		/**
		 * Enqueue admin-specific CSS styles for the plugin.
		 *
		 * This function registers and loads the plugin's custom admin stylesheet,
		 * which is useful for styling the plugin's settings pages or other admin UI components.
		 */
		public function cpbgd_enqueue_styles() {

			wp_enqueue_style( $this->plugin_name, CPBGD_ROOT_URL . 'admin/css/cpbgd-post-by-google-document-admin.css', array(), $this->version, 'all' );

		}


		/**
		 * Start a PHP session if none exists.
		 *
		 * This function initializes a session using session_start(), ensuring that
		 * it is only called if a session hasn't already been started. Useful for
		 * storing temporary data such as user-specific plugin states or API tokens.
		 * Should be hooked early in the WordPress lifecycle (e.g., on 'init').
		 */
		public function cpbgd_start_session() {
			if (session_status() === PHP_SESSION_NONE) {
				session_start();
			}
		}


		/**
		 * Registers the admin menu and submenus for the plugin in the WordPress dashboard.
		 *
		 * This function adds a top-level menu called "Google API Settings" and two submenus:
		 * - "Upload Google Doc" for uploading Google Docs.
		 * - "Documentation" for plugin usage instructions.
		 *
		 * Each menu is restricted to users with the 'manage_options' capability (typically admins).
		 */
		public function cpbgd_add_plugin_admin_menu() {
			add_menu_page(
				esc_html__('Google API Settings', 'create-post-by-google-document'), 
				esc_html__('Google API Settings', 'create-post-by-google-document'), 
				'manage_options',            
				'cpbgd_api_settings',     
				array( $this, 'cpbgd_api_settings_page' ),
				'dashicons-google',   
				80                          
			);
		
			add_submenu_page(
				'cpbgd_api_settings',     
				esc_html__('Upload Google Doc', 'create-post-by-google-document'),   
				esc_html__('Upload Google Doc', 'create-post-by-google-document'), 
				'manage_options',           
				'cpbgd_upload_doc',      
				array( $this, 'cpbgd_upload_doc_page' ),    
			);

			add_submenu_page(
				'cpbgd_api_settings',     
				esc_html__('Documentation', 'create-post-by-google-document'),   
				esc_html__('Documentation', 'create-post-by-google-document'), 
				'manage_options',           
				'cpbgd_plugin_documentation',      
				array( $this, 'cpbgd_plugin_documentation_page' ),    
			);
		}

		/**
		 * Display and handle submission of the Google API Settings page.
		 *
		 * This method renders an admin settings form where users can configure
		 * their Google API credentials (Application Name, Developer Key, Client ID, Client Secret).
		 * On form submission, it verifies the nonce for security, sanitizes input,
		 * and saves the settings using WordPress options API.
		 */
		public function cpbgd_api_settings_page() {
			if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['google_drive_save'])) {
				$my_form_nonce = isset($_POST['my_form_nonce']) ? sanitize_text_field(wp_unslash($_POST['my_form_nonce'])) : '';
				if (!empty($my_form_nonce) && wp_verify_nonce($my_form_nonce, 'my_form_action')) {

					$cpbgd_application_name = isset($_POST['cpbgd_application_name']) ? sanitize_text_field(wp_unslash($_POST['cpbgd_application_name'])) : '';
					$cpbgd_developer_key = isset($_POST['cpbgd_developer_key']) ? sanitize_text_field(wp_unslash($_POST['cpbgd_developer_key'])) : '';
					$cpbgd_client_id = isset($_POST['cpbgd_client_id']) ? sanitize_text_field(wp_unslash($_POST['cpbgd_client_id'])) : '';
					$cpbgd_client_secret = isset($_POST['cpbgd_client_secret']) ? sanitize_text_field(wp_unslash($_POST['cpbgd_client_secret'])) : '';

					// Save each value in WordPress options
					update_option('cpbgd_application_name', $cpbgd_application_name);
					update_option('cpbgd_developer_key', $cpbgd_developer_key);
					update_option('cpbgd_client_id', $cpbgd_client_id);
					update_option('cpbgd_client_secret', $cpbgd_client_secret);

					echo sprintf('<div class="updated"><p>%s</p></div>', esc_html__('Settings saved successfully!', 'create-post-by-google-document'));
				}
			}

			?>
			
			<div class="wrap">
				<h1><?php esc_html_e('Google API Settings', 'create-post-by-google-document'); ?></h1>
				<form method="post" action="">
					<table class="form-table">
						<tr valign="top">
							<th scope="row"><?php esc_html_e('Application Name', 'create-post-by-google-document'); ?></th>
							<td><input type="text" class="conf_input" name="cpbgd_application_name" value="<?php echo esc_attr(get_option('cpbgd_application_name', '') ?? ''); ?>" /></td>
						</tr>
						<tr valign="top">
							<th scope="row"><?php esc_html_e('Developer Key (API Key)', 'create-post-by-google-document'); ?></th>
							<td><input type="text" class="conf_input" name="cpbgd_developer_key" value="<?php echo esc_attr(get_option('cpbgd_developer_key', '') ?? ''); ?>" /></td>
						</tr>
						<tr valign="top">
							<th scope="row"><?php esc_html_e('Client Id', 'create-post-by-google-document'); ?></th>
							<td><input type="text" class="conf_input" name="cpbgd_client_id" value="<?php echo esc_attr(get_option('cpbgd_client_id', '') ?? ''); ?>" /></td>
						</tr>
						<tr valign="top">
							<th scope="row"><?php esc_html_e('Client Secret', 'create-post-by-google-document'); ?></th>
							<td><input type="text" class="conf_input" name="cpbgd_client_secret" value="<?php echo esc_attr(get_option('cpbgd_client_secret', '') ?? ''); ?>" /></td>
						</tr>
					</table>
					<p class="submit">
						<?php wp_nonce_field('my_form_action', 'my_form_nonce'); ?>
						<input type="submit" name="google_drive_save" class="button-primary" value="<?php esc_html_e('Save Settings', 'create-post-by-google-document'); ?>" />
					</p>

				</form>
				<p>
					<strong><?php esc_html_e( 'Note:', 'create-post-by-google-document' ); ?></strong>
					<?php
					echo esc_html__('Please add the following URL to the \'Authorized redirect URIs\' field when creating the Google Docs API credentials in your Google account. URL:', 'create-post-by-google-document');
					echo '"'.esc_url( $this->cpbgd_genrate_gooogle_doc_redirect_url() ).'".';
					echo '<br>';
					echo esc_html__('For further guidance, please see the ', 'create-post-by-google-document');
					echo '<a href="' . esc_url( admin_url( 'admin.php?page=cpbgd_plugin_documentation' ) ) . '">' . esc_html__( 'Documentation', 'create-post-by-google-document' ) . '</a>.';
					?>
					
				</p>




			</div>
			<?php

		}

		/**
		 * Initializes the Google API Client with stored credentials and handles token setup.
		 *
		 * - Starts session if not already started (required for storing temporary OAuth data).
		 * - Loads saved Google API settings from WordPress options.
		 * - Creates and configures the Google Client object.
		 * - Handles setting or refreshing access tokens for API requests.
		 */
		private function cpbgd_initialize_google_client() {

			$cpbgd_application_name = get_option('cpbgd_application_name', '');
			$cpbgd_developer_key    = get_option('cpbgd_developer_key', '');
			$cpbgd_client_id        = get_option('cpbgd_client_id', '');
			$cpbgd_client_secret    = get_option('cpbgd_client_secret', '');
			$cpbgd_api_token    = get_option('cpbgd_api_token', '');

			if($cpbgd_application_name && $cpbgd_developer_key && $cpbgd_client_id && $cpbgd_client_secret){
				
				$this->client = new Client();
				$this->client->setApplicationName($cpbgd_application_name);
				$this->client->setDeveloperKey($cpbgd_developer_key);
				$this->client->setClientId($cpbgd_client_id);
				$this->client->setClientSecret($cpbgd_client_secret);
				$redirectUrl = $this->cpbgd_genrate_gooogle_doc_redirect_url();
				$this->client->setRedirectUri($redirectUrl);
				$this->client->setAccessType('offline');
				$this->client->setPrompt('select_account consent');
				//$this->client->addScope(Google\Service\Drive::DRIVE);
				$this->client->addScope(Google\Service\Docs::DOCUMENTS_READONLY);
				$this->client->createAuthUrl();
				$token = unserialize($cpbgd_api_token);

				if ($token) {
					if(isset($token['error']) && $token['error'] && isset($_GET['code']) && isset($_SESSION['cpbgd_action_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_SESSION['cpbgd_action_nonce'])), 'cpbgd_nonce_action')){
						$this->cpbgd_fetch_access_token(sanitize_text_field(wp_unslash($_GET['code'])));
					}else{
						$this->client->setAccessToken($token);
						if ($this->client->isAccessTokenExpired()) {
							$this->cpbgd_refresh_token();
						}

					}
				} elseif (isset($_GET['code']) && isset($_SESSION['cpbgd_action_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_SESSION['cpbgd_action_nonce'])), 'cpbgd_nonce_action')) {
					$this->cpbgd_fetch_access_token(sanitize_text_field(wp_unslash($_GET['code'])));
				}
			}else{
				echo esc_html__('Please enter Google API Settings correctly.', 'create-post-by-google-document');

			}
		}

		/**
		 * Fetches the Google API access token using the OAuth authorization code
		 * and saves it to the WordPress database.
		 *
		 * @param string $code The authorization code received from Google after user consent.
		 */
		private function cpbgd_fetch_access_token($code) {

			$accessToken = $this->client->fetchAccessTokenWithAuthCode($code);
			$cpbgd_api_token = serialize($accessToken);

			$updated = update_option('cpbgd_api_token', $cpbgd_api_token);
			if(!$updated){
				echo esc_html__('Token was not updated (it may be the same as before).', 'create-post-by-google-document'). '<br>';
			}

		}

		/**
		 * Refreshes the Google API access token using the stored refresh token,
		 * then updates the token saved in the WordPress database.
		 */
		private function cpbgd_refresh_token() {
			$refreshToken = $this->client->getRefreshToken();
			$this->client->fetchAccessTokenWithRefreshToken($refreshToken);
			$cpbgd_api_token = serialize($this->client->getAccessToken());

			$updated = update_option('cpbgd_api_token', $cpbgd_api_token);

			if(!$updated){
				echo esc_html__('Token was not updated (it may be the same as before).', 'create-post-by-google-document'). '<br>';
			}
		}

		/**
		 * Generates the admin URL to redirect users to the Google Doc access page.
		 *
		 * @return string The full URL of the Google Doc access admin page.
		 */
		private function cpbgd_genrate_gooogle_doc_redirect_url(){
			
			$url = admin_url( 'admin.php?page=cpbgd_upload_doc' );
			return $url;

		}

		/**
		 * Retrieves the full URL of the current admin page.
		 *
		 * This function constructs the URL dynamically by checking the protocol (HTTP or HTTPS),
		 * and appending the host and request URI from the server variables.
		 *
		 * @return string The full current URL in the admin area.
		 */
		private function cpbgd_get_admin_current_page_url() {
			$url = 'http';
			if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
				$url .= "s";
			}
			$url .= "://";
			$url .= isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
			$url .= isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
			return $url;
		}

		/**
		 * Displays the Google Doc Access admin page.
		 *
		 * This page allows users to authorize access to their Google Docs via OAuth,
		 * enter a Google Doc URL, and start loading content from the document.
		 *
		 * Handles session start, Google API client initialization, OAuth flow, nonce security,
		 * and renders the appropriate forms and buttons for user interaction.
		 *
		 * @return void
		 */
		public function cpbgd_upload_doc_page() {
		
			?>
			
			<div class="wrap">
				<h1><?php esc_html_e('Upload Google Doc', 'create-post-by-google-document'); ?></h1>
			<?php

			$this->cpbgd_initialize_google_client();

			$cpbgd_application_name = get_option('cpbgd_application_name', '');
			$cpbgd_developer_key    = get_option('cpbgd_developer_key', '');
			$cpbgd_client_id        = get_option('cpbgd_client_id', '');
			$cpbgd_client_secret    = get_option('cpbgd_client_secret', '');

			
			if($cpbgd_application_name && $cpbgd_developer_key && $cpbgd_client_id && $cpbgd_client_secret){

				if (!$this->client->getAccessToken()) {
					$authUrl = $this->client->createAuthUrl();

					$action = 'cpbgd_nonce_action';
					$nonce = wp_create_nonce($action);
					if(isset($nonce)){
						$_SESSION['cpbgd_action_nonce'] = $nonce;

					}
					 
					echo '<a class="button doc_btn" target="_blank" href="' . esc_url($authUrl) . '">'.esc_html__('Authorize Google Doc Access', 'create-post-by-google-document').'</a>';
				} else {

					if( $this->client->getAccessToken() && isset($_REQUEST['loading'])){
						if(isset($_POST['gd_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['gd_nonce'])), 'gd_form_nonce')){
							$this->cpbgd_list_docs_in_folder();
							echo '<form class="load-post" method="post" action="'.esc_url($this->cpbgd_get_admin_current_page_url()).'">';
							echo '<label class="input-label">Google Doc url</label>';
							echo '<input type="url" class="conf_input" name="cpbgd_doc_url" value="' . esc_attr( isset($_POST['cpbgd_doc_url']) ? sanitize_text_field( wp_unslash($_POST['cpbgd_doc_url']) ) : '' ) . '" placeholder="Enter Doc url" />';
							echo '<button type="submit" class="button doc_btn">Start Uploading Post</button>';
							echo '<input type="hidden" name="gd_nonce" value="'.esc_html(wp_create_nonce('gd_form_nonce')).'">';
							echo '<p class="sample-doc">Please review the sample <a href="'.esc_url(CPBGD_ROOT_URL).'sample-google-doc.docx">document</a>.</p>';
							echo '</form>';
						}else{
							echo '<form class="load-post" method="post" action="'.esc_url($this->cpbgd_get_admin_current_page_url()).'">';
							echo '<label class="input-label">Google Doc url</label>';
							echo '<input type="url" class="conf_input" name="cpbgd_doc_url" value="' . esc_attr( isset($_POST['cpbgd_doc_url']) ? sanitize_text_field( wp_unslash($_POST['cpbgd_doc_url']) ) : '' ) . '" placeholder="Enter Doc url" />';
							echo '<button type="submit" class="button doc_btn">Start Uploading Post</button>';
							echo '<input type="hidden" name="gd_nonce" value="'.esc_html(wp_create_nonce('gd_form_nonce')).'">';
							echo '<p class="sample-doc">Please review the sample <a href="'.esc_url(CPBGD_ROOT_URL).'sample-google-doc.docx">document</a>.</p>';
							echo '</form>';
						}
					}else{
						echo '<form class="load-post" method="post" action="'.esc_url($this->cpbgd_get_admin_current_page_url()).'&loading=true">';
						echo '<label class="input-label">Google Doc url</label>';
						echo '<input type="url" class="conf_input" name="cpbgd_doc_url" value="' . esc_attr( isset($_POST['cpbgd_doc_url']) ? sanitize_text_field( wp_unslash($_POST['cpbgd_doc_url']) ) : '' ) . '" placeholder="Enter Doc url" />';
						echo '<button type="submit" class="button doc_btn">Start Uploading Post</button>';
						echo '<input type="hidden" name="gd_nonce" value="'.esc_html(wp_create_nonce('gd_form_nonce')).'">';
						echo '<p class="sample-doc">Please review the sample <a href="'.esc_url(CPBGD_ROOT_URL).'sample-google-doc.docx">document</a>.</p>';
						echo '</form>';
					}
				}
			}
			?>
			</div>

			<?php 

		}

		/**
		 * Displays the Plugin Documentation page in the WordPress admin.
		 *
		 * Provides step-by-step instructions on how to create Google API credentials,
		 * configure the OAuth consent screen, and set up the plugin.
		 *
		 * @return void
		 */
		public function cpbgd_plugin_documentation_page() {
			?>
			<div class="wrap">
				<h1><?php esc_html_e('Plugin documentation', 'create-post-by-google-document'); ?></h1>
				<div class="doc_main">

					<h2><?php esc_html_e('Google API Creation Process ', 'create-post-by-google-document'); ?></h2>

					<p><strong><?php esc_html_e('Step 1:', 'create-post-by-google-document'); ?></strong></p>
					<ul>
						<li>
							<?php esc_html_e('Create a Google Cloud Project at', 'create-post-by-google-document'); ?> <a href="https://console.cloud.google.com" target="_blank">https://console.cloud.google.com</a>
						</li>
						<li><?php esc_html_e('Click the project dropdown (top left) → ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('New Project', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Enter Project Name → Click ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('Create', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Select the project from the dropdown', 'create-post-by-google-document'); ?></li>
					</ul>

					<p><strong><?php esc_html_e('Step 2:', 'create-post-by-google-document'); ?></strong></p>
					<ul>
						<li><?php esc_html_e('Enable Google Docs API', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Go to ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('APIs & Services > Library', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Search: ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('Google Docs API', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Click it → Click ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('Enable', 'create-post-by-google-document'); ?></strong></li>
					</ul>

					<p><strong><?php esc_html_e('Step 3:', 'create-post-by-google-document'); ?></strong></p>
					<ul>
						<li><?php esc_html_e('Create OAuth 2.0 Credentials', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Go to ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('APIs & Services > Credentials', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Click ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('+ Create Credentials > OAuth client ID', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('If prompted, first set up the OAuth consent screen (see next step)', 'create-post-by-google-document'); ?></li>
					</ul>

					<p><strong><?php esc_html_e('Step 4:', 'create-post-by-google-document'); ?></strong></p>
					<ul>
						<li><?php esc_html_e('Configure OAuth Consent Screen', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Go to ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('OAuth consent screen', 'create-post-by-google-document'); ?></strong><?php esc_html_e(' (left sidebar)', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Choose ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('External', 'create-post-by-google-document'); ?></strong><?php esc_html_e(' → Click ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('Create', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Fill in the following:', 'create-post-by-google-document'); ?>
							<ul>
								<li><?php esc_html_e('App name (e.g., My Google Docs API App)', 'create-post-by-google-document'); ?></li>
								<li><?php esc_html_e('User support email', 'create-post-by-google-document'); ?></li>
								<li><?php esc_html_e('Developer contact email', 'create-post-by-google-document'); ?></li>
							</ul>
						</li>
						<li><?php esc_html_e('Save and continue through all steps → Submit for Verification (optional now, required later)', 'create-post-by-google-document'); ?></li>
					</ul>

					<p><strong><?php esc_html_e('Step 5:', 'create-post-by-google-document'); ?></strong></p>
					<ul>
						<li><?php esc_html_e('Create OAuth Client ID', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Go to ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('Credentials > Create Credentials > OAuth client ID', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Choose ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('Application Type: Web Application', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Add Authorized JavaScript origins', 'create-post-by-google-document'); ?><br>
							<code><?php echo esc_url(site_url()); ?></code></li>
						<li><?php esc_html_e('Add Authorized Redirect URIs', 'create-post-by-google-document'); ?><br>
							<code><?php echo esc_url($this->cpbgd_genrate_gooogle_doc_redirect_url()); ?></code></li>
						<li><?php esc_html_e('Click ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('Create', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Download the credentials JSON', 'create-post-by-google-document'); ?></li>
					</ul>

					<p><strong><?php esc_html_e('Step 6:', 'create-post-by-google-document'); ?></strong></p>
					<ul>
						<li><?php esc_html_e('Submit for OAuth Verification (if needed)', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Required if your app accesses sensitive scopes or is used by external users', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Go to ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('OAuth consent screen', 'create-post-by-google-document'); ?></strong><?php esc_html_e(' → Click ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('Submit for verification', 'create-post-by-google-document'); ?></strong></li>
						<li><?php esc_html_e('Provide:', 'create-post-by-google-document'); ?>
							<ul>
								<li><?php esc_html_e('App logo, privacy policy URL, terms of service URL', 'create-post-by-google-document'); ?></li>
								<li><?php esc_html_e('Video showing how you use Google user data', 'create-post-by-google-document'); ?></li>
							</ul>
						</li>
						<li><?php esc_html_e('Google will review and notify you by email (may take several days)', 'create-post-by-google-document'); ?></li>
					</ul>

					<h2><?php esc_html_e('Plugin Configuration Process', 'create-post-by-google-document'); ?></h2>
					<ol>
						<li><?php esc_html_e('Navigate to the ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('“Google Doc Settings”', 'create-post-by-google-document'); ?></strong><?php esc_html_e(' from the left sidebar in WordPress admin.', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Enter the API details:', 'create-post-by-google-document'); ?>
							<ul>
								<li><?php esc_html_e('A. Application Name', 'create-post-by-google-document'); ?></li>
								<li><?php esc_html_e('B. Developer Key (API Key)', 'create-post-by-google-document'); ?></li>
								<li><?php esc_html_e('C. Client ID', 'create-post-by-google-document'); ?></li>
								<li><?php esc_html_e('D. Client Secret', 'create-post-by-google-document'); ?></li>
							</ul>
						</li>
						<li><?php esc_html_e('Go to ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('“Upload Google Doc”', 'create-post-by-google-document'); ?></strong><?php esc_html_e(' under the ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('“Google Doc Settings”', 'create-post-by-google-document'); ?></strong><?php esc_html_e(' submenu.', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('Click ', 'create-post-by-google-document'); ?><strong><?php esc_html_e('“Authorize Google Doc Access”', 'create-post-by-google-document'); ?></strong><?php esc_html_e(' and sign in with your Google account.', 'create-post-by-google-document'); ?></li>
						<li><?php esc_html_e('After authorization, enter the Google Doc URL to create a WordPress post from it.', 'create-post-by-google-document'); ?></li>
					</ol>

				</div>
			</div>
			<?php
		}


		/**
		 * Process Google Doc URL posted via form, fetch content from Google Docs API,
		 * then create or update a WordPress post accordingly.
		 */
		private function cpbgd_list_docs_in_folder() {
			$cpbgd_application_name = get_option('cpbgd_application_name', '');
			$cpbgd_developer_key    = get_option('cpbgd_developer_key', '');
			$cpbgd_client_id        = get_option('cpbgd_client_id', '');
			$cpbgd_client_secret    = get_option('cpbgd_client_secret', '');

			if($cpbgd_application_name && $cpbgd_developer_key && $cpbgd_client_id && $cpbgd_client_secret){
				
				$docsService = new Google_Service_Docs($this->client);

				if ( isset($_POST['gd_nonce']) && wp_verify_nonce( sanitize_text_field(wp_unslash($_POST['gd_nonce'])), 'gd_form_nonce' ) ) {

					if(isset($_POST['cpbgd_doc_url'])){

						$docUrl = sanitize_text_field(wp_unslash($_POST['cpbgd_doc_url']));

						if (preg_match("/https:\/\/docs\.google\.com\/document\/d\/([a-zA-Z0-9-_]+)/", $docUrl, $matches)) {

							$documentId = $matches[1];

							try {
								
								$document = $docsService->documents->get($documentId);

								$htmlContent = $this->cpbgd_parseDocumentContentWithImages($document);

								$gpost =  $this->cpbgd_get_posts_by_meta_value('cpbgd_google_doc_id', $documentId);

								$posttitle = '';
								$posttitle = $this->cpbgd_extractFirstlineasTitleFromParagraph($htmlContent);

								$attchid = '';
								if (stripos($htmlContent, '<img') !== false) {
									$attchid = $this->cpbgd_extractFirstImageUrlFromHtml($htmlContent);
									
								}

								$postcontent = '';
								if (stripos($htmlContent, '<img') !== false) {
									$postcontent = $this->cpbgd_getContentAfterImage($htmlContent);

									if($postcontent){
										$postcontent = preg_replace('/<p>\s*<\/p>/', '<br>', $postcontent);
									}

								}

								if($gpost){
									$postID = $gpost[0];

									if($postID && $posttitle){

										$post_data = array(
											'ID'           => $postID,
											'post_title'   => $posttitle,      
											'post_content' => $postcontent,   
											'post_status'  => 'publish',            
										);
									
										$updated_post_id = wp_update_post($post_data);

										if (!is_wp_error($updated_post_id)) {

											if (has_post_thumbnail($postID)) {

												$thumbnail_id = get_post_thumbnail_id($postID);
												$deleted = wp_delete_attachment($thumbnail_id, true);

												if($deleted){

													if($attchid){
														
														if (wp_attachment_is_image($attchid)) {
															set_post_thumbnail($postID, $attchid);
														}
														
													}
												}
												
											} else {
												if($attchid){
													
													if (wp_attachment_is_image($attchid)) {
														set_post_thumbnail($postID, $attchid);
													}
													
												}
											}
											// translators: 1: Document title, 2: Post title
											$translated_text = esc_html__(
												'"%1$s" synchronized successfully and post "(%2$s)" updated.',
												'create-post-by-google-document'
											);

											echo sprintf(
												esc_html($translated_text),
												esc_html($document->getTitle()),  
												esc_html($posttitle)
											) . '<br>';

										}else{

											// translators: 1: Document title
											$translated_text = esc_html__(
												'An error occurred while synchronizing the document "%s". Please try reloading.',
												'create-post-by-google-document'
											);

											echo sprintf(
												esc_html($translated_text),
												esc_html($document->getTitle())
											) . '<br>';


										}

									}

								}else{
									if($posttitle){

										$new_post = array(
											'post_title'    => $posttitle,    
											'post_content'  => $postcontent,  
											'post_type'     => 'post', 
											'post_status'   => 'publish',  
											'post_author'   => 1,        
										);
									
										$post_id = wp_insert_post($new_post);

										if (!is_wp_error($post_id)) {
											$googledocid = add_post_meta($post_id, 'cpbgd_google_doc_id', $documentId, true);

											if($attchid){
												if (wp_attachment_is_image($attchid)) {
													set_post_thumbnail($post_id, $attchid);
												}
											}

											// translators: 1: Document title, 2: Post title
											$translated_text = esc_html__(
												'"%1$s" synchronized successfully and post "(%2$s)" created.',
												'create-post-by-google-document'
											);

											echo sprintf(
												esc_html($translated_text),
												esc_html($document->getTitle()),  
												esc_html($posttitle)
											) . '<br>';

										}else{

											// translators: 1: Document title
											$translated_text = esc_html__(
												'An error occurred while synchronizing the document "%s". Please try reloading.',
												'create-post-by-google-document'
											);

											echo sprintf(
												esc_html($translated_text),
												esc_html($document->getTitle())
											) . '<br>';

										}
									}
								}


							} catch (Google_Service_Exception $e) {
							

								// translators: 1: Error Message
								$translated_text = esc_html__(
									'Unable to access document. Reason: "%s"',
									'create-post-by-google-document'
								);

								echo sprintf(
									esc_html($translated_text),
									esc_html($e->getMessage())
								) . '<br>';

							}
						} else {
							echo esc_html__('Invalid Google Docs URL format.', 'create-post-by-google-document');
						}

					}
				}

			}else{
				echo esc_html__('Please configure your Google Docs API settings correctly.', 'create-post-by-google-document');
			}

		}


		/**
		 * Extracts the first HTML element's text content from given HTML string,
		 * stripping all HTML tags to return plain text.
		 *
		 * @param string $paragraphText HTML content (e.g. paragraph or multiple paragraphs).
		 * @return string The plain text of the first element inside the HTML.
		 */
		private function cpbgd_extractFirstlineasTitleFromParagraph($paragraphText) {
			$dom = new DOMDocument();
			libxml_use_internal_errors(true);
			$dom->loadHTML('<wrapper>' . $paragraphText . '</wrapper>'); // wrap to ensure single root
			libxml_clear_errors();
			$container = $dom->getElementsByTagName('wrapper')->item(0);

			$firstElement = null;
			foreach ($container->childNodes as $node) {
				if ($node->nodeType === XML_ELEMENT_NODE) {
					$firstElement = $dom->saveHTML($node);
					break;
				}
			}

			$firstElement = wp_strip_all_tags($firstElement);

			return $firstElement; 
		}

		/**
		 * Extracts the first image attachment ID from the given HTML content.
		 *
		 * @param string $htmlContent The HTML content to search for an image attachment ID.
		 * @return string|null The attachment ID found in the first <img> tag with 'attchid' attribute, or null if none found.
		 */
		private function cpbgd_extractFirstImageUrlFromHtml($htmlContent) {
			if (preg_match('/<img[^>]+attchid=["\']([^"\']+)["\']/i', $htmlContent, $matches)) {
				$attchid = $matches[1];
			}else{
				$attchid = '';
			}
			return $attchid;
		}

		/**
		 * Returns the portion of the HTML content that comes after the first <img> tag.
		 *
		 * @param string $htmlContent The full HTML content.
		 * @return string The HTML content after the first image tag, or empty string if no image found.
		 */
		private function cpbgd_getContentAfterImage($htmlContent) {
			$imgPos = strpos($htmlContent, '<img');
			if ($imgPos !== false) {
				$imgClosePos = strpos($htmlContent, '>', $imgPos);
				if ($imgClosePos !== false) {
					return substr($htmlContent, $imgClosePos + 1);
				}
			}
			return '';
		}

		/**
		 * Retrieves post IDs by meta key and meta value.
		 *
		 * @param string $meta_key   Meta key to search for.
		 * @param string $meta_value Meta value to match.
		 * @return array             Array of post IDs matching the meta query, or empty array if none found.
		 */
		private function cpbgd_get_posts_by_meta_value($meta_key, $meta_value) {
			$args = array(
				'post_type'      => 'post', 
				'post_status'    => 'publish', 
				'meta_query'     => array(
					array(
						'key'     => $meta_key,   
						'value'   => $meta_value,
						'compare' => '=',   
					),
				),
				'posts_per_page' => 2,
				'fields'         => 'ids',
			);
			$post_ids = get_posts( $args );
			if ($post_ids) {
				return $post_ids;
			} else {
				return array();
			}
		}

		/**
		 * Downloads an image from a URL and uploads it to the WordPress media library.
		 *
		 * @param string $image_url The URL of the image to upload.
		 * @return int|string       Attachment ID on success, or error message string on failure.
		 */
		private function cpbgd_upload_image_from_url_to_media_library($image_url) {
			$file_extension = pathinfo($image_url, PATHINFO_EXTENSION);

			if (empty($file_extension)) {
				$file_extension = 'jpg';
			}
			$file_name = 'image_' . time() . '.' . $file_extension;
			$upload_dir = wp_upload_dir();
			$temp_file = $upload_dir['path'] . '/' . uniqid('wp_upload_') . '_' . $file_name;
		
			$response = wp_remote_get( $image_url );

			if ( is_wp_error( $response ) ) {
				$error_message = $response->get_error_message();

				// translators: 1: Error Message
				$translated_text = esc_html__(
					'There was an error retrieving the image: "%s"',
					'create-post-by-google-document'
				);

				echo sprintf(
					esc_html($translated_text),
					esc_html($error_message)
				);

				
			} else {
				$image_data = wp_remote_retrieve_body( $response );
			}
			if ($image_data === false) {
				return esc_html__('Unable to download image.', 'create-post-by-google-document');
			}
			if ( ! function_exists( 'request_filesystem_credentials' ) ) {
				require_once( ABSPATH . 'wp-admin/includes/file.php' );
			}
			
			global $wp_filesystem;
			
			if ( ! isset( $wp_filesystem ) ) {
				$creds = request_filesystem_credentials( site_url() );
				if ( ! WP_Filesystem( $creds ) ) {
					return false; 
				}
			}

			$wp_filesystem->put_contents( $temp_file, $image_data, FS_CHMOD_FILE );
		
			if (!file_exists($temp_file)) {
				return esc_html__('Failed to create temporary file.', 'create-post-by-google-document');
			}
		
			$file = array(
				'name'     => $file_name,
				'type'     => mime_content_type($temp_file),
				'tmp_name' => $temp_file,
				'error'    => 0,
				'size'     => filesize($temp_file),
			);
		
			$attachment_id = media_handle_sideload($file, 0);
		
			if (is_wp_error($attachment_id)) {
				if (file_exists($temp_file)) {
					wp_delete_file($temp_file);
				}

				// translators: 1: Error Message
				$translated_text = esc_html__(
					'Image upload failed: "%s"',
					'create-post-by-google-document'
				);

				return sprintf(
					esc_html($translated_text),
					esc_html($attachment_id->get_error_message())
				);
			}
		
			if (file_exists($temp_file)) {
				wp_delete_file($temp_file);
			}
		
			return $attachment_id;
		}
		
		/**
		 * Parses the Google Docs document content including paragraphs and tables,
		 * converting them into HTML with images handled properly.
		 *
		 * @param array $document Google Docs API document object (array format).
		 * @return string HTML content parsed from the document.
		 */
		private function cpbgd_parseDocumentContentWithImages($document) {
			$html = '';
			foreach ($document['body']['content'] as $content) {
				if (isset($content['paragraph'])) {
					$html .= $this->cpbgd_parseParagraphWithImages($content['paragraph'], $document);
				}

				if (isset($content['table'])) {
					$html .= $this->cpbgd_parseTable($content['table'], $document);
				}
			}

			return $html;
			
		}

		/**
		 * Parses a paragraph element from Google Docs document, including text and inline objects (images)
		 * converting it to HTML.
		 *
		 * @param array $paragraph The paragraph array from Google Docs API.
		 * @param array $document The entire document array (needed for resolving inline objects).
		 * @return string HTML representation of the paragraph with images.
		 */
		private function cpbgd_parseParagraphWithImages($paragraph, $document) {
			$html = '';
			foreach ($paragraph['elements'] as $element) {
				if (isset($element['textRun'])) {
					$html .= $this->cpbgd_parseTextRun($element['textRun']);
				}

				if (isset($element['horizontalRule'])) {
					$html .= '<hr />';
				}
		
				if (isset($element['inlineObjectElement'])) {
					
					$html .= $this->cpbgd_parseInlineObject($element['inlineObjectElement'], $document);
				}
			}

			return '<p>' . $html . '</p>';
		}

	
		/**
		 * Parses an inline object element from a Google Doc paragraph, typically an image,
		 * uploads it to the WordPress media library, and returns the HTML <img> tag.
		 *
		 * @param array $inlineObjectElement The inline object element containing the inlineObjectId.
		 * @param array $document The full Google Doc document data.
		 * @return string HTML image tag or empty string if no image found.
		 */
		private function cpbgd_parseInlineObject($inlineObjectElement, $document) {
			$inlineObjectId = $inlineObjectElement['inlineObjectId'];
			$inlineObject = $document['inlineObjects'][$inlineObjectId];
		
			if (isset($inlineObject['inlineObjectProperties']['embeddedObject'])) {
				$embeddedObject = $inlineObject['inlineObjectProperties']['embeddedObject'];

				if (isset($embeddedObject['imageProperties']['contentUri'])) {
					$imageUrl = $embeddedObject['imageProperties']['contentUri'];

					$attchid = $this->cpbgd_upload_image_from_url_to_media_library($imageUrl);

					return wp_get_attachment_image( $attchid, 'full', false, [ 'alt' => 'Image', 'attchid' => $attchid ] );
					
				}
			}
		
			return '';
		}

		/**
		 * Parses a text run from Google Docs content and applies formatting based on the text style.
		 *
		 * @param array $textRun The text run array from the Google Docs API.
		 * @return string The formatted HTML string.
		 */
		private function cpbgd_parseTextRun($textRun) {
			$html = htmlspecialchars($textRun['content']);

			if (!empty($textRun['textStyle']['link']['url'])) {
				$url = htmlspecialchars($textRun['textStyle']['link']['url']);
				$html = trim($html);
				if(!empty($html)){
					$html = '<a href="' . $url . '" target="_blank">' . $html . '</a>';
				}
			}
			
			if (!empty($textRun['textStyle']['bold'])) {
				$html = trim($html);
				if(!empty($html)){
					$html = '<strong>' . $html . '</strong>';
				}
			}
			if (!empty($textRun['textStyle']['italic'])) {
				$html = trim($html);
				if(!empty($html)){
					$html = '<em>' . $html . '</em>';
				}
			}
		
			return $html;
		}

		/**
		 * Parses a Google Docs table object into HTML.
		 *
		 * @param array $table The table object from Google Docs API.
		 * @param array $document The full document data (used for nested parsing).
		 * @return string HTML representation of the table.
		 */
		private function cpbgd_parseTable($table, $document) {
			$totalrows = count($table['tableRows']);
			$tableClass = $totalrows==1 ? 'table-with-media' : 'table-no-media';
			$html = '<table class="' . $tableClass . '">';
			
			foreach ($table['tableRows'] as $row) {
				$html .= '<tr>';
				foreach ($row['tableCells'] as $cell) {
					$html .= '<td>';
					foreach ($cell['content'] as $cellContent) {
						// Parse the cell content, which could be paragraphs, images, etc.
						if (isset($cellContent['paragraph'])) {
							$html .= $this->cpbgd_parseParagraphWithImages($cellContent['paragraph'], $document);
						}
					}
					$html .= '</td>';
				}
				$html .= '</tr>';
			}
			$html .= '</table>';
			return $html;
		}



	}
}
