<?php
/**
 * Plugin Name: Addirectly Ads
 * Plugin URI: https://addirectly.com/installation
 * Description: Affichez des espaces publicitaires directs Addirectly sur votre site WordPress via un simple shortcode. Aucun cookie, zéro CLS.
 * Version: 1.0.0
 * Author: Addirectly
 * Author URI: https://addirectly.com
 * License: MIT
 * Text Domain: addirectly-ads
 */

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

/**
 * Injects the Addirectly loader script once, in the site footer.
 */
function addirectly_enqueue_loader() {
    wp_enqueue_script(
        'addirectly-embed',
        'https://addirectly.com/api/public/embed.js',
        array(),
        null,
        array('strategy' => 'async', 'in_footer' => true)
    );
}
add_action('wp_enqueue_scripts', 'addirectly_enqueue_loader');

/**
 * Shortcode: [addirectly slot="SLOT_ID" width="300" height="250"]
 *
 * SLOT_ID: the ad slot ID copied from your Addirectly dashboard
 * width / height: dimensions in pixels (reserves the space, prevents CLS)
 */
function addirectly_shortcode($atts) {
    $atts = shortcode_atts(array(
        'slot'   => '',
        'width'  => '',
        'height' => '',
    ), $atts, 'addirectly');

    $slot = sanitize_text_field($atts['slot']);
    if (empty($slot)) {
        return '';
    }

    $width  = intval($atts['width']);
    $height = intval($atts['height']);

    $style = 'display:block;';
    if ($width > 0 && $height > 0) {
        $style .= 'aspect-ratio:' . $width . '/' . $height . ';max-width:' . $width . 'px;margin:0 auto;';
    }

    return sprintf(
        '<div data-ad-slot="%s" data-width="%d" data-height="%d" style="%s"></div>',
        esc_attr($slot),
        $width,
        $height,
        esc_attr($style)
    );
}
add_shortcode('addirectly', 'addirectly_shortcode');

/**
 * Adds a settings link on the Plugins page.
 */
function addirectly_plugin_action_links($links) {
    $help = '<a href="https://addirectly.com/installation" target="_blank">Aide</a>';
    array_unshift($links, $help);
    return $links;
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'addirectly_plugin_action_links');

/**
 * Domain verification: outputs the Addirectly meta tag if configured via
 * the WordPress option `addirectly_verification_token`. Set it once from
 * Settings > General or via WP-CLI:
 *   wp option update addirectly_verification_token "YOUR_TOKEN"
 */
function addirectly_meta_verification() {
    $token = get_option('addirectly_verification_token', '');
    if (!empty($token)) {
        echo '<meta name="addirectly-verify" content="' . esc_attr($token) . '" />' . "\n";
    }
}
add_action('wp_head', 'addirectly_meta_verification', 1);
