<?php
/**
 * Plugin Name: Biscotti CMP
 * Plugin URI: https://biscotti-cmp.com
 * Description: GDPR/CCPA/LGPD Consent Management with AI cookie detection, Google Consent Mode v2, TCF 2.3, and 249 global jurisdictions.
 * Version: 4.2.3
 * Author: Campcruisers GmbH
 * Author URI: https://www.campcruisers.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: biscotti-cmp
 * Domain Path: /languages
 * Requires at least: 6.0
 * Tested up to: 7.0
 * Requires PHP: 7.4
 */

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

// ============================================================================
// PLUGIN CONSTANTS
// ============================================================================

define('BISCOTTI_VERSION', '4.2.3');
define('BISCOTTI_PLUGIN_FILE', __FILE__);
define('BISCOTTI_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('BISCOTTI_PLUGIN_URL', plugin_dir_url(__FILE__));
define('BISCOTTI_PLUGIN_BASENAME', plugin_basename(__FILE__));

// ============================================================================
// INCLUDES
// ============================================================================

// Canonical language list (single source of truth for every language dropdown)
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-languages.php';

// Cloud-Bridge: API Client (standardized communication)
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-api-client.php';

// Language Bridge: Universal translation plugin detection
// MUST load before API client and shortcodes use it
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-language-bridge.php';

// Template Renderer: Reusable rendering utilities for admin templates
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-template-renderer.php';

// Cloud-Bridge: Admin UI (dynamic view loading)
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-admin.php';

// Frontend: Banner injection
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-banner.php';

// Shortcodes: Legal document rendering
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-shortcodes.php';

// GeoIP & Regional Compliance (lightweight, runs client-side)
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-geoip.php';
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-regions.php';
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-multiregion-banner.php';

// Gutenberg Block Editor Blocks (native WP, always available)
require_once BISCOTTI_PLUGIN_DIR . 'includes/class-gutenberg-blocks.php';

// Elementor Widgets (only if Elementor active)
add_action('elementor/loaded', function () {
    require_once BISCOTTI_PLUGIN_DIR . 'includes/class-elementor-widgets.php';
});

// Builder & WooCommerce integrations (conditionally loaded after all plugins)
add_action('plugins_loaded', function () {
    // Divi Builder
    if (class_exists('ET_Builder_Module')) {
        require_once BISCOTTI_PLUGIN_DIR . 'includes/class-divi-modules.php';
    }
    // Beaver Builder
    if (class_exists('FLBuilder')) {
        require_once BISCOTTI_PLUGIN_DIR . 'includes/class-beaver-modules.php';
    }
    // WPBakery (Visual Composer)
    if (function_exists('vc_map')) {
        require_once BISCOTTI_PLUGIN_DIR . 'includes/class-wpbakery-elements.php';
    }
    // Oxygen Builder
    if (class_exists('OxyEl')) {
        require_once BISCOTTI_PLUGIN_DIR . 'includes/class-oxygen-elements.php';
    }
    // WooCommerce
    if (class_exists('WooCommerce')) {
        require_once BISCOTTI_PLUGIN_DIR . 'includes/class-woocommerce.php';
    }
    // Google Site Kit — block analytics scripts until consent
    if (defined('GOOGLESITEKIT_VERSION')) {
        require_once BISCOTTI_PLUGIN_DIR . 'includes/class-google-sitekit.php';
        new Biscotti_Google_Sitekit();
    }
}, 30);

// ============================================================================
// MAIN PLUGIN CLASS
// ============================================================================

class Biscotti_CMP
{
    /**
     * Single instance
     */
    private static $instance = null;

    /**
     * @var Biscotti_API_Client
     */
    private $api;

    /**
     * @var Biscotti_Admin
     */
    private $admin;

    /**
     * @var Biscotti_Banner
     */
    private $banner;

    /**
     * Get instance
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct()
    {
        // Initialize API client
        $this->api = new Biscotti_API_Client();

        // Initialize admin (menu registration + dynamic views)
        if (is_admin()) {
            $this->admin = new Biscotti_Admin($this->api);
        }

        // Initialize frontend banner injection
        $this->banner = new Biscotti_Banner($this->api);

        // Load translations
        add_action('init', [$this, 'load_textdomain']);

        // Admin notices
        add_action('admin_notices', [$this, 'connection_notice']);

        // Plugin action links
        add_filter('plugin_action_links_' . BISCOTTI_PLUGIN_BASENAME, [$this, 'action_links']);

        // Activation / Deactivation
        register_activation_hook(__FILE__, [$this, 'activate']);
        register_deactivation_hook(__FILE__, [$this, 'deactivate']);
    }

    /**
     * Load text domain for translations
     */
    public function load_textdomain()
    {
        // Map plugin language codes to WordPress locale codes
        $locale_map = [
            'de' => 'de_DE', 'en' => 'en_US', 'fr' => 'fr_FR', 'es' => 'es_ES',
            'it' => 'it_IT', 'nl' => 'nl_NL', 'pl' => 'pl_PL', 'pt' => 'pt_PT',
            'pt-BR' => 'pt_BR', 'pt-PT' => 'pt_PT',
            'da' => 'da_DK', 'sv' => 'sv_SE', 'fi' => 'fi_FI', 'no' => 'nb_NO',
            'nb' => 'nb_NO',
            'cs' => 'cs_CZ', 'sk' => 'sk_SK', 'hu' => 'hu_HU', 'ro' => 'ro_RO',
            'bg' => 'bg_BG', 'hr' => 'hr_HR', 'sl' => 'sl_SI', 'lt' => 'lt_LT',
            'el' => 'el_GR', 'tr' => 'tr_TR', 'ru' => 'ru_RU', 'uk' => 'uk_UA',
            'ja' => 'ja_JP', 'zh' => 'zh_CN', 'zh-TW' => 'zh_TW', 'ar' => 'ar_SA',
            'hi' => 'hi_IN', 'he' => 'he_IL', 'th' => 'th_TH', 'vi' => 'vi_VN',
            'id' => 'id_ID',
            'bs' => 'bs_BA', 'ca' => 'ca_ES', 'eu' => 'eu_ES',
            'gl' => 'gl_ES', 'mr' => 'mr_IN', 'sr' => 'sr_RS',
        ];
        $options = get_option('biscotti_options', []);
        $selected_lang = $options['default_language'] ?? 'en';
        $locale = $locale_map[$selected_lang] ?? 'en_US';

        // Unload any auto-loaded textdomain
        unload_textdomain('biscotti-cmp');

        $mo_file = BISCOTTI_PLUGIN_DIR . 'languages/biscotti-cmp-' . $locale . '.mo';
        if (file_exists($mo_file)) {
            load_textdomain('biscotti-cmp', $mo_file);
        }
    }

    /**
     * Show admin notice if plugin is not connected
     */
    public function connection_notice()
    {
        if (!$this->api->is_connected()) {
            // The connection screen renders on the main Biscotti CMP dashboard page
            // when the site is not yet connected (see Biscotti_Admin::render_connection_required()).
            $connect_url = admin_url('admin.php?page=biscotti-cmp');
            echo '<div class="notice notice-warning is-dismissible"><p>';
            printf(
                /* translators: %s: Connect/dashboard URL */
                esc_html__('Biscotti CMP: Please %s to connect your Biscotti account.', 'biscotti-cmp'),
                '<a href="' . esc_url($connect_url) . '">' . esc_html__('complete the setup', 'biscotti-cmp') . '</a>'
            );
            echo '</p></div>';
        }
    }

    /**
     * Plugin action links (Settings link under plugin name)
     * @param array $links
     * @return array
     */
    public function action_links($links)
    {
        $settings_link = '<a href="' . esc_url(admin_url('admin.php?page=biscotti-settings')) . '">'
            . esc_html__('Settings', 'biscotti-cmp') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    /**
     * Plugin activation
     */
    public function activate()
    {
        // Set default options if not already set
        if (!get_option('biscotti_options')) {
            update_option('biscotti_options', [
                'banner_enabled'    => true,
                'website_id'        => '',
                'api_key'           => '',
                'default_language'  => substr(get_locale(), 0, 2) ?: 'en',
                'show_floating_button' => true,
                'show_attribution'  => false,
            ]);
        }

        update_option('biscotti_installed', time());

        // Only flush rewrite rules if the plugin version changed
        $stored_version = get_option('biscotti_version', '');
        if ($stored_version !== BISCOTTI_VERSION) {
            update_option('biscotti_version', BISCOTTI_VERSION);
            flush_rewrite_rules();
        }
    }

    /**
     * Plugin deactivation
     */
    public function deactivate()
    {
        // Clear cached API responses
        $this->api->clear_cache();
        flush_rewrite_rules();
    }

    /**
     * Get the API client
     * @return Biscotti_API_Client
     */
    public function api()
    {
        return $this->api;
    }
}

// ============================================================================
// INITIALIZE
// ============================================================================

function biscotti_cmp()
{
    return Biscotti_CMP::get_instance();
}

biscotti_cmp();
