<?php
/**
 * Schema Audit
 *
 * Integrates schema checks into TAMRANK SEO Audit
 *
 * @package TamRank
 * @subpackage Schema
 */

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

class TAMRANK_Schema_Audit {

    /**
     * Templates manager instance
     *
     * @var TAMRANK_Schema_Templates
     */
    private $templates;

    /**
     * Settings manager instance
     *
     * @var TAMRANK_Schema_Settings
     */
    private $settings;

    /**
     * Initialize the audit
     *
     * @param TAMRANK_Schema_Templates $templates Templates manager
     * @param TAMRANK_Schema_Settings $settings Settings manager
     */
    public function __construct($templates, $settings) {
        $this->templates = $templates;
        $this->settings = $settings;

        // Hook into existing TAMRANK audit system
        // NOTE: This assumes the existing audit system has a filter hook
        // If not, this will need to be integrated differently
        add_filter('tamrank_audit_checks', array($this, 'add_schema_checks'), 10, 2);
    }

    /**
     * Add schema checks to the audit
     *
     * @param array $checks Existing audit checks
     * @param int $post_id Post ID being audited
     * @return array Modified checks
     */
    public function add_schema_checks($checks, $post_id) {
        $schema_checks = $this->run_schema_audit($post_id);

        return array_merge($checks, $schema_checks);
    }

    /**
     * Run schema audit for a post
     *
     * @param int $post_id Post ID
     * @return array Audit results
     */
    public function run_schema_audit($post_id) {
        $results = array();

        // Check if post has schema enabled
        $enabled = get_post_meta($post_id, 'tamrank_schema_enabled', true);

        if ($enabled === '' || $enabled === '1') {
            // Schema should be present
            $template_id = get_post_meta($post_id, 'tamrank_schema_template_id', true);
            $template = null;

            if ($template_id) {
                $template = $this->templates->get_template($template_id);
            } else {
                // Try to find template for this post type
                $post_type = get_post_type($post_id);
                $templates = $this->templates->get_templates_for_post_type($post_type);
                if (!empty($templates)) {
                    $template = reset($templates);
                }
            }

            if ($template) {
                $results['schema_status'] = array(
                    'label' => __( 'Schema Markup', 'tam-rank' ),
                    'status' => 'passed',
                    'message' => sprintf( /* translators: %s: schema type */ __( 'Schema markup is active (%s)', 'tam-rank' ), $template['schema_type'] ),
                    'score' => 10
                );

                // Check required fields
                $missing_fields = $this->check_required_fields($post_id, $template);

                if (!empty($missing_fields)) {
                    $results['schema_required_fields'] = array(
                        'label' => __( 'Schema Required Fields', 'tam-rank' ),
                        'status' => 'warning',
                        'message' => sprintf( /* translators: %s: comma-separated list of missing field names */ __( 'Schema is missing required fields: %s', 'tam-rank' ), implode( ', ', $missing_fields ) ),
                        'score' => 5
                    );
                } else {
                    $results['schema_required_fields'] = array(
                        'label' => __( 'Schema Required Fields', 'tam-rank' ),
                        'status' => 'passed',
                        'message' => __( 'All required schema fields are present', 'tam-rank' ),
                        'score' => 10
                    );
                }

                // Check image quality for schema
                $results = array_merge($results, $this->check_schema_image($post_id, $template));

            } else {
                $results['schema_status'] = array(
                    'label' => __( 'Schema Markup', 'tam-rank' ),
                    'status' => 'failed',
                    'message' => __( 'No schema template found for this post type', 'tam-rank' ),
                    'score' => 0
                );
            }
        } else {
            $results['schema_status'] = array(
                'label' => __( 'Schema Markup', 'tam-rank' ),
                'status' => 'info',
                'message' => __( 'Schema markup is disabled for this page', 'tam-rank' ),
                'score' => 0
            );
        }

        return $results;
    }

