<?php
/*
Plugin Name: Ada Payments for WooCommerce
Plugin URI: https://wordpress.org/plugins/adapayments-for-woocommerce/
Description: Accept payments in Cardano (ADA) cryptocurrency via WooCommerce.
Version: 1.1.1
Requires at least: 5.0
Tested up to: 7.0
Requires PHP: 7.4
Author: Lidonation
Author URI: https://www.lidonation.com
License: GPL v2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Requires Plugins: woocommerce
*/


declare(strict_types=1);

defined('ABSPATH') || exit;

use LidonationDevs\ADAPAYFWC\Admin\Setup;

if (!defined('MAIN_PLUGIN_FILE')) {
    define('ADAPAYFWC_PLUGIN_FILE', __FILE__);
    define('ADAPAYFWC_PLUGIN_DIR', plugin_dir_path(__FILE__));
    define('ADAPAYFWC_PLUGIN_URL', plugin_dir_url(__FILE__));
}

include_once plugin_dir_path(__FILE__) . 'includes/custom-thankyou.php';

add_action('plugins_loaded', 'ADAPAYFWC_start_plugin', 0);
function ADAPAYFWC_start_plugin(): void
{
    if (!class_exists('WC_Payment_Gateway')) {
        return;
    }

    include_once ADAPAYFWC_PLUGIN_DIR . 'includes/helpers.php';

    // Only instantiate Setup if the class actually exists to prevent fatal errors.
    if (is_admin() && class_exists(Setup::class)) {
        new Setup();
    }

    include(plugin_dir_path(__FILE__) . 'adapayment-gateway.php');
}

add_filter('woocommerce_payment_gateways', 'ADAPAYFWC_start_gateway');
function ADAPAYFWC_start_gateway($gateways): mixed
{
    $gateways[] = 'ADAPAYFWC_GateWay';
    return $gateways;
}

// create tx table for recording
register_activation_hook(__FILE__, 'ADAPAYFWC_setup_tables');
function ADAPAYFWC_setup_tables(): void
{
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();

    $order_value_table   = "{$wpdb->prefix}ada_payments";

    $sql = "
        CREATE TABLE {$order_value_table} (
        `order_id` int(11) unsigned not null auto_increment,
        `lovelace_value` bigint unsigned not null,
        `conversion_rate` decimal(18,6) not null,
        `tx_hash` varchar(120),
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        primary key (`order_id`)
    ) {$charset_collate};
    ";


    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    $wpdb->show_errors();
    $wpdb->print_error();
}


/**
 * Custom function to declare compatibility with cart_checkout_blocks feature
 */
function ADAPAYFWC_register_checkout_blocks(): void
{
    // Check if the required class exists
    if (class_exists('\Automattic\WooCommerce\Utilities\FeaturesUtil')) {
        // Declare compatibility for 'cart_checkout_blocks'
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
    }
}
// Hook the custom function to the 'before_woocommerce_init' action
add_action('before_woocommerce_init', 'ADAPAYFWC_register_checkout_blocks');

// Hook the custom function to the 'woocommerce_blocks_loaded' action
add_action('woocommerce_blocks_loaded', 'ADAPAYFWC_register_payment_method');

/**
 * Custom function to register a payment method type
 */
function ADAPAYFWC_register_payment_method(): void
{
    require_once plugin_dir_path(__FILE__) . 'adapayment-block.php';

    add_action(
        'woocommerce_blocks_payment_method_type_registration',
        function (Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry) {
            $payment_method_registry->register(new ADAPAYFWC_Blocks);
        }
    );
}


// add ada details to order
add_filter('manage_woocommerce_page_wc-orders_columns', 'ADAPAYFWC_add_tx_column');
function ADAPAYFWC_add_tx_column($columns): mixed
{
    $columns['adapayment_tx_hash'] = 'ADA Transaction Hash';

    return $columns;
}

