<?php
/**
 * Plugin Name: Ogrodut Automated Payment Gateway for WooCommerce
 * Description: Accept automated bKash, Nagad, Rocket, Upay, and Bank transfers in WooCommerce with instant verification.
 * Version: 2.2.0
 * Author: Ogrodut
 */

if (!defined('ABSPATH')) {
    exit;
}

add_action('plugins_loaded', 'init_payautobd_wc_gateway', 11);

function init_payautobd_wc_gateway() {
    if (!class_exists('WC_Payment_Gateway')) {
        return;
    }

    class WC_Gateway_PayAutoBD extends WC_Payment_Gateway {
        public function __construct() {
            $this->id = 'payautobd';
            $this->has_fields = false;
            $this->method_title = 'Ogrodut Automated Gateway';
            $this->method_description = 'Automated bKash, Nagad, Rocket, Upay & Bank Checkout Gateway.';

            $this->init_form_fields();
            $this->init_settings();

            $this->title = $this->get_option('title');
            $this->description = $this->get_option('description');
            $this->public_key = $this->get_option('public_key');
            $this->secret_key = $this->get_option('secret_key');

            add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
            add_action('woocommerce_api_wc_gateway_payautobd', array($this, 'handle_webhook'));
        }

        public function init_form_fields() {
            $this->form_fields = array(
                'enabled' => array('title' => 'Enable/Disable', 'type' => 'checkbox', 'label' => 'Enable Ogrodut Payment Gateway', 'default' => 'yes'),
                'title' => array('title' => 'Checkout Title', 'type' => 'text', 'default' => 'bKash / Nagad / Rocket / Instant Pay'),
                'description' => array('title' => 'Customer Message', 'type' => 'textarea', 'default' => 'Pay securely via bKash, Nagad, Rocket, Upay, or Bank Transfer.'),
                'public_key' => array('title' => 'Brand Public Key', 'type' => 'text', 'default' => ''),
                'secret_key' => array('title' => 'Brand Secret Key', 'type' => 'password', 'default' => ''),
            );
        }

        public function process_payment($order_id) {
            $order = wc_get_order($order_id);
            $payload = array(
                'merchant_order_id' => (string) $order->get_id(),
                'product_title' => 'WooCommerce Order #' . $order->get_order_number(),
                'amount' => (float) $order->get_total(),
                'customer_name' => trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()),
                'customer_phone' => $order->get_billing_phone(),
                'customer_email' => $order->get_billing_email(),
                'store_domain' => parse_url(home_url(), PHP_URL_HOST),
                'success_url' => $this->get_return_url($order),
                'cancel_url' => $order->get_cancel_order_url(),
                'webhook_url' => WC()->api_request_url('WC_Gateway_PayAutoBD'),
            );

            $response = wp_remote_post('https://ogrodut.click/api/v1/payment/create', array(
                'timeout' => 20,
                'headers' => array(
                    'Accept' => 'application/json',
                    'X-Public-Key' => trim($this->public_key),
                    'X-Secret-Key' => trim($this->secret_key),
                ),
                'body' => $payload,
            ));

            if (is_wp_error($response)) {
                wc_add_notice('Payment gateway connection error.', 'error');
                return array('result' => 'fail');
            }

            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (!empty($data['payment_url'])) {
                return array('result' => 'success', 'redirect' => $data['payment_url']);
            }

            wc_add_notice($data['message'] ?? 'Unable to initiate payment.', 'error');
            return array('result' => 'fail');
        }

        public function handle_webhook() {
            $rawBody = file_get_contents('php://input');
            $signature = $_SERVER['HTTP_X_PAYAUTO_SIGNATURE'] ?? '';
            $expected = hash_hmac('sha256', $rawBody, trim($this->secret_key));
            $data = json_decode($rawBody, true);

            if (!is_array($data) || empty($data['merchant_order_id'])) {
                status_header(400);
                exit('Invalid Payload');
            }
            if (!empty($signature) && !hash_equals($expected, $signature)) {
                status_header(403);
                exit('Invalid Signature');
            }
            if (($data['status'] ?? '') === 'completed') {
                $order = wc_get_order($data['merchant_order_id']);
                if ($order && !$order->is_paid()) {
                    $trxId = sanitize_text_field($data['trx_id'] ?? 'VERIFIED');
                    $order->payment_complete($trxId);
                    $order->add_order_note("Verified via Ogrodut (TrxID: {$trxId})");
                }
            }
            status_header(200);
            exit('OK');
        }
    }

    add_filter('woocommerce_payment_gateways', function($methods) {
        $methods[] = 'WC_Gateway_PayAutoBD';
        return $methods;
    });
}