<?php
 
 /**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Extra Functions for Blue Raven 
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - BUILD PRODUCT LIST
 * ||   - IMAGES
 * ||   - CREATE ROWS
 * || 
 * =============================================================================
 */

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

/*
============================================================
    BUILD PRODUCT LIST
============================================================
*/

    /**
     * Builds a product list HTML output for given WooCommerce product IDs
     * 
     * @param array|string $ids Single product ID (in 'id:123' format) or array of product IDs
     * @return void Outputs HTML directly
     */
     
function BlueRaven_build_product_list($ids) {
        
    ## =========== Ensure we have WooCommerce active =========== ##
    
    if (!function_exists('wc_get_product')) {
        error_log('WooCommerce is not active in BlueRaven_build_product_list()');
        return;
    }
    
    ## =========== Normalize input to array =========== ##
    
    if (empty($ids)) return;
    
    $ids = explode(',', $ids);
    $input_ids = is_array($ids) ? $ids : array($ids);
    
    $product_ids = array_map(function($item) {
        if (is_string($item) && strpos(trim($item), 'id:') === 0) $item = substr(trim($item), 3);
        $item = absint($item);
        return $item;
    }, $input_ids);
    
    ## =========== Filter out any invalid (zero or negative) IDs =========== ##
    
    $product_ids = array_filter($product_ids, function($id) { return $id > 0; });
    
    ## =========== No valid IDs? Bail early =========== ##

    if (empty($product_ids)) return;
   
    ## =========== Loop through each ID =========== ##
    
    $remove_icon = esc_html('❌');
    
    foreach ($product_ids as $product_id) {
        $product = wc_get_product($product_id);
    
    ## =========== Skip if product doesn't exist or isn't accessible =========== ##
    
        if (!$product || !$product->is_visible()) continue;
    
    ## =========== Escape all output =========== ##
    
        $escaped_id = esc_attr($product_id);
        $escaped_name = esc_html($product->get_name());
        
        if($escaped_id != '' && $escaped_name != ''){
    
    ## =========== Use printf for safer output with placeholders =========== ##
    
           printf(
				'<div class="br-block-item br-tag-item flex-sb blue-tag" style="min-width: 3rem; margin: 0.25rem;">
					<p data-id="%s" class="spacing-right-small">%s</p>
					<span class="br-block-remove remove-tag" style="padding-top: 0.1rem;" aria-label="%s">%s</span>
				</div>',
				esc_attr($escaped_id),
				esc_html($escaped_name),
				esc_attr__('Remove product', 'blue-raven'),
				wp_kses_post($remove_icon)
			);
        }
    }
}

/*
============================================================
    IMAGES
============================================================
*/

    /**
     * Builds an HTML list of images with edit controls.
     *
     * @param string $csv_urls Comma-separated list of image URLs.
     * @return string HTML output of image blocks.
     */
     
function BlueRaven_build_image_list( $Image_urls ) {
    
    if ( empty( $Image_urls ) ) { return ''; }
    
    $urls = array_map( 'trim', explode( ',', $Image_urls ) );
    $output = '';
    $first_image = true;

    foreach ( $urls as $url ) {
        $src = esc_url( $url );

        if (empty(attachment_url_to_postid($src))) {$src = BLUERAVEN_PLUGIN_URL . 'assets/media/blue_raven_place_holder.webp';}
    
    ## =========== Get attachment ID from URL =========== ##
 
        $attachment_id = attachment_url_to_postid( $src );
        $alt = $attachment_id ? get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) : '';
        $alt = $alt ? esc_attr( $alt ) : '';
        $checkbox_id = 'star-thumbnail-' . wp_generate_uuid4() . '-' . time();

        ob_start();
        ?>
        <div style="margin: 2rem 0rem 1rem 0rem;" class="image-block">
            <div class="flex-sb">
                <div class="spacing-right">
                    <img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr($alt); ?>" width="150" height="auto" style="cursor: pointer;" class="media-post-image">
                </div>
                <div class='image-metas'>
                    <div class="flex-sb">
                        <div style="align-content: center; height: 2.5rem;">
                            <input type="checkbox" id="<?php echo esc_attr($checkbox_id); ?>" class="br-star-checkbox" name="star-thumbnail" <?php echo $first_image ? 'checked' : ''; ?>>
							<label for="<?php echo esc_attr($checkbox_id); ?>" class="br-star-label">★</label>
                        </div>    
                        <button type="button" class="remove-image-block text-button" style="align-self: flex-start;">❌</button>
                    </div>
                    <div class="flex-sb spacing-bottom" style="width: 100%">
                        <label class="text-center"><h4 class="no-margin-padding spacing-right-small text-center"><?php esc_html_e( 'Alt Text', 'blue-raven' ); ?></h4></label>
                        <input type="text" name="alt-text" placeholder="<?php esc_attr_e( 'Enter alternative text', 'blue-raven' ); ?>" class="br-input media-post-image-alt" style="width: 85%" value="<?php echo esc_attr( $alt ); ?>">
                        <button class="enterra-button save-alt-text" style="margin-left: 1rem;"><?php esc_html_e( 'Save', 'blue-raven' ); ?></button>
                    </div>
                </div>
            </div>
        </div>
        <?php
        $output .= ob_get_clean();

        $first_image = false;
    }
    return $output;
}
            
