<?php
/**
 * Cloud site identity.
 *
 * @package SubmissionInbox
 */

namespace SUBIN\Cloud;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Stores a stable local identity for future Cloud connections.
 */
class SiteIdentity {
	const OPTION_KEY = 'subin_site_identity';

	/**
	 * Get or create identity.
	 *
	 * @return array<string,string>
	 */
	public function get() {
		$identity = get_option( self::OPTION_KEY, array() );
		if ( ! is_array( $identity ) ) {
			$identity = array();
		}

		if ( empty( $identity['site_uuid'] ) ) {
			$identity = array(
				'site_uuid'         => wp_generate_uuid4(),
				'created_at'        => current_time( 'mysql' ),
				'connection_status' => 'disconnected',
			);
			update_option( self::OPTION_KEY, $identity, false );
		}

		return array(
			'site_uuid'         => sanitize_text_field( (string) ( $identity['site_uuid'] ?? '' ) ),
			'created_at'        => sanitize_text_field( (string) ( $identity['created_at'] ?? '' ) ),
			'connection_status' => sanitize_key( (string) ( $identity['connection_status'] ?? 'disconnected' ) ),
		);
	}

	/**
	 * Update connection status.
	 *
	 * @param string $status Status.
	 * @return void
	 */
	public function update_connection_status( $status ) {
		$identity = $this->get();
		$status   = sanitize_key( (string) $status );
		if ( ! in_array( $status, array( 'connected', 'disconnected', 'error' ), true ) ) {
			$status = 'disconnected';
		}

		$identity['connection_status'] = $status;
		update_option( self::OPTION_KEY, $identity, false );
	}
}
