<?php
/**
 * Connection service class.
 *
 * Handles API key encryption, validation against the API, and storage.
 *
 * @package    100Prints
 */

class Hundred_Prints_Connection_Service {

	/**
	 * Verify and store the API Secret Key.
	 *
	 * @param string $raw_key The raw API key from user input.
	 * @return bool True if validated and stored, false otherwise.
	 */
	public function store_key( $raw_key ) {
		if ( empty( $raw_key ) ) {
			return false;
		}

		$workspace_info = $this->verify_key_against_api( $raw_key );
		if ( ! $workspace_info ) {
			return false;
		}

		// Encrypt key
		$encrypted_key = hundred_prints_encrypt( $raw_key );
		if ( empty( $encrypted_key ) ) {
			return false;
		}

		// Save key
		update_option( '100prints_api_key', $encrypted_key );

		// Save workspace information
		update_option( '100p_workspace_info', $workspace_info );
		
		// Flush template cache
		delete_option( '100p_template_index' );

		return true;
	}

	/**
	 * Get the decrypted API key.
	 *
	 * @return string|null The decrypted API key, or null if not set.
	 */
	public function get_key() {
		$encrypted_key = get_option( '100prints_api_key' );
		if ( empty( $encrypted_key ) ) {
			return null;
		}

		return hundred_prints_decrypt( $encrypted_key );
	}

	/**
	 * Check if the plugin is connected.
	 *
	 * @return bool True if connected, false otherwise.
	 */
	public function is_connected() {
		$key = $this->get_key();
		return ! empty( $key );
	}

	/**
	 * Fetch stored workspace info.
	 *
	 * @return array|null Workspace meta array or null.
	 */
	public function get_workspace_info() {
		return get_option( '100p_workspace_info', null );
	}

	/**
	 * Disconnect the account, clearing keys and synced template metadata.
	 */
	public function disconnect() {
		delete_option( '100prints_api_key' );
		delete_option( '100p_workspace_info' );
		delete_option( '100p_template_index' );

		// Delete cached templates
		global $wpdb;
		$options = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s",
				'100p_template_cache_%'
			)
		);
		if ( ! empty( $options ) ) {
			foreach ( $options as $opt ) {
				delete_option( $opt );
			}
		}
	}

	/**
	 * Get the base API URL.
	 */
	public function get_api_base_url() {
		$settings = hundred_prints_get_settings();
		$url_override = isset( $settings['api_url_override'] ) ? $settings['api_url_override'] : '';

		if ( ! empty( $url_override ) ) {
			return rtrim( $url_override, '/' );
		}

		return 'https://api.100printswith.me/public/v1/wordpress';
	}

	/**
	 * Call the 100Prints API to verify the key.
	 *
	 * @param string $raw_key The raw API key to test.
	 * @return array|false Verified workspace info array or false.
	 */
	private function verify_key_against_api( $raw_key ) {
		$api_url = $this->get_api_base_url() . '/verify';

		$response = wp_remote_get( $api_url, [
			'headers' => [
				'Authorization' => 'Bearer ' . $raw_key,
				'Content-Type'  => 'application/json',
			],
			'timeout' => 15,
		] );

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

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

		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		if ( ! is_array( $data ) || ! isset( $data['plan_tier'] ) ) {
			return false;
		}

		return [
			'workspace_name'  => isset( $data['workspace_name'] ) ? sanitize_text_field( $data['workspace_name'] ) : 'My Workspace',
			'email'           => isset( $data['email'] ) ? sanitize_email( $data['email'] ) : '',
			'plan_tier'       => sanitize_key( $data['plan_tier'] ),
			'template_count'  => absint( $data['template_count'] ),
			'api_quota_used'  => absint( $data['api_quota_used'] ),
			'api_quota_limit' => absint( $data['api_quota_limit'] ),
		];
	}
}
