<?php
defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception messages go to PHP error log, never to HTML output.

/**
 * Imports recent posts from connected WordPress sites into Contentosapp Studio history.
 */
final class Costudio_Admin_Remote_Post_Sync {

	private function __construct() {
	}

	public static function sync_site_posts( string $site_key, array $cfg ): int {
		$sites_repo = function_exists( 'costudio_sites' ) ? costudio_sites() : null;
		if ( $sites_repo && ! $sites_repo->is_site_operable( $site_key ) ) {
			throw new Exception(
				empty( $cfg['active'] )
					? __( 'Site is inactive (or not configured).', 'contentosapp-studio' )
					: $sites_repo->get_unavailable_site_message()
			);
		}

		$base_url = costudio_safe_http_url( rtrim( (string) ( $cfg['url'] ?? '' ), '/' ) );
		if ( '' === $base_url ) {
			throw new Exception( __( 'Invalid or unsafe site URL.', 'contentosapp-studio' ) );
		}
		$url      = $base_url . '/wp-json/wp/v2/posts?per_page=10&status=publish';
		$user     = $cfg['user'] ?? '';
		$password = Costudio_Sites_Crypto::decrypt( $cfg['password'] ?? '' );

		$response = wp_safe_remote_get(
			$url,
			costudio_safe_remote_args(
				array(
					'timeout' => 30,
					'headers' => array( 'Authorization' => 'Basic ' . base64_encode( "{$user}:{$password}" ) ),
				)
			)
		);

		if ( is_wp_error( $response ) ) {
			throw new Exception( $response->get_error_message() );
		}

		$code = (int) wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) {
			throw new Exception( "HTTP {$code}" );
		}

		$posts = json_decode( wp_remote_retrieve_body( $response ), true );
		if ( ! is_array( $posts ) ) {
			return 0;
		}

		$count = 0;
		foreach ( $posts as $post ) {
			$wp_id = (int) $post['id'];
			$title = html_entity_decode( $post['title']['rendered'] ?? '', ENT_QUOTES, 'UTF-8' );

			if ( Costudio_Production::exists_by_post_id( $site_key, $wp_id ) ) {
				continue;
			}

			Costudio_Production::create(
				array(
					'status'      => 'completed',
					'site_key'    => $site_key,
					'title'       => $title,
					'keyword'     => '',
					'is_external' => 1,
					'wp_post_id'  => $wp_id,
					'wp_post_url' => $post['link'] ?? '',
					'created_at'  => gmdate( 'Y-m-d H:i:s', strtotime( $post['date'] ?? 'now' ) ),
				)
			);
			$count++;
		}

		return $count;
	}
}
