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

add_action( 'save_post', 'cafi_generate_featured_image', 10, 3 );

function cafi_generate_featured_image( $post_id, $post, $update ) {
    // Check if this is an auto-save, revision, or not a valid post type
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }
    
    // Check if plugin is enabled
    $options = get_option( 'cafi_settings' );
    if ( ! isset( $options['enable_plugin'] ) || ! $options['enable_plugin'] ) {
        return;
    }

    // Check Allowed Post Types
    $allowed_types = isset( $options['post_types'] ) && is_array( $options['post_types'] ) && !empty( $options['post_types'] ) ? $options['post_types'] : ['post'];
    if ( ! in_array( $post->post_type, $allowed_types ) ) {
        return;
    }

    // Prevent generation for Auto Drafts
    if ( $post->post_status === 'auto-draft' || $post->post_title === 'Auto Draft' ) {
        return;
    }

    // Check if featured image is already set
    if ( has_post_thumbnail( $post_id ) ) {
        $thumbnail_id = get_post_thumbnail_id( $post_id );
        $is_generated = get_post_meta( $thumbnail_id, '_cafi_generated', true );
        
        // If it's not generated by us, preserve it.
        if ( ! $is_generated ) {
            return;
        }
        
        // If it WAS generated by us, we want to update it (delete old, create new).
        // Check if title actually changed? For simplicity, let's regenerate to be safe/synced.
        wp_delete_attachment( $thumbnail_id, true );
    }

    // Generate Logic
    cafi_create_image_for_post( $post_id, $post->post_title );
}

