<?php
/**
 * FajaedeSEO Frontend Meta Tags
 */

defined('ABSPATH') or exit;

function fajaedeseo_render_meta_tags() {
    $plan = class_exists('\FajaedeSEO_Pro_License') ? \FajaedeSEO_Pro_License::get_plan_level() : 'free';

    // Toon alleen reclame als het GEEN Agency abonnement is (White-label)
    if ($plan !== 'agency') {
        echo "\n<!-- Optimized by FajaedeSEO AI - https://www.fajaede.nl -->\n";
    }

    $post_id = is_singular() ? get_the_ID() : 0;
    $title = '';
    $desc = '';
    $image = defined('FAJAEDESEO_OG_IMAGE_FALLBACK') ? FAJAEDESEO_OG_IMAGE_FALLBACK : '';
    $url = home_url( add_query_arg( array(), $GLOBALS['wp']->request ) );
    $robots_index = 'index';
    $robots_follow = 'follow';

    // 1. Expliciet de Canonical URL forceren en native WP gedrag uitschakelen
    $canonical = $url;
    if ( is_singular() ) {
        $custom_canonical = get_post_meta( $post_id, '_fajaedeseo_canonical', true );
        if ( ! empty( $custom_canonical ) ) {
            $canonical = $custom_canonical;
        } elseif ( function_exists('wp_get_canonical_url') && wp_get_canonical_url( $post_id ) ) {
            $canonical = wp_get_canonical_url( $post_id );
        }
    } elseif ( is_front_page() || is_home() ) {
        $canonical = home_url( '/' );
    }
    echo '<link rel="canonical" href="' . esc_url( $canonical ) . '" />' . "\n";
    remove_action( 'wp_head', 'rel_canonical' );

    if ( is_front_page() || is_home() ) {
        $title = get_option( 'fajaedeseo_home_seo_title' ) ?: get_bloginfo( 'name' );
        $desc = get_option( 'fajaedeseo_home_seo_desc' ) ?: get_bloginfo( 'description' );
    } elseif ( is_singular() ) {
        $title = get_post_meta( $post_id, '_fajaedeseo_meta_title', true ) ?: get_the_title( $post_id );
        $desc = get_post_meta( $post_id, '_fajaedeseo_meta_desc', true );
        
        // Dynamische fallback als er (nog) geen custom beschrijving is opgeslagen
        if ( empty( $desc ) ) {
            if ( has_excerpt( $post_id ) ) {
                $desc = wp_strip_all_tags( get_the_excerpt( $post_id ) );
            } else {
                $post_obj = get_post( $post_id );
                $desc = wp_trim_words( wp_strip_all_tags( $post_obj->post_content ), 30 );
            }
        }
        
        $robots_index = get_post_meta( $post_id, '_fajaedeseo_robots_index', true ) ?: 'index';
        $robots_follow = get_post_meta( $post_id, '_fajaedeseo_robots_follow', true ) ?: 'follow';
        $url = get_permalink( $post_id );
        if ( has_post_thumbnail( $post_id ) ) {
            $image = get_the_post_thumbnail_url( $post_id, 'full' );
        }
        
        // Automatically force noindex on checkout success page to prevent indexing of sensitive order info
        $post_obj = get_post( $post_id );
        if ( $post_obj && has_shortcode( $post_obj->post_content, 'fajaedeseo_checkout_success' ) ) {
            $robots_index = 'noindex';
            $robots_follow = 'nofollow';
        }
    }

    $is_homepage = is_front_page() || is_home();

    // Geavanceerde Robots Tag (Cruciaal voor Google Discover en AI overviews)
    $robots_string = $robots_index . ', ' . $robots_follow;
    if ( $robots_index === 'index' ) {
        $robots_string .= ', max-image-preview:large, max-snippet:-1, max-video-preview:-1';
    }

    // Robots Meta Tag (Altijd tonen, inclusief geavanceerde tags)
    echo '<meta name="robots" content="' . esc_attr( $robots_string ) . '" />' . "\n";

    // Basic Meta
    if ( $desc ) echo '<meta name="description" content="' . esc_attr( $desc ) . '" />' . "\n";
    
    if ( $plan !== 'free' ) {
        // Open Graph
        echo '<meta property="og:locale" content="' . esc_attr( get_locale() ) . '" />' . "\n";
        echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n";
        if ( $desc ) {
            echo '<meta property="og:description" content="' . esc_attr( $desc ) . '" />' . "\n";
            echo '<meta itemprop="description" content="' . esc_attr( $desc ) . '" />' . "\n"; // Microdata fallback
        }
        echo '<meta property="og:type" content="' . ( (is_singular() && !$is_homepage) ? 'article' : 'website' ) . '" />' . "\n";
        echo '<meta property="og:url" content="' . esc_url( $url ) . '" />' . "\n";
        if ( $image ) {
            echo '<meta property="og:image" content="' . esc_url( $image ) . '" />' . "\n";
            echo '<meta itemprop="image" content="' . esc_url( $image ) . '" />' . "\n"; // Microdata fallback
            if (strpos($image, 'https://') === 0) {
                echo '<meta property="og:image:secure_url" content="' . esc_url( $image ) . '" />' . "\n";
            }
        }
        echo '<meta property="og:site_name" content="' . esc_attr( get_bloginfo( 'name' ) ) . '" />' . "\n";
        
        $facebook_handle = get_option( 'fajaedeseo_facebook_handle' );
        if ( $facebook_handle && is_singular() && !$is_homepage ) {
            $fb_url = $facebook_handle;
            if ( ! filter_var( $facebook_handle, FILTER_VALIDATE_URL ) ) {
                $fb_url = 'https://www.facebook.com/' . ltrim( $facebook_handle, '@' );
            }
            echo '<meta property="article:publisher" content="' . esc_url( $fb_url ) . '" />' . "\n";
        }
        
        // Twitter Cards
        echo '<meta name="twitter:card" content="summary_large_image" />' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr( $title ) . '" />' . "\n";
        if ( $desc ) echo '<meta name="twitter:description" content="' . esc_attr( $desc ) . '" />' . "\n";
        if ( $image ) echo '<meta name="twitter:image" content="' . esc_url( $image ) . '" />' . "\n";
        
        $twitter_handle = get_option( 'fajaedeseo_twitter_handle' );
        if ( $twitter_handle ) {
            echo '<meta name="twitter:site" content="@' . esc_attr( ltrim( $twitter_handle, '@' ) ) . '" />' . "\n";
        }

        // Dynamische leestijd en auteur voor de Twitter "Written by" kaarten
        if ( is_singular() && isset($post_obj) ) {
            $author_id = $post_obj->post_author;
            $author_name = get_the_author_meta('display_name', $author_id) ?: get_bloginfo('name');
            $word_count = str_word_count(wp_strip_all_tags($post_obj->post_content));
            $reading_time = max(1, ceil($word_count / 200)); // Gemiddeld 200 woorden per minuut
            
            echo '<meta name="twitter:creator" content="' . esc_attr( $author_name ) . '" />' . "\n";
            echo '<meta name="twitter:label1" content="Written by" />' . "\n";
            echo '<meta name="twitter:data1" content="' . esc_attr( $author_name ) . '" />' . "\n";
            echo '<meta name="twitter:label2" content="Est. reading time" />' . "\n";
            echo '<meta name="twitter:data2" content="' . esc_attr( $reading_time ) . ' minute' . ($reading_time > 1 ? 's' : '') . '" />' . "\n";
        }
    } else {
        // Plaats een onzichtbare HTML-commentaar als teasertje voor ontwikkelaars/marketeers die de broncode bekijken
        echo "\n<!-- FajaedeSEO: Upgrade to Pro for OpenGraph & Twitter Social Cards -->\n";
    }
    
    // Local SEO (Geo-Targeting) & Branding for Premium / Agency
    if ( $plan === 'premium' || $plan === 'agency' ) {
        $fb_admins = get_option('fajaedeseo_fb_admins');
        if ( $fb_admins ) echo '<meta property="fb:admins" content="' . esc_attr( $fb_admins ) . '" />' . "\n";
        
        $fb_app_id = get_option('fajaedeseo_fb_app_id'); // of fb:pages
        if ( $fb_app_id ) echo '<meta property="fb:pages" content="' . esc_attr( $fb_app_id ) . '" />' . "\n";

        $city = get_option('fajaedeseo_company_city');
        $region = get_option('fajaedeseo_company_region');
        $lat = get_option('fajaedeseo_company_lat');
        $lng = get_option('fajaedeseo_company_lng');
        
        if ( $city || $region || ($lat && $lng) ) {
            if ( $city )   echo '<meta name="geo.placename" content="' . esc_attr($city) . '" />' . "\n";
            if ( $region ) echo '<meta name="geo.region" content="' . esc_attr($region) . '" />' . "\n";
            if ( $lat && $lng ) {
                echo '<meta name="geo.position" content="' . esc_attr($lat . ';' . $lng) . '" />' . "\n";
                echo '<meta name="ICBM" content="' . esc_attr($lat . ', ' . $lng) . '" />' . "\n";
            }
        }
    }
    if ( $plan === 'agency' ) {
        echo "<meta name=\"Fajaede\" content=\"Martinn Margaritha\" />\n";
    }

    if ($plan !== 'agency') {
        echo "<!-- FajaedeSEO End -->\n";
    }
}