add_filter('manage_woocommerce_page_wc-orders_custom_column', 'ADAPAYFWC_populate_tx_column', 10, 2);
function ADAPAYFWC_populate_tx_column($column_name, WC_Order $order): void
{
    global $wpdb;

    $table_name = esc_sql("{$wpdb->prefix}ada_payments");

    $tx_hash = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT tx_hash FROM $table_name WHERE order_id = %d",
            $order->get_id()
        )
    );

    $settings = get_option('woocommerce_ada_payment_settings');
    $network = isset($settings['network']) ? $settings['network'] : null;

    if ('adapayment_tx_hash' === $column_name && !!$tx_hash && !!$network) {
        $explorerLink = $network == 'Mainnet' ? "https://cexplorer.io/" . esc_html($tx_hash) : "https://preview.cexplorer.io/" . esc_html($tx_hash);
        $tx_hash_short = substr($tx_hash, 0, 12) . '...';

        echo '<a href="' . esc_html($explorerLink) . '" target="_blank" class="order-view">
            <strong>' . esc_html($tx_hash_short) . '</strong>
          </a>';
    }
}

/**
 * Custom endpoints
 */
add_action('rest_api_init', 'ADAPAYFWC_register_rest_routes');

function ADAPAYFWC_register_rest_routes(): void
{
    register_rest_route('adapayments-woocommerce/v1', '/complete-order', array(
        'methods' => 'POST',
        'callback' => 'ADAPAYFWC_update_order_status',
        'permission_callback' => function ($request) {
            $nonce = $request->get_header('X-WP-Nonce');
            if (wp_verify_nonce($nonce, 'wp_rest')) {
                return true;
            }
            $body = json_decode($request->get_body(), true);
            if (isset($body['nonce']) && wp_verify_nonce($body['nonce'], 'wp_rest')) {
                return true;
            }
            return new WP_Error('rest_cookie_invalid_nonce', 'Cookie check failed', array('status' => 403));
        }
    ));
}


function ADAPAYFWC_update_order_status(WP_REST_Request $request)
{
    $data = $request->get_json_params();
    if (empty($data)) {
        $data = json_decode($request->get_body(), true);
    }

    if (empty($data)) {
        return new WP_Error('invalid_payload', 'Invalid request payload', array('status' => 400));
    }

    $order_id = isset($data['order_id']) ? absint($data['order_id']) : 0;
    if (!$order_id || !($order = wc_get_order($order_id))) {
        return new WP_Error('invalid_order', 'Invalid Order ID', array('status' => 400));
    }

    if (!isset($data['payedAmt']) || !is_numeric($data['payedAmt']) || $data['payedAmt'] <= 0) {
        return new WP_Error('invalid_amount', 'Invalid amount', array('status' => 400));
    }

    if (empty($data['txHash']) || !preg_match('/^[a-f0-9]{64}$/i', $data['txHash'])) {
        return new WP_Error('invalid_tx', 'Invalid transaction hash', array('status' => 400));
    }

    try {
        if ($order->get_total() > 0) {
            $order->update_status('wc-processing', 'Payment to be confirmed. Tx: ' . sanitize_text_field($data['txHash']));
        } else {
            $order->payment_complete($data['txHash']);
        }

        $recorded = ADAPAYFWC_save_tx_details($data);
        if (!$recorded) {
            error_log('ADA Payment: Failed to save tx details for order ' . $order_id);
        }

        return rest_ensure_response(array('success' => true, 'order_id' => $order_id));
    } catch (Exception $e) {
        error_log('ADA Payment Error: ' . $e->getMessage());
        return new WP_Error('processing_error', $e->getMessage(), array('status' => 500));
    }
}

function ADAPAYFWC_save_tx_details($data)
{

    global $wpdb;
    $order_value_table = $wpdb->prefix . 'ada_payments';


    $data = array(
        'order_id' => absint($data['order_id']),
        'lovelace_value' => absint($data['payedAmt']),
        'conversion_rate' => floatval(ADAPAYFWC_convertion_rate_ada_to_usd()),
        'tx_hash' => sanitize_text_field($data['txHash']),
    );

    // Insert data into the table
    $result = $wpdb->insert($order_value_table, $data);

    if ($result === false) {
        $wpdb->show_errors();
        $wpdb->print_error();
    } else {
        return $result;
    }
}

function ADAPAYFWC_email_instructions()
{
    echo wp_kses_post(wpautop(wptexturize('Thank you for your payment. Your transaction has been completed,')) . PHP_EOL);
}
