<?php
/**
 * POP – Free Electronic Invoices & Legal Documents Generator for eCommerce (ex-WooPop)
 *
 * Plugin Name: POP – Free Electronic Invoices & Legal Documents Generator for eCommerce (ex-WooPop)
 * Plugin URI: https://popapi.io/
 * Description: POP automatically configures your e-commerce to comply with European tax regulations. Your e-commerce
 * can generate electronic invoices in XML format and, thanks to our APIs, automatically transmit them to your
 * accounting software and tax authorities.
 *
 * Version: 6.9.8
 * Requires at least: 4.6
 * Requires PHP: 7.4
 * Author: POP
 * Author URI: https://popapi.io/
 * License: GPL-2.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: el-inv
 *
 * WC requires at least: 4.0
 * WC tested up to: 10.x.x
 *
 * Copyright (C) 2025 POP <info@popapi.io>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

// Is localhost?
$whitelist   = array('127.0.0.1', '::1');
$isLocalhost = isset($_SERVER['REMOTE_ADDR']) && in_array($_SERVER['REMOTE_ADDR'], $whitelist);
if (! defined('IS_LOCALHOST')) {
    define("IS_LOCALHOST", $isLocalhost);
}

// Define mode
if (! defined('WC_EL_INV_ENV')) {
    define('WC_EL_INV_ENV', 'prod');
}

// Plugin default config
define('WC_EL_INV_NAME', 'POP Electronic Invoice');
define('WC_EL_INV_TEXTDOMAIN', 'el-inv');
define('WC_EL_INV_VERSION', '6.9.8');
define('WC_EL_INV_VERSION_CLASS', str_replace('.', '_', WC_EL_INV_VERSION));
define('WC_EL_INV_PLUGIN_DIR', basename(plugin_dir_path(__FILE__)));
define('WC_EL_INV_DIR', plugin_dir_path(__FILE__));
define('WC_EL_INV_URL', plugin_dir_url(__FILE__));

// Plugin environments config (strict: no fallback to prod)
$rawEnv        = (string)WC_EL_INV_ENV;
$configBaseDir = trailingslashit(__DIR__) . 'config/environments/';

// Allow only safe env identifiers to avoid unexpected file resolution.
if (! preg_match('/^[a-zA-Z0-9_-]+$/', $rawEnv)) {
    if (is_admin()) {
        add_action('admin_notices', function () {
            $title   = esc_html__('POP - Environment configuration error:', WC_EL_INV_TEXTDOMAIN);
            $message = esc_html__('Invalid environment identifier configured in WC_EL_INV_ENV.', WC_EL_INV_TEXTDOMAIN);
            echo '<div class="notice notice-error"><p><strong>' . $title . '</strong> ' . $message . '</p></div>';
        });
    }

    error_log('[POP] Invalid WC_EL_INV_ENV value: ' . $rawEnv);

    return;
}

$configPath = $configBaseDir . $rawEnv . '.php';

if (! is_readable($configPath)) {
    if (is_admin()) {
        add_action('admin_notices', function () use ($configPath) {
            $title   = esc_html__('POP - Environment configuration error:', WC_EL_INV_TEXTDOMAIN);
            $message = sprintf(
                esc_html__('Missing or unreadable configuration file: %s', WC_EL_INV_TEXTDOMAIN),
                esc_html($configPath)
            );
            echo '<div class="notice notice-error"><p><strong>' . $title . '</strong> ' . $message . '</p></div>';
        });
    }

    error_log('[POP] Environment config missing/unreadable: ' . $configPath);

    return;
}

require_once $configPath;

// Base Requirements.
require_once untrailingslashit(WC_EL_INV_DIR . 'src/Plugin.php');
require_once untrailingslashit(WC_EL_INV_DIR . 'requires.php');
require_once untrailingslashit(WC_EL_INV_DIR . 'addon/init.php');

// Register the activation and deactivation hook.
register_activation_hook(__FILE__, array('WcElectronInvoice\\Activate', 'activate'));
register_deactivation_hook(__FILE__, array('WcElectronInvoice\\Deactivate', 'deactivate'));

// Plugin Init.
add_action('init', function () {

    if (method_exists(\WcElectronInvoice\Plugin::class, 'load_plugin_textdomain')) {
        // Load Localisation files.
        \WcElectronInvoice\Plugin::load_plugin_textdomain();
    }

    // Register WooCommerce provider (default)
    if (\WcElectronInvoice\Functions\isWooCommerceActive()) {
        $ordersProviderQuery = \WcElectronInvoice\Providers\OrderQuery::instance();
        $ordersProviderQuery->register_provider(new \WcElectronInvoice\WooCommerce\Providers\OrdersProvider());
    }

    // Init - Check and set the next number
    \WcElectronInvoice\Functions\setNextNumber();

    // Reset numerations
    \WcElectronInvoice\Functions\resetNumerationsOnYearChange();

    $filters = array();

    // Global filter
    $filters = array_merge(
        $filters,
        include \WcElectronInvoice\Plugin::getPluginDirPath('/inc/filters.php')
    );

    // Admin filter
    if (is_admin()) {
        $filters = array_merge(
            $filters,
            include \WcElectronInvoice\Plugin::getPluginDirPath('/inc/filtersAdmin.php')
        );
    } // Front filter
    else {
        $filters = array_merge(
            $filters,
            include \WcElectronInvoice\Plugin::getPluginDirPath('/inc/filtersFront.php')
        );
    }

    // Loader init.
    $init = new WcElectronInvoice\Init(new WcElectronInvoice\Loader(), $filters);
    $init->init();

    // Load providers
    do_action('wc_el_inv-enqueue_orders_provider');
    do_action('wc_el_inv-enqueue_taxes_provider');
    do_action('wc_el_inv-enqueue_products_provider');

    // Settings plugin init.
    \WcElectronInvoice\Admin\Settings\OptionPage::init();

    // Providers not active, lets notice.
    if (! \WcElectronInvoice\Functions\haveAnActiveProvider()) {
        \WcElectronInvoice\Functions\pluginNotice();
    }
}, 10);

// After plugin bootstrap
// @hooked integrations
do_action('wc_el_inv-after_init');

// WooCommerce Support for High-Performance Order Storage
add_action('before_woocommerce_init', function () {
    if (\WcElectronInvoice\Functions\isWooCommerceActive()) {
        if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
            \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
                'custom_order_tables',
                __FILE__,
                true
            );
        }
    }
});

/** ---------------------------------------------------------------------------------------------------------------- **/
/**
 * POP checkout > WooCommerce Block
 */