    /**
     * Check for missing required fields
     *
     * @param int $post_id Post ID
     * @param array $template Template configuration
     * @return array Missing field labels
     */
    private function check_required_fields($post_id, $template) {
        $post = get_post($post_id);
        $schema_types = tamrank_get_schema_types();
        $schema_config = $schema_types[$template['schema_type']] ?? null;
        $overrides = get_post_meta($post_id, 'tamrank_schema_overrides', true);

        if (!is_array($overrides)) {
            $overrides = array();
        }

        $missing = array();

        if (!is_array($schema_config) || empty($schema_config['properties'])) {
            return $missing;
        }

        foreach ($schema_config['properties'] as $property => $prop_config) {
            if (!($prop_config['required'] ?? false)) {
                continue; // Skip non-required fields
            }

            $mapping = $template['field_mappings'][$property] ?? array();

            // Check if there's an override
            if (!empty($overrides[$property])) {
                continue; // Field has override value
            }

            // Check if the source can provide a value
            $source = $mapping['source'] ?? '';
            $can_provide_value = false;

            switch ($source) {
                case 'post_title':
                    $can_provide_value = !empty($post->post_title);
                    break;

                case 'meta_description':
                    $can_provide_value = !empty(get_post_meta($post_id, '_tam_rank_meta_description', true));
                    break;

                case 'excerpt':
                    $can_provide_value = !empty($post->post_excerpt);
                    break;

                case 'content_excerpt':
                    $can_provide_value = !empty($post->post_content);
                    break;

                case 'featured_image':
                    $can_provide_value = has_post_thumbnail($post_id);
                    break;

                case 'first_content_image':
                    preg_match('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches);
                    $can_provide_value = !empty($matches[1]);
                    break;

                case 'author_name':
                case 'author_url':
                case 'post_date':
                case 'post_modified':
                    $can_provide_value = true; // These always have values
                    break;

                case 'global_organization':
                case 'global_logo':
                    $can_provide_value = true; // Global settings
                    break;

                case 'custom_field':
                    $meta_key = $mapping['custom_field'] ?? '';
                    if ($meta_key) {
                        $can_provide_value = !empty(get_post_meta($post_id, $meta_key, true));
                    }
                    break;

                case 'manual':
                    $can_provide_value = !empty($mapping['value']);
                    break;
            }

            if (!$can_provide_value) {
                $missing[] = $prop_config['label'];
            }
        }

        return $missing;
    }

    /**
     * Check schema image requirements
     *
     * @param int $post_id Post ID
     * @param array $template Template configuration
     * @return array Audit results
     */
    private function check_schema_image($post_id, $template) {
        $results = array();
        $schema_types = tamrank_get_schema_types();
        $schema_config = $schema_types[$template['schema_type']] ?? null;

        // Check if schema type requires image
        if (!isset($schema_config['properties']['image'])) {
            return $results;
        }

        $image_mapping = $template['field_mappings']['image'] ?? array();
        $source = $image_mapping['source'] ?? '';

        $image_id = null;

        if ($source === 'featured_image') {
            $image_id = get_post_thumbnail_id($post_id);
        }

        if ($image_id) {
            $image_data = wp_get_attachment_metadata($image_id);

            // Check image dimensions (Google recommends min 1200px wide)
            $width = $image_data['width'] ?? 0;
            $height = $image_data['height'] ?? 0;

            if ($width >= 1200 && $height >= 675) {
                $results['schema_image_quality'] = array(
                    'label' => __( 'Schema Image Quality', 'tam-rank' ),
                    'status' => 'passed',
                    'message' => sprintf( /* translators: 1: width in pixels, 2: height in pixels */ __( 'Image has good dimensions (%1$dx%2$dpx)', 'tam-rank' ), $width, $height ),
                    'score' => 10
                );
            } elseif ($width >= 600) {
                $results['schema_image_quality'] = array(
                    'label' => __( 'Schema Image Quality', 'tam-rank' ),
                    'status' => 'warning',
                    'message' => sprintf( /* translators: 1: width in pixels, 2: height in pixels */ __( 'Image is too small (%1$dx%2$dpx). Google recommends at least 1200x675px', 'tam-rank' ), $width, $height ),
                    'score' => 5
                );
            } else {
                $results['schema_image_quality'] = array(
                    'label' => __( 'Schema Image Quality', 'tam-rank' ),
                    'status' => 'failed',
                    'message' => sprintf( /* translators: 1: width in pixels, 2: height in pixels */ __( 'Image is far too small (%1$dx%2$dpx). Use a larger image', 'tam-rank' ), $width, $height ),
                    'score' => 0
                );
            }
        }

        return $results;
    }


}
