<?php
/**
 * Google Sheets Customer Sync Manager
 *
 * @package ShopExplorer\GoogleSheets
 * @since 1.0.0
 */

namespace SHOPEXPLORER\GoogleSheets;

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

/**
 * Customer Sync Manager class
 *
 * Handles syncing WooCommerce customers to Google Sheets
 *
 * @since 1.0.0
 */
class SHOPEX_CustomerSyncManager {

	/**
	 * Service Account Auth instance
	 *
	 * @var ServiceAccountAuth
	 */
	private $auth_manager;

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

	/**
	 * Get available customer fields for syncing
	 *
	 * @return array
	 */
	public function get_available_fields() {
		$fields = [
			'customer_id' => [
				'label' => 'Customer ID',
				'type' => 'core',
				'enabled' => true, // Always enabled
			],
			'username' => [
				'label' => 'Username',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_username', true ),
			],
			'email' => [
				'label' => 'Email',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_email', true ),
			],
			'first_name' => [
				'label' => 'First Name',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_first_name', true ),
			],
			'last_name' => [
				'label' => 'Last Name',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_last_name', true ),
			],
			'phone' => [
				'label' => 'Phone',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_phone', true ),
			],
			'billing_address' => [
				'label' => 'Billing Address',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_billing_address', false ),
			],
			'shipping_address' => [
				'label' => 'Shipping Address',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_shipping_address', false ),
			],
			'total_orders' => [
				'label' => 'Total Orders',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_total_orders', true ),
			],
			'total_spent' => [
				'label' => 'Total Spent',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_total_spent', true ),
			],
			'date_registered' => [
				'label' => 'Date Registered',
				'type' => 'core',
				'enabled' => (bool) get_option( 'shopex_sync_customer_date_registered', false ),
			],
		];

		return $fields;
	}

	/**
	 * Get current field settings
	 *
	 * @return array
	 */
	public function get_field_settings() {
		try {
			return $this->get_available_fields();
		} catch ( \Exception $e ) {
			error_log( 'Error getting customer sync fields: ' . $e->getMessage() );
			return [];
		}
	}

	/**
	 * Update field settings
	 *
	 * @param array $field_settings Field settings
	 * @return bool
	 */
	public function update_field_settings( $field_settings ) {
		$available_fields = $this->get_available_fields();

		foreach ( $field_settings as $field_key => $enabled ) {
			if ( isset( $available_fields[ $field_key ] ) && $field_key !== 'customer_id' ) {
				update_option( 'shopex_sync_customer_' . $field_key, (bool) $enabled );
			}
		}

		return true;
	}

	/**
	 * Get enabled fields only
	 *
	 * @return array
	 */
	public function get_enabled_fields() {
		$fields = $this->get_available_fields();
		return array_filter( $fields, function ( $field ) {
			return $field['enabled'];
		});
	}

	/**
	 * Get column headers for Google Sheets
	 *
	 * @return array
	 */
	public function get_column_headers() {
		$enabled_fields = $this->get_enabled_fields();
		return array_column( $enabled_fields, 'label' );
	}

	/**
	 * Get all customers data for syncing
	 *
	 * @param array $args Query arguments
	 * @return array
	 */
	public function get_customers_data( $args = [] ) {
		$default_args = [
			'number' => -1,
			'orderby' => 'ID',
			'order' => 'ASC',
		];

		$args = wp_parse_args( $args, $default_args );

		$customers = get_users( $args );
		$customers_data = [];

		foreach ( $customers as $customer ) {
			$customers_data[] = $this->format_customer_data( $customer );
		}

		return $customers_data;
	}

