<?php
/**
 * Plugin Name: GR UPN payment form PRO
 * Description: PRO add-on for GR UPN payment form.
 * Version: 1.4.1
 * Author: Grega78
 * Author URI: https://gregarednak.si
 * Text Domain: gr-upn-payment-form-pro
 * Tested up to: 6.8
 * Stable tag: 1.4.1
 * Requires PHP: 8.2
 * Tags: woocommerce, qr, upn, slovenia, bacs
 * Domain Path: /languages
 * License: GPL-3.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 */

namespace GrUpnPf\Pro;

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

// === Freemius SDK bootstrap ===
if (!function_exists('grupnpf_pro_fs')) {
    function grupnpf_pro_fs()
    {
        global $grupnpf_pro_fs;
        if (!isset($grupnpf_pro_fs)) {
            require_once dirname(__FILE__) . '/vendor/freemius/wordpress-sdk/start.php';
            $grupnpf_pro_fs = fs_dynamic_init([
                'id' => '14756',
                'slug' => 'gr-upn-payment-form-pro',
                'type' => 'plugin',
                'public_key' => 'pk_82748159feee520dfb4bf6fec3797',
                'is_premium' => true,
                'is_premium_only' => true,
                'has_paid_plans' => true,
                'menu' => [
                    'first-path' => 'plugins.php',
                    'contact' => false,
                    'support' => false,
                ],
            ]);
        }
        return $grupnpf_pro_fs;
    }

    // Init Freemius as early as possible.
    grupnpf_pro_fs();
}

// Require the Composer autoloader.
require_once dirname(__FILE__) . '/vendor/autoload.php';