// Init editor block
add_action('current_screen', function ($screen) {
    if (\WcElectronInvoice\Functions\isWooCommerceActive()) {
        if (property_exists($screen, 'is_block_editor') && $screen->is_block_editor && $screen->post_type === 'page') {
            $postID = \WcElectronInvoice\Functions\filterInput($_GET, 'post', FILTER_SANITIZE_NUMBER_INT);
            if ($postID && has_block('woocommerce/checkout', get_post_field('post_content', $postID))) {
                \WcElectronInvoice\WooCommerce\Fields\InvoiceFields::popCheckoutBlockInit();
            }
        }
    }
});
// Init frontend block
add_action('template_redirect', function () {
    if (\WcElectronInvoice\Functions\isWooCommerceActive()) {
        $checkoutID = wc_get_page_id('checkout');
        if ($checkoutID && has_block('woocommerce/checkout', get_post_field('post_content', $checkoutID))) {
            if (is_checkout()) {
                \WcElectronInvoice\WooCommerce\Fields\InvoiceFields::popCheckoutBlockInit();
            }
        }
    }
});
// Validation
// use hook: woocommerce_store_api_cart_errors
add_action('init', function () {
    \WcElectronInvoice\WooCommerce\Fields\InvoiceFields::popCheckoutBlockValidationInit();
});
// Save meta
// use hook: woocommerce_store_api_checkout_update_order_from_request
add_action('init', function () {
    \WcElectronInvoice\WooCommerce\Fields\InvoiceFields::popCheckoutBlockSaveData();
});
/** ---------------------------------------------------------------------------------------------------------------- **/
