<?php

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

class AIEO_SEO_Image {

	
	public static function alt_text( $title, $brand = '' ) {
		$title = trim( (string) $title );
		$fmt   = '';
		if ( class_exists( 'AIEO_DMM_Settings' ) ) {
			$fmt = (string) AIEO_DMM_Settings::get( 'seo.image_alt_format', '' );
		}
		if ( '' === trim( $fmt ) ) {
			return $title; 
		}
		$sep  = class_exists( 'AIEO_DMM_Settings' ) ? (string) AIEO_DMM_Settings::get( 'seo.separator', '-' ) : '-';
		$site = (string) get_bloginfo( 'name' );
		$out  = strtr( $fmt, array(
			'#product_title' => $title,
			'#title'         => $title,
			'#brand'         => (string) $brand,
			'#separator_sa'  => $sep,
			'#separator'     => $sep,
			'#site_title'    => $site,
		) );
		
		$out = preg_replace( '/\s*' . preg_quote( $sep, '/' ) . '\s*' . preg_quote( $sep, '/' ) . '\s*/u', ' ' . $sep . ' ', $out );
		$out = trim( preg_replace( '/\s{2,}/u', ' ', $out ) );
		$out = trim( $out, " \t\n\r\0\x0B" . $sep );
		return '' !== $out ? $out : $title;
	}

	
	public static function backfill_alt( $limit = 200 ) {
		global $wpdb;
		$limit = max( 1, min( 2000, (int) $limit ) );
		
		
		$rows = $wpdb->get_results( $wpdb->prepare(
			"SELECT p.ID AS product_id, p.post_title AS title, tid.meta_value AS thumb_id
			 FROM {$wpdb->posts} p
			 INNER JOIN {$wpdb->postmeta} tid ON tid.post_id = p.ID AND tid.meta_key = '_thumbnail_id' AND tid.meta_value <> ''
			 LEFT JOIN {$wpdb->postmeta} alt ON alt.post_id = tid.meta_value AND alt.meta_key = '_wp_attachment_image_alt'
			 WHERE p.post_type = 'product' AND p.post_status = 'publish'
			   AND ( alt.meta_value IS NULL OR alt.meta_value = '' )
			 LIMIT %d",
			$limit
		) );
		if ( empty( $rows ) ) {
			return 0;
		}
		$written = 0;
		foreach ( $rows as $r ) {
			$thumb = (int) $r->thumb_id;
			if ( $thumb <= 0 ) {
				continue;
			}
			$brand = '';
			$terms = get_the_terms( (int) $r->product_id, 'product_brand' );
			if ( $terms && ! is_wp_error( $terms ) ) {
				$brand = (string) $terms[0]->name;
			}
			$alt = self::alt_text( $r->title, $brand );
			if ( '' === $alt ) {
				continue;
			}
			update_post_meta( $thumb, '_wp_attachment_image_alt', $alt );
			if ( class_exists( 'AIEO_SEO_Store' ) ) {
				AIEO_SEO_Store::save( 'product', (int) $r->product_id, array( 'image_alt' => $alt ) );
			}
			$written++;
		}
		return $written;
	}

	
	public static function image_url_for_product( $product_id ) {
		$thumb = get_post_thumbnail_id( (int) $product_id );
		if ( ! $thumb ) {
			return '';
		}
		$src = wp_get_attachment_image_url( (int) $thumb, 'full' );
		return $src ? (string) $src : '';
	}
}
