<?php
/**
 * Plugin Name: GR Odstop od pogodbe
 * Description: Skladnost s predpisi EU (Direktiva 2011/83/EU) in slovenskim ZVPot-1 glede gumba in elektronskega odstopa od pogodbe.
 * Version: 1.0.1
 * Author: Grega78
 * Author URI: https://gregarednak.si
 * Text Domain: gr-odstop-od-pogodbe
 * Domain Path: /languages
 * Tested up to: 7.0
 * Stable tag: 1.0.1
 * Requires PHP: 7.4
 * Tags: woocommerce, odstop od pogodbe, consumer rights, slovenia
 * License: GPL-3.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 */

/*
GR Odstop od pogodbe
Copyright (C) 2026 Grega Rednak

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 3 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, see <https://www.gnu.org/licenses/>.
*/

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

// Make sure to use the Composer autoloader:
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

if (function_exists('oop_fs')) {
    oop_fs()->set_basename(true, __FILE__);
} else {
    // DO NOT REMOVE THIS IF, IT IS ESSENTIAL FOR THE `function_exists` CALL ABOVE TO PROPERLY WORK.
    if (!function_exists('oop_fs')) {
        // Create a helper function for easy SDK access.
        function oop_fs() {
            global $oop_fs;

            if (!isset($oop_fs)) {
                // Include Freemius SDK.
                // SDK is auto-loaded through Composer
                $oop_fs = fs_dynamic_init(array(
                    'id'                  => '32283',
                    'slug'                => 'odstop-od-pogodbe',
                    'type'                => 'plugin',
                    'public_key'          => 'pk_28692b39ae1daaf1d11ea525acaf5',
                    'is_premium'          => true,
                    'premium_suffix'      => 'pro',
                    'has_premium_version' => true,
                    'has_addons'          => false,
                    'has_paid_plans'      => true,
                    'is_org_compliant'    => true,
                    'wp_org_gatekeeper'   => 'OA7#BoRiBNqdf52FvzEf!!074aRLPs8fspif$7K1#4u4Csys1fQlCecVcUTOs2mcpeVHi#C2j9d09fOTvbC0HloPT7fFee5WdS3G',
                    'trial'               => array(
                        'days'               => 14,
                        'is_require_payment' => true,
                    ),
                    'menu'                => array(
                        'support'        => false,
                    ),
                ));
            }

            return $oop_fs;
        }

        // Init Freemius.
        oop_fs();
        // Signal that SDK was initiated.
        do_action('oop_fs_loaded');
    }
}

// Hook the uninstall cleanup function to Freemius after_uninstall action
if (function_exists('oop_fs')) {
    oop_fs()->add_action('after_uninstall', 'oop_fs_uninstall_cleanup');
}

/**
 * Cleanup database tables and settings options on plugin uninstall.
 */
function oop_fs_uninstall_cleanup() {
    global $wpdb;

    // 1. Drop the custom database table
    $table_name = $wpdb->prefix . 'grcop_withdrawals';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $wpdb->query("DROP TABLE IF EXISTS {$table_name}");

    // 2. Delete plugin settings options
    $options = [
        'grcop_withdrawal_window',
        'grcop_eligible_statuses',
        'grcop_form_page',
        'grcop_enable_footer_link',
        'grcop_button_text',
        'grcop_email_btn_bg_color',
        'grcop_email_btn_text_color',
        'grcop_btn_bg_color',
        'grcop_btn_text_color',
        'grcop_btn_border_radius',
        'grcop_form_bg_color',
        'grcop_form_border_radius',
        'grcop_return_address',
        'grcop_excluded_categories',
        'grcop_excluded_products',
        'grcop_refund_methods',
        'grcop_email_customer_subject',
        'grcop_email_customer_body',
        'grcop_email_admin_subject',
        'grcop_email_admin_body',
        'grcop_email_admin_recipient',
        'grcop_enable_debug_logging',
        'grcop_do_activation_redirect',
        'grcop_setup_wizard_completed',
        'grcop_tax_display'
    ];

    foreach ($options as $option) {
        delete_option($option);
    }
}

/**
 * Global logging function for the plugin.
 *
 * @param mixed $message The message to log.
 */
function grcop_log($message)
{
    if (get_option('grcop_enable_debug_logging') === 'yes') {
        if (is_array($message) || is_object($message)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
            $message = print_r($message, true);
        }
        
        $upload_dir = wp_upload_dir();
        $log_dir = $upload_dir['basedir'] . '/grcop-logs';
        
        if (!file_exists($log_dir)) {
            wp_mkdir_p($log_dir);
            @file_put_contents($log_dir . '/index.html', '');
            @file_put_contents($log_dir . '/.htaccess', "Deny from all\n");
        }
        
        $log_file = $log_dir . '/debug.log';
        $timestamp = current_time('mysql');
        $log_entry = sprintf("[%s] %s\n", $timestamp, $message);
        
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
        @error_log($log_entry, 3, $log_file);
        
        if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('[GR ODSTOP DEBUG] ' . $message);
        }
    }
}

if (!defined('GRCOP_PLUGIN_FILE')) {
    define('GRCOP_PLUGIN_FILE', __FILE__);
}

// Register activation and deactivation hooks.
register_activation_hook(__FILE__, ['GrCop\GrCop_Main', 'activate']);
register_deactivation_hook(__FILE__, ['GrCop\GrCop_Main', 'deactivate']);

// Declare compatibility with High-Performance Order Storage (HPOS)
add_action('before_woocommerce_init', function () {
    if (class_exists('\Automattic\WooCommerce\Utilities\FeaturesUtil')) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', GRCOP_PLUGIN_FILE, true);
    }
});

if (file_exists(plugin_dir_path(__FILE__) . 'vendor/autoload.php')) {
    require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
} else {
    // Fallback PSR-4 autoloader for GrCop namespace
    spl_autoload_register(function ($class) {
        $prefix = 'GrCop\\';
        $base_dir = plugin_dir_path(__FILE__) . 'src/';
        
        $len = strlen($prefix);
        if (strncmp($prefix, $class, $len) !== 0) {
            return;
        }
        
        $relative_class = substr($class, $len);
        $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
        
        if (file_exists($file)) {
            require_once $file;
        }
    });
}

if (class_exists('GrCop\GrCop_Main')) {
    new GrCop\GrCop_Main();
}