<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Sifency_Addons_Prebuild_Website {
	private $api_list_url = 'https://data-delta-five.vercel.app/data/library.json';
	public function render() {
		if ( isset( $_GET['force_refresh'] ) ) {
			delete_transient( 'sifency_lib_cache_v2' );
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Data Synced Successfully!', 'sifency-addons' ) . '</p></div>';
		}
		$is_sync_state_unlocked = class_exists( 'Sifency_Addons_Theme_Builder_Master' )
			? Sifency_Addons_Theme_Builder_Master::sync_environment_state()
			: false;
		$templates              = $this->get_remote_templates();

		if ( empty( $templates ) ) {
			$refresh_url = add_query_arg( 'force_refresh', 'true' );
			echo '<div class="notice notice-warning"><p>' . esc_html__( 'Failed to load library data.', 'sifency-addons' ) . ' <a href="' . esc_url( $refresh_url ) . '">Try Refreshing</a></p></div>';
			return;
		}
		$categories = array();
		foreach ( $templates as $t ) {
			if ( ! empty( $t['category'] ) ) {
				$categories[] = ucfirst( $t['category'] );
			}
		}
		$categories = array_unique( $categories );
		sort( $categories );
		array_unshift( $categories, 'All' );

		$current_url  = remove_query_arg( 'force_refresh' );
		$refresh_link = add_query_arg( 'force_refresh', 'true', $current_url );

		?>
		<div class="sifency-dashboard-layout">
			<div class="sifency-dashboard-nav">
				<?php foreach ( $categories as $index => $cat ) : ?>
				<button class="sifency-nav-item sifency-admin-btn <?php echo ( 0 === $index ) ? 'active' : ''; ?>"
					data-cat="<?php echo esc_attr( strtolower( $cat ) ); ?>">
					<?php echo esc_html( $cat ); ?>
				</button>
				<?php endforeach; ?>
			</div>
			<div class="sifency-admin-content prebuild">
				<div class="sifency-demo-header">
				<div class="sifency-header-area">
					<h2>Template Library</h2>
				</div>

				<div class="sifency-filter-bar">
					<div class="sifency-type-nav">
						<button class="sifency-admin-btn text_underline_animation sifency-type-btn active" data-type="all"><span> All Items </span></button>
						<button class="sifency-admin-btn text_underline_animation sifency-type-btn" data-type="block"><span> Blocks </span></button>
						<button class="sifency-admin-btn text_underline_animation sifency-type-btn" data-type="page"><span> Pages </span></button>
						<button class="sifency-admin-btn text_underline_animation sifency-type-btn" data-type="websites"><span> Websites </span></button>
					</div>
					<a href="<?php echo esc_url( $refresh_link ); ?>" class="sifency-admin-btn text_underline_animation sifency-demo-link">
					   <span>Sync Data</span>
					</a>
					<div class="sifency-search-box">
						<input type="text" id="sifency-admin-search" placeholder="Search...">
					</div>
				</div>
				</div>
			<div class="sifency-theme-grid prebuild" id="sifency-admin-grid">
			<?php
			foreach ( $templates as $item ) :
				$title = esc_html( $item['title'] );
				$image = esc_url( $item['image'] );
				$type  = esc_attr( $item['type'] );
				$cat   = esc_attr( strtolower( $item['category'] ) );

				// Optional Data
				$live_url = ! empty( $item['live_url'] ) ? esc_url( $item['live_url'] ) : '';
				$price    = isset( $item['price'] ) ? $item['price'] : 'Free';
				$buy_link = ! empty( $item['buy_link'] ) ? esc_url( $item['buy_link'] ) : '';

				$badges_html = '';
				if ( ! $is_sync_state_unlocked || ( $is_sync_state_unlocked && $price !== 'Free' ) ) {
					$badges_html .= '<span class="sifency-badge badge-pro">PRO</span>';
				}
				$badges_html .= '<span class="sifency-badge badge-price">' . esc_html( $price ) . '</span>';

				$allowed_badge_html = array(
					'span' => array(
						'class' => true,
					),
				);

				$allowed_footer_html = array(
					'a'    => array(
						'href'   => true,
						'target' => true,
						'class'  => true,
					),
					'span' => array(
						'class' => true,
					),
				);

				$footer_html = '';
				if ( ! $is_sync_state_unlocked ) {
					$footer_html = '<a href="https://sifency.com/sifency-addons/pricing" target="_blank"
                        class="sifency-upgrade-btn">
                        <span class="dashicons dashicons-lock"></span> Upgrade to Pro
                    </a>';
				} else {
					if ( ! empty( $price ) && $price !== 'Free' ) {
						$purchase_url = ! empty( $buy_link ) ? $buy_link : '#';
						$footer_html  = sprintf(
							'<a href="%s" target="_blank" class="sifency-purchase-btn sifency-admin-btn sifency-upgrade-btn">
                               </span> Purchase - %s
                            </a>',
							esc_url( $purchase_url ),
							esc_html( $price )
						);

					} else {
						$footer_html = '<span class="sifency-status-text sifency-badge include">
                            Available
                        </span>';

					}
				}
				?>
				<div class="sifency-theme-card"
					data-type="<?php echo esc_attr( $type ); ?>"
					data-cat="<?php echo esc_attr( $cat ); ?>"
					data-title="<?php echo esc_attr( strtolower( $title ) ); ?>">
					<div class="sifency-theme-thumb">
						<div class="sifency-pro-badge sifency-theme-pro-badge">
							<?php echo wp_kses( $badges_html, $allowed_badge_html ); ?>
						</div>
						<img src="<?php echo esc_url( $image ); ?>" alt="<?php echo esc_attr( $title ); ?>">
						<?php if ( $live_url ) : ?>
							<div class="sifency-theme-hover">
								<a href="<?php echo esc_url( $live_url ); ?>" target="_blank"
									class="sifency-preview-link sifency-admin-btn text_underline_animation sifency-demo-link">
									<span>Live Preview</span>
								</a>
							</div>
						<?php endif; ?>
					</div>

					<div class="sifency-theme-info">
						<h3 class="sifency-theme-title"><?php echo esc_html( $title ); ?></h3>

						<div class="sifency-card-footer">
							<?php echo wp_kses( $footer_html, $allowed_footer_html ); ?>
						</div>
					</div>

				</div>

			<?php endforeach; ?>

			</div>
			</div>
		</div>
		<?php
	}
	private function get_remote_templates() {

		$cache_key = 'sifency_lib_cache_v2';

		$cached = get_transient( $cache_key );
		if ( $cached !== false && is_array( $cached ) ) {
			return $cached;
		}

		$response = wp_remote_get(
			$this->api_list_url,
			array(
				'timeout'     => 4,
				'redirection' => 3,
				'sslverify'   => true,
				'headers'     => array(
					'Accept' => 'application/json',
				),
			)
		);

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

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

		$body = wp_remote_retrieve_body( $response );
		if ( empty( $body ) ) {
			return false;
		}

		$data = json_decode( $body, true );

		if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $data ) ) {
			return false;
		}
		set_transient( $cache_key, $data, 12 * HOUR_IN_SECONDS );

		return $data;
	}
}
