<?php
/**
 * Plugin Name:       ChainPay Payment Gateway
 * Plugin URI:        https://chainpay.store
 * Description:       Accept Bitcoin, Litecoin & 12+ cryptocurrencies non-custodially. Free: 50 payments/month with BTC+LTC. Pro license ($49/yr) unlocks unlimited payments, all 14 coins, per-domain activation. Powered by chainpay.store
 * Version:           1.1.0
 * Requires at least: 5.8
 * Requires PHP:      7.4
 * Author:            ChainPay
 * Author URI:        https://chainpay.store
 * License:           GPL-2.0-or-later
 * Text Domain:       chainpay
 * WC requires at least: 6.0
 * WC tested up to:   9.0
 */
defined( 'ABSPATH' ) || exit;

define( 'CHAINPAY_VERSION',         '1.1.0' );
define( 'CHAINPAY_FILE',            __FILE__ );
define( 'CHAINPAY_DIR',             plugin_dir_path( __FILE__ ) );
define( 'CHAINPAY_URL',             plugin_dir_url( __FILE__ ) );
define( 'CHAINPAY_API_BASE',        'https://api.chainpay.store/v1' );
define( 'CHAINPAY_FREE_LIMIT',      50 );   // payments per month on free plan
define( 'CHAINPAY_FREE_COINS',      array( 'BTC', 'LTC' ) );

/* ── Cron intervals ─────────────────────────────────────── */
add_filter( 'cron_schedules', function ( array $s ) {
    $s['chainpay_1min'] = array( 'interval' => 60,  'display' => 'Every Minute' );
    $s['chainpay_5min'] = array( 'interval' => 300, 'display' => 'Every 5 Minutes' );
    return $s;
} );

/* ── Boot ────────────────────────────────────────────────── */
add_action( 'plugins_loaded', 'chainpay_boot', 10 );

function chainpay_boot() {
    if ( ! class_exists( 'WooCommerce' ) ) {
        add_action( 'admin_notices', function () {
            echo '<div class="notice notice-error"><p><strong>ChainPay:</strong> WooCommerce must be installed and active.</p></div>';
        } );
        return;
    }

    require_once CHAINPAY_DIR . 'includes/class-chainpay-coin-registry.php';
    require_once CHAINPAY_DIR . 'includes/class-chainpay-license.php';
    require_once CHAINPAY_DIR . 'includes/class-chainpay-price-feed.php';
    require_once CHAINPAY_DIR . 'includes/class-chainpay-xpub.php';
    require_once CHAINPAY_DIR . 'includes/class-chainpay-invoice.php';
    require_once CHAINPAY_DIR . 'includes/class-chainpay-webhook.php';
    require_once CHAINPAY_DIR . 'includes/class-chainpay-emails.php';
    require_once CHAINPAY_DIR . 'includes/class-chainpay-gateway.php';
    require_once CHAINPAY_DIR . 'admin/class-chainpay-admin.php';
    require_once CHAINPAY_DIR . 'admin/class-chainpay-order-meta.php';

    add_filter( 'woocommerce_payment_gateways', function ( array $g ) {
        $g[] = 'ChainPay_Gateway';
        return $g;
    } );

    add_action( 'before_woocommerce_init', function () {
        if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
            \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', CHAINPAY_FILE, true );
        }
    } );

    if ( is_admin() ) {
        new ChainPay_Admin();
        new ChainPay_Order_Meta();
    }

    new ChainPay_Webhook();
    ChainPay_Emails::init();

    add_action( 'chainpay_cron_invoices', array( 'ChainPay_Invoice',    'cron_check' ) );
    add_action( 'chainpay_cron_prices',   array( 'ChainPay_Price_Feed', 'refresh_all' ) );
}

/* ── Activation ──────────────────────────────────────────── */
register_activation_hook( __FILE__, 'chainpay_activate' );

function chainpay_activate() {
    global $wpdb;
    $col = $wpdb->get_charset_collate();
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    dbDelta( "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}chainpay_invoices (
        id            BIGINT UNSIGNED     NOT NULL AUTO_INCREMENT,
        order_id      BIGINT UNSIGNED     NOT NULL,
        invoice_id    VARCHAR(64)         NOT NULL,
        coin          VARCHAR(20)         NOT NULL,
        network       VARCHAR(80)         NOT NULL DEFAULT '',
        address       VARCHAR(255)        NOT NULL DEFAULT '',
        amount_crypto DECIMAL(28,10)      NOT NULL DEFAULT '0',
        amount_fiat   DECIMAL(12,2)       NOT NULL DEFAULT '0',
        fiat_currency VARCHAR(10)         NOT NULL DEFAULT 'USD',
        exchange_rate DECIMAL(24,8)       NOT NULL DEFAULT '0',
        status        VARCHAR(30)         NOT NULL DEFAULT 'pending',
        tx_hash       VARCHAR(255)                 DEFAULT NULL,
        confirmations INT UNSIGNED                 DEFAULT 0,
        expires_at    DATETIME            NOT NULL,
        created_at    DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at    DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY   (id),
        UNIQUE KEY    invoice_id (invoice_id),
        KEY           order_id   (order_id),
        KEY           status     (status),
        KEY           created_at (created_at)
    ) $col;" );

    dbDelta( "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}chainpay_addresses (
        id         BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        coin       VARCHAR(20)     NOT NULL,
        address    VARCHAR(255)    NOT NULL,
        idx        INT UNSIGNED    NOT NULL DEFAULT 0,
        order_id   BIGINT UNSIGNED          DEFAULT NULL,
        used       TINYINT(1)      NOT NULL DEFAULT 0,
        created_at DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY  address   (address),
        KEY         coin_used (coin, used)
    ) $col;" );

    $defaults = array(
        'chainpay_api_mode'             => 'live',
        'chainpay_invoice_timeout'      => 15,
        'chainpay_underpayment_pct'     => 1,
        'chainpay_confirmed_status'     => 'processing',
        'chainpay_pending_status'       => 'on-hold',
        'chainpay_expired_status'       => 'cancelled',
        'chainpay_smart_routing'        => 'yes',
        'chainpay_show_qr'              => 'yes',
        'chainpay_show_timer'           => 'yes',
        'chainpay_show_rate'            => 'yes',
        'chainpay_show_fee'             => 'yes',
        'chainpay_underpayment_email'   => 'yes',
        'chainpay_enabled_coins'        => array( 'BTC', 'LTC' ),
        'chainpay_db_version'           => '1.1',
        // License / usage cache
        'chainpay_monthly_count'        => 0,
        'chainpay_monthly_reset'        => gmdate( 'Y-m' ),
        'chainpay_usage_last_sync'      => 0,
    );
    foreach ( $defaults as $k => $v ) {
        if ( false === get_option( $k ) ) update_option( $k, $v );
    }

    if ( ! wp_next_scheduled( 'chainpay_cron_invoices' ) ) {
        wp_schedule_event( time(), 'chainpay_1min', 'chainpay_cron_invoices' );
    }
    if ( ! wp_next_scheduled( 'chainpay_cron_prices' ) ) {
        wp_schedule_event( time(), 'chainpay_5min', 'chainpay_cron_prices' );
    }

    // Flush rewrite rules for IPN endpoint
    flush_rewrite_rules();
}

register_deactivation_hook( __FILE__, 'chainpay_deactivate' );
function chainpay_deactivate() {
    wp_clear_scheduled_hook( 'chainpay_cron_invoices' );
    wp_clear_scheduled_hook( 'chainpay_cron_prices' );
    flush_rewrite_rules();
}