class GrUpnPf_Pro
{
    private static $instance;

    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        add_action('plugins_loaded', [$this, 'init'], 20);
        add_action('init', [$this, 'load_textdomain']);
        add_filter('plugin_action_links_gr-upn-payment-form/gr-upn-payment-form.php', [$this, 'remove_deactivation_link']);
    }

    public function remove_deactivation_link($links)
    {
        if (isset($links['deactivate'])) {
            unset($links['deactivate']);
        }
        return $links;
    }

    public function load_textdomain()
    {
        load_textdomain('gr-upn-payment-form-pro', WP_LANG_DIR . '/gr-upn-payment-form-pro/gr-upn-payment-form-pro-' . determine_locale() . '.mo');
    }

    public function init()
    {
        if (!self::is_parent_active()) {
            add_action('admin_notices', [$this, 'parent_not_active_notice']);
            return;
        }

        self::fs();

        if (self::is_premium()) {
            define('GRUPNPF_PRO_ACTIVE', true);
            // Load features after WooCommerce is fully loaded
            add_action('plugins_loaded', [$this, 'maybe_load_features'], 30);
            add_action('admin_notices', [$this, 'admin_notice']);
        } else {
            add_action('admin_notices', [$this, 'license_not_active_notice']);
        }
    }

    public function maybe_load_features()
    {
        if (class_exists('WooCommerce')) {
            new GrUpnPf_Pro_Features();
        } else {
            add_action('admin_notices', function () {
                echo '<div class="notice notice-error"><p>'
                    . esc_html__('WooCommerce mora biti aktiviran za delovanje GR UPN PRO funkcionalnosti.', 'gr-upn-payment-form-pro')
                    . '</p></div>';
            });
        }
    }

    public function license_not_active_notice()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $message = __('Vaša licenca za GR UPN Plačilni nalog PRO ni aktivna. Prosimo, aktivirajte jo za uporabo vseh funkcij PRO različice.', 'gr-upn-payment-form-pro');

        echo '<div class="notice notice-warning"><p>'
            . esc_html($message)
            . '</p></div>';
    }


    public function parent_not_active_notice()
    {
        $plugins = get_plugins();
        $parent_plugin_slug = 'gr-upn-payment-form/gr-upn-payment-form.php';

        if (isset($plugins[$parent_plugin_slug])) {
            // Parent plugin is installed but not active
            $action_url = wp_nonce_url(admin_url('plugins.php?action=activate&plugin=' . $parent_plugin_slug), 'activate-plugin_' . $parent_plugin_slug);
            $action_text = __('Aktivirajte brezplačno različico', 'gr-upn-payment-form-pro');
            $message = __('GR UPN plačilni nalog PRO zahteva aktivno brezplačno različico vtičnika.', 'gr-upn-payment-form-pro');
            $link_html = ' <a href="' . esc_url($action_url) . '">' . esc_html($action_text) . '</a>';
        } else {
            // Parent plugin is not installed
            $action_url = 'https://gregarednak.si/gr-upn-payment-form-zip-download';
            $action_text = __('Naložite brezplačno različico', 'gr-upn-payment-form-pro');
            $message = __('GR UPN plačilni nalog PRO zahteva brezplačno različico. Prosimo, naložite in namestite jo.', 'gr-upn-payment-form-pro');
            $link_html = ' <a href="' . esc_url($action_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($action_text) . '</a>';
        }

        echo '<div class="notice notice-error"><p>' .
            esc_html($message) .
            wp_kses_post($link_html) .
            '</p></div>';
    }

    public static function activate()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'grupnpf_usage';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id MEDIUMINT(9) UNSIGNED NOT NULL AUTO_INCREMENT,
            order_id BIGINT(20) UNSIGNED NOT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY order_id (order_id)
        ) $charset_collate;";


        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);

        // Set default options for PRO features on activation
        add_option('grupnpf_email_vstavi_upn', 'yes');
        add_option('grupnpf_email_priponka', 'yes');
        add_option('grupnpf_thankyou_page', 'yes');
    }

    public static function fs()
    {
        return grupnpf_pro_fs();
    }


    public static function get_current_usage()
    {
        global $wpdb;

        $table_name = $wpdb->prefix . 'grupnpf_usage';
        $current_month = gmdate('n');
        $current_year = gmdate('Y');
        $transient_key = 'grupnpf_current_usage_' . $current_month . '_' . $current_year;

        // Try transient cache first
        $usage = get_transient($transient_key);
        if (false !== $usage) {
            return $usage;
        }

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $usage = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(id) FROM `{$table_name}` WHERE MONTH(created_at) = %d AND YEAR(created_at) = %d",
            $current_month,
            $current_year
        ));

        set_transient($transient_key, $usage, HOUR_IN_SECONDS);

        return $usage;
    }

    public static function log_usage($order_id)
    {
        $order_id = (int) $order_id;
        global $wpdb;

        $table_name = $wpdb->prefix . 'grupnpf_usage';

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $existing_order = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT id FROM `{$table_name}` WHERE order_id = %d",
                $order_id
            )
        );

        if (null === $existing_order) {
            $wpdb->insert(
                $table_name,
                [
                    'order_id' => $order_id,
                    'created_at' => current_time('mysql'),
                ]
            );
            delete_transient('grupnpf_current_usage_' . gmdate('n') . '_' . gmdate('Y'));
        }
    }


    public static function is_parent_active()
    {
        return class_exists('GrUpnPf\\GrUpnPf_Logic_UPN');
    }

    public static function is_premium()
    {
        return self::fs()->is_premium();
    }

    public static function get_usage_limitations()
    {
        if (!self::is_premium())
            return 0;
        $plan = self::fs()->get_plan();
        if (!$plan)
            return 0;
        if ($plan->name === 'pro')
            return -1;
        if ($plan->name === 'starter')
            return 100;
        return 0;
    }

    public function admin_notice()
    {
        $limit = self::get_usage_limitations();
        $usage = self::get_current_usage();

        if ($limit === -1 || $limit === 0)
            return;

        $remaining = $limit - $usage;

        if ($remaining <= 0) {
            $class = 'notice notice-error';
            $message = __('Dosegli ste mesečno omejitev UPN obrazcev. Prosimo, nadgradite svoj paket, da boste lahko nadaljevali z uporabo vtičnika.', 'gr-upn-payment-form-pro');
        } elseif ($remaining <= 10) {
            $class = 'notice notice-warning';
            /* translators: %d: remaining usages */
            $message = sprintf(__('Približujete se mesečni omejitvi UPN obrazcev. Na voljo vam je še %d.', 'gr-upn-payment-form-pro'), $remaining);
        } else {
            return;
        }

        printf('<div class="%1$s"><p>%2$s</p></div>', esc_attr($class), esc_html($message));
    }
}

// Instantiate the plugin.
GrUpnPf_Pro::instance();

// Register activation hook.
register_activation_hook(__FILE__, [GrUpnPf_Pro::class, 'activate']);