/*
============================================================
    CREATE ROWS
============================================================
*/

    /**
     * Creates HTML rows for product variations
     *
     * @param int    $pid  Product ID
     * @param string $att  JSON string of product attributes
     * @return string      Generated HTML
     */
     
function BlueRaven_create_rows( $pid, $att ) {

    try{
        global $wpdb;

        $pid = absint( $pid );
        if (!is_numeric($pid) || empty($att)) return '';

        $table_name = $wpdb->prefix . 'BlueRavenProducts';
        $pid = absint( $pid );
            
    ## =========== Get existing variations CSV from database =========== ##
    
        $existing_csv = $wpdb->get_var($wpdb->prepare("SELECT variations_CSV FROM $table_name WHERE ID = %d",$pid));

    ## =========== Parse the CSV data =========== ## 
    
        if ($existing_csv == null || $existing_csv == '') return '';
        if (empty($rows = array_map('str_getcsv', explode("\n", $existing_csv)))) return '';
        if (!is_array($header = array_shift($rows))) return '';
        
        $variations = array();
        foreach ($rows as $row) {if (is_array($row) && count($row) === count($header)) $variations[] = array_combine($header, $row);}
        if ($variations == []) return '';
        
    ## =========== Decode attributes JSON =========== ##
    
        $attributes_data = json_decode(stripslashes($att), true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($attributes_data)) { return ''; }
        $attribute_count = count($attributes_data);
         
    ## =========== Generate HTML for each variation =========== ##       
    
        $html = '<script>document.getElementById("variations-list-table").style.display = "block";</script>';
        
        foreach ( $variations as $index => $variation ) {
            $variation_number = $index + 1;
            $vID = $variation['ID'] === '' ? $variation_number : $variation['ID'];
            $html .= '<tr data-id="'.$vID.'">';
            $html .= sprintf(
                '<td style="align-content: baseline; padding-top: 1.2rem;"><input type="hidden" name="variation[%d][id]" value="%d">#%d</td><td>',
                $variation_number,
                $variation_number,
                $variation_number
            );
              
    ## =========== Add attribute dropdowns =========== ##
    
            for ( $i = 1; $i <= $attribute_count; $i++ ) {
                $name_key = "Attribute $i name";
                $value_key = "Attribute $i value(s)";
                $used_for_variations_key = "Attribute $i used_for_variations";
                
                if (!isset($variation[$name_key], $variation[$value_key]) || (isset($variation[$used_for_variations_key]) && !$variation[$used_for_variations_key])) continue;
                
                $attr_name = $variation[ $name_key ];
                $attr_value = $variation[ $value_key ];
                
                $html .= '<div class="flex-left">';
                $html .= sprintf(
                    '<label for="variation_%d_%s" class="text-center" style="width:10rem;"><p class="no-margin-padding spacing-right-small text-center">%s</p></label>',
                    $variation_number,
                    sanitize_title( $attr_name ),
                    esc_html( $attr_name )
                );
                
                $html .= sprintf(
                    '<select name="variation[%d][attributes][%s]" class="variation-attribute-dropdown br-dropdown" style="width: 30rem; padding: 0.5rem; margin-right: 1rem" disabled>',
                    $variation_number,
                    esc_attr( $attr_name )
                );
                    
    ## =========== Find matching attribute values =========== ##                  
    
                foreach ( $attributes_data as $item ) {
                    
                    if ( isset( $item['name'] ) && strtolower( $item['name'] ) === strtolower( $attr_name ) && ! empty( $item['values'] ) ) {
                        foreach ( $item['values'] as $value ) {
                            $selected = selected( $attr_value, $value, false );
                            $html .= sprintf(
                                '<option value="%s" %s>%s</option>',
                                esc_attr( $value ),
                                $selected,
                                esc_html( $value )
                            ); 
                        }
                        break;
                    }
                }
                
                $html .= '</select></div><br>';
            }
                
    ## =========== Add action buttons =========== ##              
    
            $html .= sprintf(
                '</td><td style="align-content: baseline;"><a type="button" class="edit-variation text-button" data-row-index="%d">%s</a></td>',
                $variation_number,
                esc_html__( 'Edit', 'blue-raven' )
            );
            
            $html .= sprintf(
                '<td style="align-content: baseline;"><button type="button" class="remove-variation text-button" data-row-index="%d">❌</button></td></tr>',
                $variation_number
            );
        }
        
        return $html;
        
    } catch (Exception $e) {
        BlueRaven_SendError("ERROR", "blue-raven/includes/extras/my-product-extras.php", "LOAD error", $e->getMessage());
        return false;
    }
}
        