	/**
	 * Format single customer data
	 *
	 * @param \WP_User $customer WordPress user object
	 * @return array
	 */
	public function format_customer_data( $customer ) {
		$enabled_fields = $this->get_enabled_fields();
		$customer_data = [];
		$wc_customer = new \WC_Customer( $customer->ID );

		foreach ( array_keys( $enabled_fields ) as $field_key ) {
			switch ( $field_key ) {
				case 'customer_id':
					$customer_data[] = $customer->ID;
					break;

				case 'username':
					$customer_data[] = $customer->user_login;
					break;

				case 'email':
					$customer_data[] = $customer->user_email;
					break;

				case 'first_name':
					$customer_data[] = $wc_customer->get_first_name();
					break;

				case 'last_name':
					$customer_data[] = $wc_customer->get_last_name();
					break;

				case 'phone':
					$customer_data[] = $wc_customer->get_billing_phone();
					break;

				case 'billing_address':
					$billing = sprintf(
						'%s, %s, %s %s, %s',
						$wc_customer->get_billing_address_1(),
						$wc_customer->get_billing_city(),
						$wc_customer->get_billing_state(),
						$wc_customer->get_billing_postcode(),
						$wc_customer->get_billing_country()
					);
					$customer_data[] = $billing;
					break;

				case 'shipping_address':
					$shipping = sprintf(
						'%s, %s, %s %s, %s',
						$wc_customer->get_shipping_address_1(),
						$wc_customer->get_shipping_city(),
						$wc_customer->get_shipping_state(),
						$wc_customer->get_shipping_postcode(),
						$wc_customer->get_shipping_country()
					);
					$customer_data[] = $shipping;
					break;

				case 'total_orders':
					$customer_data[] = $wc_customer->get_order_count();
					break;

				case 'total_spent':
					$customer_data[] = $wc_customer->get_total_spent();
					break;

				case 'date_registered':
					$customer_data[] = $customer->user_registered;
					break;

				default:
					$customer_data[] = '';
					break;
			}
		}

		return $customer_data;
	}

	/**
	 * Sync all customers to Google Sheets
	 *
	 * @param string $spreadsheet_id Google Sheets spreadsheet ID
	 * @param string $sheet_name Sheet name/tab
	 * @return array Result with success status and message
	 */
	public function sync_all_customers( $spreadsheet_id, $sheet_name = 'Customers' ) {
		try {
			if ( ! $this->auth_manager->has_credentials() ) {
				return [
					'success' => false,
					'message' => 'Google Sheets credentials not configured.',
				];
			}

			// Get access token
			$access_token = $this->auth_manager->get_access_token();
			if ( ! $access_token ) {
				return [
					'success' => false,
					'message' => 'Failed to get access token.',
				];
			}

			// Get customers data
			$customers_data = $this->get_customers_data();
			if ( empty( $customers_data ) ) {
				return [
					'success' => false,
					'message' => 'No customers found to sync.',
				];
			}

			// Prepare data with headers
			$headers = $this->get_column_headers();
			$sheet_data = array_merge( [ $headers ], $customers_data );

			// Clear existing data and add new data
			$this->clear_sheet( $access_token, $spreadsheet_id, $sheet_name );
			$result = $this->write_to_sheet( $access_token, $spreadsheet_id, $sheet_name, $sheet_data );

			if ( $result ) {
				return [
					'success' => true,
					'message' => sprintf( 'Successfully synced %d customers to Google Sheets.', count( $customers_data ) ),
					'synced_count' => count( $customers_data ),
				];
			} else {
				return [
					'success' => false,
					'message' => 'Failed to sync customers.',
				];
			}
		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => 'Failed to sync customers.',
			];
		}
	}

	/**
	 * Clear sheet data
	 *
	 * @param string $access_token Access token
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $sheet_name Sheet name
	 * @return bool
	 */
	private function clear_sheet( $access_token, $spreadsheet_id, $sheet_name ) {
		$api_url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheet_id}/values/{$sheet_name}:clear";

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

		return ! \is_wp_error( $response ) && \wp_remote_retrieve_response_code( $response ) === 200;
	}

	/**
	 * Write data to sheet
	 *
	 * @param string $access_token Access token
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $sheet_name Sheet name
	 * @param array  $data Data to write
	 * @return bool
	 */
	private function write_to_sheet( $access_token, $spreadsheet_id, $sheet_name, $data ) {
		$api_url = "https://sheets.googleapis.com/v4/spreadsheets/{$spreadsheet_id}/values/{$sheet_name}?valueInputOption=USER_ENTERED";

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

		return ! \is_wp_error( $response ) && \wp_remote_retrieve_response_code( $response ) === 200;
	}
}
