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

class SEOFORGE_Image_Seo {
    private static $instance = null;
    public static function instance() { if (!self::$instance) self::$instance = new self(); return self::$instance; }

    private function __construct() {
        if (!SEOFORGE_License::instance()->can('image_seo')) {
            return;
        }

        // Auto-generate alt text on upload
        add_action('add_attachment', [$this, 'auto_alt_on_upload']);

        // Clean filename on upload
        add_filter('sanitize_file_name', [$this, 'clean_filename'], 10, 1);

        // Add alt text reminder in media library
        add_filter('attachment_fields_to_edit', [$this, 'alt_text_reminder'], 20, 2);
    }

    /**
 * Auto-generate alt text from filename when image is uploaded
 */
    public function auto_alt_on_upload($attachment_id) {
        if (!wp_attachment_is_image($attachment_id)) return;

        // Skip if alt text already set
        $existing_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
        if (!empty($existing_alt)) return;

        $attachment = get_post($attachment_id);
        if (!$attachment) return;

        // Generate alt from filename
        $filename = pathinfo(get_attached_file($attachment_id), PATHINFO_FILENAME);
        $alt = $this->filename_to_alt($filename);

        // If post has a parent, append post title for context
        if ($attachment->post_parent) {
            $parent = get_post($attachment->post_parent);
            if ($parent && !empty($parent->post_title)) {
                $alt .= ' - ' . $parent->post_title;
            }
        }

        if (!empty($alt)) {
            update_post_meta($attachment_id, '_wp_attachment_image_alt', sanitize_text_field($alt));
        }

        // Also set title if empty
        if (empty($attachment->post_title) || $attachment->post_title === $filename) {
            wp_update_post([
                'ID' => $attachment_id,
                'post_title' => $this->filename_to_alt($filename),
            ]);
        }
    }

    /**
 * Convert filename to readable alt text
 * "my-awesome-photo-2024" → "My Awesome Photo 2024"
 */
    private function filename_to_alt($filename) {
        // Remove common suffixes
        $filename = preg_replace('/[-_]?\d{2,4}x\d{2,4}$/i', '', $filename); // Remove dimensions
        $filename = preg_replace('/[-_]?(scaled|rotated|cropped|edited|copy|final|v\d+)$/i', '', $filename);

        // Replace separators with spaces
        $alt = str_replace(['-', '_', '.'], ' ', $filename);

        // Remove multiple spaces
        $alt = preg_replace('/\s+/', ' ', $alt);

        // Capitalize words
        $alt = mb_convert_case(trim($alt), MB_CASE_TITLE);

        return $alt;
    }

    /**
 * Clean filenames on upload for SEO
 * "My Photo (1).JPG" → "my-photo-1.jpg"
 */
    public function clean_filename($filename) {
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $name = pathinfo($filename, PATHINFO_FILENAME);

        // Transliterate common characters
        $name = mb_strtolower($name);
        $name = str_replace(['_', ' '], '-', $name);
        $name = preg_replace('/[^a-z0-9\-]/u', '-', $name);
        $name = preg_replace('/-+/', '-', $name);
        $name = trim($name, '-');

        if (empty($name)) $name = 'image-' . time();

        return $name . '.' . strtolower($ext);
    }

    /**
 * Show reminder in media library if alt text is missing
 */
    public function alt_text_reminder($form_fields, $post) {
        if (!wp_attachment_is_image($post->ID)) return $form_fields;

        $alt = get_post_meta($post->ID, '_wp_attachment_image_alt', true);

        if (empty($alt)) {
            $form_fields['seoforge_alt_notice'] = [
                'label' => '',
                'input' => 'html',
                'html' => '<p style="color:#D97706;font-size:14px;padding:4px 8px;background:#FFFBEB;border-radius:4px;border-left:3px solid #D97706;"><strong>SEO Forge:</strong> ' . __('This image has no alt text. Alt text helps SEO and accessibility.', 'seoforge') . '</p>',
            ];
        }

        return $form_fields;
    }
}