function cafi_create_image_for_post( $post_id, $title ) {
    cafi_log( "Starting generation for Post ID: $post_id" );
    
    $options = get_option( 'cafi_settings' );
    
    // Default settings
    $template_file = isset( $options['template'] ) ? $options['template'] : 'default-white.png';
    $font_size = isset( $options['font_size'] ) ? intval( $options['font_size'] ) : 40;
    $font_color_hex = isset( $options['font_color'] ) ? $options['font_color'] : '#000000';
    
    // Default Logo Logic for Generator
    // Only use default if logo_url is strictly NOT SET (fresh install). 
    // If it is SET but EMPTY (user removed it), we respect that and show no logo.
    if ( ! isset( $options['logo_url'] ) ) {
        // Use default logo from admin assets
        $options['logo_url'] = CAFI_PLUGIN_URL . 'admin/assets/images/logo.png';
    }
    // If set and empty, it stays empty -> no watermark.
    
    // Ensure hex has hash
    if ( strpos( $font_color_hex, '#' ) !== 0 ) {
        $font_color_hex = '#' . $font_color_hex;
    }
    
    cafi_log( "Settings - Template: $template_file, Size: $font_size, Color: $font_color_hex" );

    require_once CAFI_PLUGIN_DIR . 'includes/helpers.php'; // Ensure helpers loaded

    // Resolve Template Configuration
    $is_solid_color = false;
    $solid_hex = '#FFFFFF';
    
    $is_gradient = false;
    $grad_data = '';
    
    $custom_template_path = '';
    
    if ( function_exists( 'cafi_get_current_template_data' ) ) {
        $tmpl_data = cafi_get_current_template_data( $options );
        
        if ( $tmpl_data['type'] === 'color' ) {
            $is_solid_color = true;
            $solid_hex = $tmpl_data['value'];
        } elseif ( $tmpl_data['type'] === 'gradient' ) {
            $is_gradient = true;
            $grad_data = $tmpl_data['value'];
        } elseif ( $tmpl_data['type'] === 'image' || $tmpl_data['type'] === 'file' ) {
            // Resolve File Path from URL
            $file_url = $tmpl_data['value'];
            // Convert URL to Path
            $upload_dir_info = wp_upload_dir();
            $base_url = $upload_dir_info['baseurl'];
            $base_path = $upload_dir_info['basedir'];
            
            // Try standard WP uploads first
            $path = str_replace( $base_url, $base_path, $file_url );
            
            // If that fails (plugin assets), try Plugin logic
            if ( strpos($file_url, CAFI_PLUGIN_URL) !== false ) {
                $path = str_replace( CAFI_PLUGIN_URL, CAFI_PLUGIN_DIR, $file_url );
            }
            
            $custom_template_path = $path;
        }
    }

    // Target Dimensions: 1200x628
    $target_width = 1200;
    $target_height = 628;
    
    if ( $is_solid_color ) {
        // Create Solid Color Background
        $im = imagecreatetruecolor( $target_width, $target_height );
        
        // Parse Hex
        $hex = ltrim( $solid_hex, '#' );
        if ( strlen( $hex ) == 3 ) {
            $r = hexdec( substr( $hex, 0, 1 ) . substr( $hex, 0, 1 ) );
            $g = hexdec( substr( $hex, 1, 1 ) . substr( $hex, 1, 1 ) );
            $b = hexdec( substr( $hex, 2, 1 ) . substr( $hex, 2, 1 ) );
        } else {
            $r = hexdec( substr( $hex, 0, 2 ) );
            $g = hexdec( substr( $hex, 2, 2 ) );
            $b = hexdec( substr( $hex, 4, 2 ) );
        }
        $bg_color = imagecolorallocate( $im, $r, $g, $b );
        imagefilledrectangle( $im, 0, 0, $target_width, $target_height, $bg_color );
        
        cafi_log( "Created Solid Color Background: $solid_hex" );
        
    } elseif ( $is_gradient ) {
        // Create Gradient Background
        $im = imagecreatetruecolor( $target_width, $target_height );
        
        // Parse Gradient Data: hex1,hex2,direction
        $parts = explode(',', $grad_data);
        if (count($parts) >= 3) {
            $dir = trim($parts[count($parts)-1]);
            $colors = array_slice($parts, 0, count($parts)-1); // support 2 colors for now
            
            // Helper to hexdec
            function cafi_hex2rgb($hex) {
                $hex = ltrim($hex, '#');
                if(strlen($hex) == 3) {
                    return [
                        hexdec(substr($hex,0,1).substr($hex,0,1)),
                        hexdec(substr($hex,1,1).substr($hex,1,1)),
                        hexdec(substr($hex,2,1).substr($hex,2,1))
                    ];
                }
                return [
                    hexdec(substr($hex,0,2)),
                    hexdec(substr($hex,2,2)),
                    hexdec(substr($hex,4,2))
                ];
            }
            
            $start_rgb = cafi_hex2rgb($colors[0]);
            $end_rgb = cafi_hex2rgb($colors[1]);
            
            if ($dir === 'vertical') {
                for ($y = 0; $y < $target_height; $y++) {
                    $p = $y / ($target_height - 1);
                    $r = intval($start_rgb[0] * (1 - $p) + $end_rgb[0] * $p);
                    $g = intval($start_rgb[1] * (1 - $p) + $end_rgb[1] * $p);
                    $b = intval($start_rgb[2] * (1 - $p) + $end_rgb[2] * $p);
                    $color = imagecolorallocate($im, $r, $g, $b);
                    imageline($im, 0, $y, $target_width, $y, $color);
                }
            } else {
                // Horizontal
                for ($x = 0; $x < $target_width; $x++) {
                    $p = $x / ($target_width - 1);
                    $r = intval($start_rgb[0] * (1 - $p) + $end_rgb[0] * $p);
                    $g = intval($start_rgb[1] * (1 - $p) + $end_rgb[1] * $p);
                    $b = intval($start_rgb[2] * (1 - $p) + $end_rgb[2] * $p);
                    $color = imagecolorallocate($im, $r, $g, $b);
                    imageline($im, $x, 0, $x, $target_height, $color);
                }
            }
        }
        
    } else {
        // ID is filename or we resolved a custom path
        $template_path = '';
        
        if ( ! empty( $custom_template_path ) ) {
            $template_path = $custom_template_path;
        } else {
            // Legacy Fallback (if ID is filename directly like 'default-white.png')
            $template_id = isset( $options['template'] ) ? $options['template'] : 'default-white.png';
            // Construct legacy path (though now unused mostly)
            // Fix path to use correct admin dir
            $template_path = CAFI_PLUGIN_DIR . 'admin/assets/images/templates/' . $template_id;
        }
        
        if ( ! file_exists( $template_path ) ) {
            cafi_log( "Error: Template file not found at $template_path" );
            // Try default fallback
             $template_path = CAFI_PLUGIN_DIR . 'admin/assets/images/templates/business_01.png'; // safe fallback
             if (!file_exists($template_path)) {
                cafi_log( "Critical Error: Fallback template also not found at $template_path" );
                return; // critical fail
             }
        }

        // Load Image
        $image_info = getimagesize( $template_path );
        $mime = $image_info['mime'];
        
        switch ( $mime ) {
            case 'image/jpeg': $im_orig = imagecreatefromjpeg( $template_path ); break;
            case 'image/png':  $im_orig = imagecreatefrompng( $template_path ); break;
            case 'image/gif':  $im_orig = imagecreatefromgif( $template_path ); break;
            case 'image/webp': $im_orig = imagecreatefromwebp( $template_path ); break;
            default: cafi_log( "Error: Unsupported mime type $mime" ); return;
        }
    
        if ( ! $im_orig ) {
            cafi_log( "Error: Could not create image resource." );
            return;
        }
    
        $im = imagecreatetruecolor( $target_width, $target_height );
        
        // Scale template to 1200x628
        imagecopyresampled( $im, $im_orig, 0, 0, 0, 0, $target_width, $target_height, imagesx($im_orig), imagesy($im_orig) );
        imagedestroy( $im_orig );
    }
    
    // Ensure TrueColor to prevent palette issues
    if ( ! imageistruecolor( $im ) ) {
        imagepalettetotruecolor( $im );
    }
    
    // Enable alpha blending for correct color layering
    imagealphablending( $im, true );

    // Color Parsing
    $hex = ltrim( $font_color_hex, '#' );
    if ( strlen( $hex ) == 3 ) {
        $r = hexdec( substr( $hex, 0, 1 ) . substr( $hex, 0, 1 ) );
        $g = hexdec( substr( $hex, 1, 1 ) . substr( $hex, 1, 1 ) );
        $b = hexdec( substr( $hex, 2, 1 ) . substr( $hex, 2, 1 ) );
    } else {
        $r = hexdec( substr( $hex, 0, 2 ) );
        $g = hexdec( substr( $hex, 2, 2 ) );
        $b = hexdec( substr( $hex, 4, 2 ) );
    }
    $text_color = imagecolorallocate( $im, $r, $g, $b );
    
    // Font Handling
    $font_file = false;
    $font_family = isset( $options['font_family'] ) ? $options['font_family'] : 'Arial';
    $font_weight = isset( $options['font_weight'] ) ? $options['font_weight'] : 'Regular';
    
    // Use Font Manager to get path (handle download if needed)
    if ( class_exists( 'CAFI_Font_Manager' ) ) {
        $font_file = CAFI_Font_Manager::get_instance()->get_font_path( $font_family, $font_weight );
    }
    
    // Fallback if manager fails or file not found (though manager handles most)
    if ( ! $font_file || ! file_exists( $font_file ) ) {
        cafi_log( "Warning: Font file for '$font_family' ($font_weight) not found. Falling back to Arial." );
        // Fallback font - make sure path is correct
        $font_file = CAFI_PLUGIN_DIR . 'admin/assets/fonts/arial.ttf';
    }
    
    if ( ! $font_file || ! file_exists( $font_file ) ) {
         $font_file = false; // Trigger gd fallback
    }

    // Settings
    $text_position = isset( $options['text_position'] ) ? $options['text_position'] : 'middle';
    $text_alignment = isset( $options['text_alignment'] ) ? $options['text_alignment'] : 'center';
    
    // Legacy/Fallback Logic
    $legacy_padding = isset( $options['padding'] ) ? intval( $options['padding'] ) : 60;
    
    // Intermediate Fallback: Horizontal/Vertical
    $legacy_pad_x = isset( $options['padding_horizontal'] ) ? intval( $options['padding_horizontal'] ) : $legacy_padding;
    $legacy_pad_y = isset( $options['padding_vertical'] ) ? intval( $options['padding_vertical'] ) : $legacy_padding;

    // Final 4-Way Padding
    $p_top = isset( $options['padding_top'] ) ? intval( $options['padding_top'] ) : $legacy_pad_y;
    $p_right = isset( $options['padding_right'] ) ? intval( $options['padding_right'] ) : $legacy_pad_x;
    $p_bottom = isset( $options['padding_bottom'] ) ? intval( $options['padding_bottom'] ) : $legacy_pad_y;
    $p_left = isset( $options['padding_left'] ) ? intval( $options['padding_left'] ) : $legacy_pad_x;
    
    // Calculate centered text
    $img_width = imagesx( $im );
    $img_height = imagesy( $im );
    
    if ( $font_file ) {
        // Use TTF with Wrapping
        $words = explode( ' ', $title );
        $lines = [];
        $current_line = '';
        
        $max_width = $img_width - $p_left - $p_right;

        foreach ( $words as $word ) {
            $test_line = $current_line . ($current_line ? ' ' : '') . $word;
            $bbox = imagettfbbox( $font_size, 0, $font_file, $test_line );
            $width = $bbox[2] - $bbox[0];
            
            if ( $width > $max_width ) { 
                $lines[] = $current_line;
                $current_line = $word;
            } else {
                $current_line = $test_line;
            }
        }
        $lines[] = $current_line;
        
        // Draw Lines
        $line_height = (int)($font_size * 1.5);
        $total_text_height = count($lines) * $line_height;
        
        // Start Y Calculation
        if ( $text_position === 'top' ) {
            $start_y = $p_top + $font_size; 
        } elseif ( $text_position === 'bottom' ) {
            $start_y = $img_height - $p_bottom - $total_text_height + $font_size; 
        } else {
            // Middle
            $start_y = ($img_height - $total_text_height) / 2 + $font_size;
        }
        
        foreach ( $lines as $i => $line ) {
            $bbox = imagettfbbox( $font_size, 0, $font_file, $line );
            $text_width = $bbox[2] - $bbox[0];
            
            // Alignment X Calculation
            if ( $text_alignment === 'left' ) {
                $x = $p_left;
            } elseif ( $text_alignment === 'right' ) {
                 $x = $img_width - $p_right - $text_width;
            } else {
                // Center
                $x = (int)(($img_width - $text_width) / 2);
            }
            
            $y = (int)($start_y + ($i * $line_height));
            
            imagettftext($im, $font_size, 0, $x, $y, $text_color, $font_file, $line);
        }
        
    } else {
        // Fallback to imagestring
        // ... (Keep existing fallback or simple one) ...
        $font_num = 5;
        $fw = imagefontwidth($font_num);
        $fh = imagefontheight($font_num);
        $len = strlen($title);
        $tw = $len * $fw;
        
        // Basic alignment for fallback
         if ( $text_alignment === 'left' ) {
            $x = 20; // fixed small padding
        } elseif ( $text_alignment === 'right' ) {
             $x = $img_width - 20 - $tw;
        } else {
             $x = ($img_width - $tw) / 2;
        }

        $y = ($img_height - $fh) / 2;
        imagestring($im, $font_num, $x, $y, $title, $text_color);
    }
    
    // --- Logo Overlay ---
    // --- Logo Overlay ---
    // LOGIC UPDATE: Use explicit template settings if available.
    // If the active template (via cafi_get_current_template_data) does NOT have 'logo_position',
    // then WE SHOULD NOT RENDER THE LOGO, even if a global logo_url is set.
    
    $should_render_logo = true;
    
    // Attempt to check current template configuration for explicit logo disabling
    // We already called cafi_get_current_template_data above ($tmpl_data)
    // If $tmpl_data exists and has 'settings', check for 'logo_position'
    
    if ( isset($tmpl_data) && isset($tmpl_data['settings']) ) {
        if ( ! isset($tmpl_data['settings']['logo_position']) || empty($tmpl_data['settings']['logo_position']) ) {
            $should_render_logo = false; 
            cafi_log("Logo skipped: Template has no logo_position defined.");
        }
    }

    $logo_url = isset( $options['logo_url'] ) ? $options['logo_url'] : '';
    
    if ( $should_render_logo && ! empty( $logo_url ) ) {
        // Get local path from URL if possible to avoid HTTP fetch overhead/issues
        // Simple check: if URL contains site URL, replace with ABSPATH
        $upload_dir_info = wp_upload_dir();
        $base_url = $upload_dir_info['baseurl'];
        $base_path = $upload_dir_info['basedir'];
        
        $logo_path = str_replace( $base_url, $base_path, $logo_url );
        
        // If replacement didn't work (external URL?), try fetching or use as is if allow_url_fopen
        if ( file_exists( $logo_path ) ) {
            $logo_info = getimagesize( $logo_path );
            if ( $logo_info ) {
                $l_mime = $logo_info['mime'];
                $im_logo = false;
                
                switch ( $l_mime ) {
                    case 'image/jpeg': $im_logo = imagecreatefromjpeg( $logo_path ); break;
                    case 'image/png':  $im_logo = imagecreatefrompng( $logo_path ); break;
                    case 'image/gif':  $im_logo = imagecreatefromgif( $logo_path ); break;
                    case 'image/webp': $im_logo = imagecreatefromwebp( $logo_path ); break;
                }
                
                if ( $im_logo ) {
                    $logo_w = imagesx( $im_logo );
                    $logo_h = imagesy( $im_logo );
                    
                    // Settings
                    $l_size_pct = isset( $options['logo_size'] ) ? intval( $options['logo_size'] ) : 20;
                    $l_pos = isset( $options['logo_position'] ) ? $options['logo_position'] : 'bottom-right';
                    
                    // Split Offsets
                    $l_offset_x = isset( $options['logo_offset_x'] ) ? intval( $options['logo_offset_x'] ) : ( isset( $options['logo_offset'] ) ? intval( $options['logo_offset'] ) : 20 );
                    $l_offset_y = isset( $options['logo_offset_y'] ) ? intval( $options['logo_offset_y'] ) : ( isset( $options['logo_offset'] ) ? intval( $options['logo_offset'] ) : 20 );
                    
                    // Calculate Target Size
                    $target_logo_w = ($l_size_pct / 100) * $img_width;
                    $target_logo_h = ($target_logo_w / $logo_w) * $logo_h;
                    
                    // Calculate Position
                    $lx = 0;
                    $ly = 0;
                    $parts = explode('-', $l_pos);
                    $v_pos = $parts[0];
                    $h_pos = $parts[1];
                    
                    // Horizontal
                    if ( $h_pos === 'left' ) {
                        $lx = $l_offset_x;
                    } elseif ( $h_pos === 'right' ) {
                        $lx = $img_width - $l_offset_x - $target_logo_w;
                    } else { // center
                        $lx = ($img_width - $target_logo_w) / 2;
                    }
                    
                    // Vertical
                    if ( $v_pos === 'top' ) {
                        $ly = $l_offset_y;
                    } elseif ( $v_pos === 'bottom' ) {
                        $ly = $img_height - $l_offset_y - $target_logo_h;
                    } else { // middle
                        $ly = ($img_height - $target_logo_h) / 2;
                    }
                    
                    // Overlay
                    imagecopyresampled( $im, $im_logo, $lx, $ly, 0, 0, $target_logo_w, $target_logo_h, $logo_w, $logo_h );
                    imagedestroy( $im_logo );
                }
            }
        }
    }
    
    // Generate Output filename based on format
    $output_format = isset( $options['output_format'] ) ? $options['output_format'] : 'png';
    $ext = $output_format;
    // Map jpg to jpeg for mime type if needed, but extension is usually jpg/jpeg. 
    // WordPress convention: mime 'image/jpeg', ext 'jpg'
    
    $upload_dir = wp_upload_dir();
    $filename = 'afi-generated-' . $post_id . '-' . time() . '.' . $ext;
    $file_path = $upload_dir['path'] . '/' . $filename;
    
    cafi_log( "Saving image to: $file_path (Format: $output_format)" );
    
    // Save based on format
    $save_result = false;
    $post_mime_type = 'image/png';

    switch ( $output_format ) {
        case 'jpg':
        case 'jpeg':
            $save_result = imagejpeg( $im, $file_path, 82 ); // Optimized quality (82 is standard web balance)
            $post_mime_type = 'image/jpeg';
            break;
        case 'webp':
            $save_result = imagewebp( $im, $file_path, 80 ); // Optimized quality
            $post_mime_type = 'image/webp';
            break;
        case 'png':
        default:
            $save_result = imagepng( $im, $file_path, 9 ); // 9 = max compression (lossless, so quality is same but size is smaller)
            $post_mime_type = 'image/png';
            break;
    }
    
    imagedestroy( $im );
    
    // Verify file was created
    if ( $save_result && file_exists( $file_path ) ) {
        cafi_log( "Image saved successfully. File size: " . filesize( $file_path ) . " bytes" );
    } else {
        cafi_log( "ERROR: Image file was NOT created!" );
    }

    $attachment = array(
        'post_mime_type' => $post_mime_type,
        'post_title'     => $title,
        'post_content'   => '',
        'post_status'    => 'inherit'
    );
    
    $attach_id = wp_insert_attachment( $attachment, $file_path, $post_id );
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    
    update_post_meta( $attach_id, '_cafi_generated', 1 );

    set_post_thumbnail( $post_id, $attach_id );
    cafi_log( "Finished. Attached ID: $attach_id" );
}


