<?php
/**
 * Plugin Name: WooCommerce ObliqPay Gateway
 * Plugin URI: https://obliqpay.com
 * Description: Accept payments via ObliqPay payment gateway for WooCommerce
 * Version: 1.0.0
 * Author: Your Name
 * Author URI: https://yourwebsite.com
 * Text Domain: wc-obliqpay-gateway
 * Domain Path: /languages
 * Requires at least: 5.0
 * Requires PHP: 7.2
 * WC requires at least: 3.0
 * WC tested up to: 8.0
 *
 * @package WC_ObliqPay_Gateway
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Define plugin constants
define('WC_OBLIQPAY_VERSION', '1.0.0');
define('WC_OBLIQPAY_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WC_OBLIQPAY_PLUGIN_URL', plugin_dir_url(__FILE__));

/**
 * Check if WooCommerce is active
 */
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    return;
}

/**
 * Add the gateway to WooCommerce
 */
add_filter('woocommerce_payment_gateways', 'wc_obliqpay_add_gateway');
function wc_obliqpay_add_gateway($gateways) {
    $gateways[] = 'WC_ObliqPay_Gateway';
    return $gateways;
}

/**
 * Initialize the gateway
 */
add_action('plugins_loaded', 'wc_obliqpay_gateway_init');
function wc_obliqpay_gateway_init() {
    
    if (!class_exists('WC_Payment_Gateway')) {
        return;
    }

    /**
     * ObliqPay Payment Gateway Class
     */
    class WC_ObliqPay_Gateway extends WC_Payment_Gateway {

        /**
         * API Base URL
         */
        const API_BASE_URL = 'https://api.obliqpay.com';

        /**
         * Constructor
         */
        public function __construct() {
            $this->id                 = 'obliqpay';
            $this->icon               = apply_filters('woocommerce_obliqpay_icon', '');
            $this->has_fields         = false;
            $this->method_title       = __('ObliqPay', 'wc-obliqpay-gateway');
            $this->method_description = __('Accept payments via ObliqPay - supports multiple cryptocurrencies and payment methods.', 'wc-obliqpay-gateway');

            // Load the settings
            $this->init_form_fields();
            $this->init_settings();

            // Define user set variables
            $this->title              = $this->get_option('title');
            $this->description        = $this->get_option('description');
            $this->api_key            = $this->get_option('api_key');
            $this->test_mode          = 'yes' === $this->get_option('test_mode');
            $this->debug              = 'yes' === $this->get_option('debug', 'no');
            $this->redirect_type      = $this->get_option('redirect_type', 'same_window');

            // Logs
            if ($this->debug) {
                $this->log = wc_get_logger();
            }

            // Actions
            add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
            add_action('woocommerce_api_wc_obliqpay_gateway', array($this, 'webhook_handler'));
            add_action('woocommerce_thankyou_' . $this->id, array($this, 'thankyou_page'));
        }

        /**
         * Initialize Gateway Settings Form Fields
         */
        public function init_form_fields() {
            $this->form_fields = array(
                'enabled' => array(
                    'title'   => __('Enable/Disable', 'wc-obliqpay-gateway'),
                    'type'    => 'checkbox',
                    'label'   => __('Enable ObliqPay Payment Gateway', 'wc-obliqpay-gateway'),
                    'default' => 'no'
                ),
                'title' => array(
                    'title'       => __('Title', 'wc-obliqpay-gateway'),
                    'type'        => 'text',
                    'description' => __('This controls the title which the user sees during checkout.', 'wc-obliqpay-gateway'),
                    'default'     => __('ObliqPay', 'wc-obliqpay-gateway'),
                    'desc_tip'    => true,
                ),
                'description' => array(
                    'title'       => __('Description', 'wc-obliqpay-gateway'),
                    'type'        => 'textarea',
                    'description' => __('This controls the description which the user sees during checkout.', 'wc-obliqpay-gateway'),
                    'default'     => __('Pay securely with cryptocurrency or other payment methods via ObliqPay.', 'wc-obliqpay-gateway'),
                    'desc_tip'    => true,
                ),
                'api_key' => array(
                    'title'       => __('API Key', 'wc-obliqpay-gateway'),
                    'type'        => 'password',
                    'description' => __('Enter your ObliqPay API Key. You can get this from your ObliqPay dashboard.', 'wc-obliqpay-gateway'),
                    'default'     => '',
                    'desc_tip'    => true,
                ),
                'test_mode' => array(
                    'title'       => __('Test Mode', 'wc-obliqpay-gateway'),
                    'type'        => 'checkbox',
                    'label'       => __('Enable Test Mode', 'wc-obliqpay-gateway'),
                    'default'     => 'yes',
                    'description' => __('Place the payment gateway in test mode using test API keys.', 'wc-obliqpay-gateway'),
                ),
                'redirect_type' => array(
                    'title'       => __('Redirect Type', 'wc-obliqpay-gateway'),
                    'type'        => 'select',
                    'description' => __('Choose how to redirect customers to the payment page.', 'wc-obliqpay-gateway'),
                    'default'     => 'same_window',
                    'desc_tip'    => true,
                    'options'     => array(
                        'same_window' => __('Same Window', 'wc-obliqpay-gateway'),
                        'new_tab'     => __('New Tab', 'wc-obliqpay-gateway'),
                    ),
                ),
                'debug' => array(
                    'title'       => __('Debug Log', 'wc-obliqpay-gateway'),
                    'type'        => 'checkbox',
                    'label'       => __('Enable logging', 'wc-obliqpay-gateway'),
                    'default'     => 'no',
                    'description' => sprintf(__('Log ObliqPay events inside %s', 'wc-obliqpay-gateway'), '<code>' . WC_Log_Handler_File::get_log_file_path('obliqpay') . '</code>'),
                ),
                'webhook_info' => array(
                    'title'       => __('Webhook URL', 'wc-obliqpay-gateway'),
                    'type'        => 'title',
                    'description' => sprintf(
                        __('Your webhook URL is: %s<br>Use this URL in your ObliqPay dashboard or when creating orders.', 'wc-obliqpay-gateway'),
                        '<code>' . home_url('/wc-api/wc_obliqpay_gateway') . '</code>'
                    ),
                ),
            );
        }

        /**
         * Process the payment
         */
        public function process_payment($order_id) {
            $order = wc_get_order($order_id);

            try {
                // Create ObliqPay order
                $obliqpay_order = $this->create_obliqpay_order($order);

                if (!$obliqpay_order || !isset($obliqpay_order['checkoutUrl'])) {
                    throw new Exception(__('Failed to create ObliqPay order.', 'wc-obliqpay-gateway'));
                }

                // Store the ObliqPay order ID
                $order->update_meta_data('_obliqpay_order_id', $obliqpay_order['orderId']);
                $order->update_meta_data('_obliqpay_checkout_url', $obliqpay_order['checkoutUrl']);
                $order->save();

                // Mark as pending payment
                $order->update_status('pending', __('Awaiting ObliqPay payment.', 'wc-obliqpay-gateway'));

                // Log
                if ($this->debug) {
                    $this->log->info('ObliqPay order created', array(
                        'source' => 'obliqpay',
                        'order_id' => $order_id,
                        'obliqpay_order_id' => $obliqpay_order['orderId']
                    ));
                }

                // Return success and redirect
                return array(
                    'result'   => 'success',
                    'redirect' => $obliqpay_order['checkoutUrl']
                );

            } catch (Exception $e) {
                wc_add_notice(__('Payment error: ', 'wc-obliqpay-gateway') . $e->getMessage(), 'error');
                
                if ($this->debug) {
                    $this->log->error('Payment processing failed', array(
                        'source' => 'obliqpay',
                        'order_id' => $order_id,
                        'error' => $e->getMessage()
                    ));
                }
                
                return array(
                    'result'   => 'fail',
                    'redirect' => ''
                );
            }
        }

        /**
         * Create ObliqPay order via API
         */
        private function create_obliqpay_order($order) {
            $amount = floatval($order->get_total());
            $currency = strtolower($order->get_currency());
            $email = $order->get_billing_email();

            $body = array(
                'amount'      => $amount,
                'currency'    => $currency,
                'email'       => $email,
                'webhook_url' => home_url('/wc-api/wc_obliqpay_gateway')
            );

            $args = array(
                'method'  => 'POST',
                'headers' => array(
                    'Authorization' => 'Bearer ' . $this->api_key,
                    'Content-Type'  => 'application/json',
                ),
                'body'    => json_encode($body),
                'timeout' => 30,
            );

            if ($this->debug) {
                $this->log->info('Creating ObliqPay order', array(
                    'source' => 'obliqpay',
                    'request' => $body
                ));
            }

            $response = wp_remote_post(self::API_BASE_URL . '/orders', $args);

            if (is_wp_error($response)) {
                throw new Exception($response->get_error_message());
            }

            $response_code = wp_remote_retrieve_response_code($response);
            $response_body = wp_remote_retrieve_body($response);
            $data = json_decode($response_body, true);

            if ($this->debug) {
                $this->log->info('ObliqPay API response', array(
                    'source' => 'obliqpay',
                    'status_code' => $response_code,
                    'response' => $data
                ));
            }

            if ($response_code !== 200 && $response_code !== 201) {
                $error_message = isset($data['detail']) ? $data['detail'] : 'Unknown error';
                throw new Exception(sprintf(__('API Error (%d): %s', 'wc-obliqpay-gateway'), $response_code, $error_message));
            }

            return $data;
        }

        /**
         * Check order status via API
         */
        private function check_order_status($obliqpay_order_id) {
            $args = array(
                'method'  => 'GET',
                'headers' => array(
                    'Authorization' => 'Bearer ' . $this->api_key,
                ),
                'timeout' => 30,
            );

            $response = wp_remote_get(self::API_BASE_URL . '/orders/' . $obliqpay_order_id, $args);

            if (is_wp_error($response)) {
                return false;
            }

            $response_code = wp_remote_retrieve_response_code($response);
            $response_body = wp_remote_retrieve_body($response);
            $data = json_decode($response_body, true);

            if ($response_code === 200) {
                return $data;
            }

            return false;
        }

        /**
         * Webhook handler
         */
        public function webhook_handler() {
            $raw_post = file_get_contents('php://input');
            $data = json_decode($raw_post, true);

            if ($this->debug) {
                $this->log->info('Webhook received', array(
                    'source' => 'obliqpay',
                    'data' => $data
                ));
            }

            // Validate webhook data
            if (!isset($data['order_id']) || !isset($data['event'])) {
                if ($this->debug) {
                    $this->log->error('Invalid webhook data', array('source' => 'obliqpay'));
                }
                status_header(400);
                exit;
            }

            $obliqpay_order_id = sanitize_text_field($data['order_id']);
            $event = sanitize_text_field($data['event']);

            // Find the WooCommerce order
            $orders = wc_get_orders(array(
                'meta_key'   => '_obliqpay_order_id',
                'meta_value' => $obliqpay_order_id,
                'limit'      => 1,
            ));

            if (empty($orders)) {
                if ($this->debug) {
                    $this->log->error('Order not found for webhook', array(
                        'source' => 'obliqpay',
                        'obliqpay_order_id' => $obliqpay_order_id
                    ));
                }
                status_header(404);
                exit;
            }

            $order = $orders[0];

            // Process webhook based on event type
            if ($event === 'payment.completed' && isset($data['status']) && $data['status'] === 'completed') {
                if ($order->get_status() !== 'completed' && $order->get_status() !== 'processing') {
                    $order->payment_complete();
                    $order->add_order_note(
                        sprintf(
                            __('ObliqPay payment completed. Order ID: %s, Amount: %s %s', 'wc-obliqpay-gateway'),
                            $obliqpay_order_id,
                            $data['amount'],
                            strtoupper($data['currency'])
                        )
                    );

                    if ($this->debug) {
                        $this->log->info('Payment completed via webhook', array(
                            'source' => 'obliqpay',
                            'wc_order_id' => $order->get_id(),
                            'obliqpay_order_id' => $obliqpay_order_id
                        ));
                    }
                }
            }

            status_header(200);
            exit;
        }

        /**
         * Thank you page
         */
        public function thankyou_page($order_id) {
            $order = wc_get_order($order_id);
            $obliqpay_order_id = $order->get_meta('_obliqpay_order_id');

            if ($obliqpay_order_id && $order->get_status() === 'pending') {
                // Check order status
                $status = $this->check_order_status($obliqpay_order_id);
                
                if ($status && isset($status['status']) && $status['status'] === 'completed') {
                    $order->payment_complete();
                    $order->add_order_note(__('Payment verified and completed via ObliqPay.', 'wc-obliqpay-gateway'));
                }

                if ($order->get_status() === 'pending') {
                    echo '<div class="woocommerce-info">';
                    echo __('Your payment is being processed. You will receive a confirmation email once the payment is complete.', 'wc-obliqpay-gateway');
                    echo '</div>';
                }
            }
        }

        /**
         * Admin options
         */
        public function admin_options() {
            ?>
            <h2><?php echo esc_html($this->get_method_title()); ?></h2>
            <p><?php echo esc_html($this->get_method_description()); ?></p>
            <table class="form-table">
                <?php $this->generate_settings_html(); ?>
            </table>
            <?php
        }
    }
}

/**
 * Add custom action links
 */
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'wc_obliqpay_action_links');
function wc_obliqpay_action_links($links) {
    $plugin_links = array(
        '<a href="' . admin_url('admin.php?page=wc-settings&tab=checkout&section=obliqpay') . '">' . __('Settings', 'wc-obliqpay-gateway') . '</a>',
    );
    return array_merge($plugin_links, $links);
}
