<?php
/**
 * Simple Google Sheets Manager Class
 *
 * @package ShopExplorer\GoogleSheets
 * @since 1.0.0
 */

namespace SHOPEXPLORER\GoogleSheets;

use SHOPEXPLORER\Exceptions\GoogleSheetsException;

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

/**
 * Simple Google Sheets Manager class
 *
 * Handles Google Sheets operations without requiring Google Client library
 *
 * @since 1.0.0
 */
class SHOPEX_SimpleGoogleSheetsManager {

	/**
	 * Service account authentication
	 *
	 * @var SHOPEX_ServiceAccountAuth
	 */
	private $auth;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->auth = new SHOPEX_ServiceAccountAuth();
	}

	/**
	 * Check if authenticated
	 *
	 * @return bool
	 */
	public function is_authenticated() {
		return $this->auth->has_credentials() && $this->auth->get_access_token() !== false;
	}

	/**
	 * Get authentication manager
	 *
	 * @return SHOPEX_ServiceAccountAuth
	 */
	public function get_auth_manager() {
		return $this->auth;
	}

	/**
	 * Test sheet access
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $sheet_name Sheet name
	 * @return bool
	 */
	public function test_sheet_access( $spreadsheet_id, $sheet_name = 'Sheet1' ) {
		$access_token = $this->auth->get_access_token();

		if ( ! $access_token ) {
			return false;
		}

		$range = $sheet_name . '!A1:A1';
		$url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheet_id}/values/{$range}";

		$response = \wp_remote_get( $url, [
			'headers' => [
				'Authorization' => 'Bearer ' . $access_token,
			],
			'timeout' => 30,
		] );

		if ( \is_wp_error( $response ) ) {
			return false;
		}

		$response_code = \wp_remote_retrieve_response_code( $response );
		return $response_code === 200;
	}

	/**
	 * Get spreadsheet metadata
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @return array|false
	 */
	public function get_spreadsheet_metadata( $spreadsheet_id ) {
		$access_token = $this->auth->get_access_token();

		if ( ! $access_token ) {
			return false;
		}

		$url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheet_id}";

		$response = \wp_remote_get( $url, [
			'headers' => [
				'Authorization' => 'Bearer ' . $access_token,
			],
			'timeout' => 30,
		] );

		if ( \is_wp_error( $response ) ) {
			return false;
		}

		$response_code = \wp_remote_retrieve_response_code( $response );
		if ( $response_code !== 200 ) {
			return false;
		}

		$response_body = \wp_remote_retrieve_body( $response );
		$data = \json_decode( $response_body, true );

		if ( ! $data ) {
			return false;
		}

		$metadata = [
			'title' => $data['properties']['title'] ?? 'Unknown',
			'url' => $data['spreadsheetUrl'] ?? '',
			'sheets' => [],
		];

		if ( isset( $data['sheets'] ) ) {
			foreach ( $data['sheets'] as $sheet ) {
				$properties = $sheet['properties'];
				$metadata['sheets'][] = [
					'id' => $properties['sheetId'],
					'title' => $properties['title'],
					'index' => $properties['index'],
				];
			}
		}

		return $metadata;
	}

	/**
	 * Get sheet data
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $range Range (e.g., 'Sheet1!A1:Z100')
	 * @return array|false
	 */
	public function get_sheet_data( $spreadsheet_id, $range ) {
		$access_token = $this->auth->get_access_token();

		if ( ! $access_token ) {
			return false;
		}

		$url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheet_id}/values/" . \urlencode( $range );

		$response = \wp_remote_get( $url, [
			'headers' => [
				'Authorization' => 'Bearer ' . $access_token,
			],
			'timeout' => 30,
		] );

		if ( \is_wp_error( $response ) ) {
			return false;
		}

		$response_code = \wp_remote_retrieve_response_code( $response );
		if ( $response_code !== 200 ) {
			return false;
		}

		$response_body = \wp_remote_retrieve_body( $response );
		$data = \json_decode( $response_body, true );

		return $data['values'] ?? [];
	}

	/**
	 * Update sheet data
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $range Range (e.g., 'Sheet1!A1:Z100')
	 * @param array  $values Values to update
	 * @return bool
	 */
	public function update_sheet_data( $spreadsheet_id, $range, $values ) {
		$access_token = $this->auth->get_access_token();

		if ( ! $access_token ) {
			return false;
		}

		$url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheet_id}/values/" . \urlencode( $range ) . '?valueInputOption=USER_ENTERED';

		$response = \wp_remote_request( $url, [
			'method' => 'PUT',
			'headers' => [
				'Authorization' => 'Bearer ' . $access_token,
				'Content-Type' => 'application/json',
			],
			'body' => \json_encode( [
				'values' => $values,
			] ),
			'timeout' => 30,
		] );

		if ( \is_wp_error( $response ) ) {
			return false;
		}

		$response_code = \wp_remote_retrieve_response_code( $response );
		return $response_code === 200;
	}

	/**
	 * Append data to sheet
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $range Range (e.g., 'Sheet1!A:Z')
	 * @param array  $values Values to append
	 * @return bool
	 */
	public function append_to_sheet( $spreadsheet_id, $range, $values ) {
		$access_token = $this->auth->get_access_token();

		if ( ! $access_token ) {
			return false;
		}

		$url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheet_id}/values/" . \urlencode( $range ) . ':append?valueInputOption=USER_ENTERED';

		$response = \wp_remote_post( $url, [
			'headers' => [
				'Authorization' => 'Bearer ' . $access_token,
				'Content-Type' => 'application/json',
			],
			'body' => \json_encode( [
				'values' => $values,
			] ),
			'timeout' => 30,
		] );

		if ( \is_wp_error( $response ) ) {
			return false;
		}

		$response_code = \wp_remote_retrieve_response_code( $response );
		return $response_code === 200;
	}

	/**
	 * Clear sheet range
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $range Range to clear
	 * @return bool
	 */
	public function clear_sheet_range( $spreadsheet_id, $range ) {
		$access_token = $this->auth->get_access_token();

		if ( ! $access_token ) {
			return false;
		}

		$url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheet_id}/values/" . \urlencode( $range ) . ':clear';

		$response = \wp_remote_post( $url, [
			'headers' => [
				'Authorization' => 'Bearer ' . $access_token,
				'Content-Type' => 'application/json',
			],
			'timeout' => 30,
		] );

		if ( \is_wp_error( $response ) ) {
			return false;
		}

		$response_code = \wp_remote_retrieve_response_code( $response );
		return $response_code === 200;
	}

	/**
	 * Initialize sheet with headers
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $sheet_name Sheet name
	 * @param array  $headers Headers array
	 * @return bool
	 */
	public function initialize_sheet_headers( $spreadsheet_id, $sheet_name, $headers ) {
		$range = $sheet_name . '!A1:' . $this->get_column_letter( count( $headers ) ) . '1';
		return $this->update_sheet_data( $spreadsheet_id, $range, [ $headers ] );
	}

	/**
	 * Get column letter from number
	 *
	 * @param int $column_number Column number (1-based)
	 * @return string
	 */
	private function get_column_letter( $column_number ) {
		$letter = '';
		while ( $column_number > 0 ) {
			$column_number--;
			$letter = chr( 65 + ( $column_number % 26 ) ) . $letter;
			$column_number = intval( $column_number / 26 );
		}
		return $letter;
	}

	/**
	 * Extract spreadsheet ID from URL
	 *
	 * @param string $url Google Sheets URL
	 * @return string|false
	 */
	public static function extract_spreadsheet_id( $url ) {
		if ( preg_match( '/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/', $url, $matches ) ) {
			return $matches[1];
		}
		return false;
	}
}