function cafi_log( $message ) {
    // Debugging only:
    // if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( '[AutoFeatured] ' . $message ); }
}

/**
 * Handle manual generation request via AJAX
 */
function cafi_handle_manual_generate_ajax() {
	if ( ! current_user_can( 'edit_posts' ) ) {
		wp_send_json_error( __( 'Permission denied.', 'custom-auto-featured-image' ) ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
	}

	$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
	
	check_ajax_referer( 'cafi_generate_' . $post_id );

	if ( ! $post_id ) {
		wp_send_json_error( __( 'Invalid Post ID.', 'custom-auto-featured-image' ) ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
	}

	$post = get_post( $post_id );
	if ( ! $post ) {
		wp_send_json_error( __( 'Post not found.', 'custom-auto-featured-image' ) ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
	}

	// Remove existing if it's generated by us
	if ( has_post_thumbnail( $post_id ) ) {
		$thumbnail_id = get_post_thumbnail_id( $post_id );
		$is_generated = get_post_meta( $thumbnail_id, '_cafi_generated', true );
		if ( $is_generated ) {
			wp_delete_attachment( $thumbnail_id, true );
		}
	}

	cafi_create_image_for_post( $post_id, $post->post_title );

	wp_send_json_success( __( 'Image generated/updated successfully.', 'custom-auto-featured-image' ) ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
}
add_action( 'wp_ajax_cafi_generate_image_ajax', 'cafi_handle_manual_generate_ajax' );


