<?php
if (!defined('ABSPATH')) exit;

class Fusion_WooDoo_Webhooks {

    const WEBHOOK_PREFIX = 'fusion-woodoo-';

    public function __construct() {
        add_action('woocommerce_settings_saved', [$this, 'maybe_register']);
    }

    /**
     * Register all required WooCommerce webhooks pointing at the configured Odoo URL.
     */
    public function register_webhooks(): void {
        $odoo_url = rtrim(get_option('fusion_woodoo_odoo_url', ''), '/');
        if (empty($odoo_url)) {
            return;
        }

        $webhooks = [
            [
                'name'    => self::WEBHOOK_PREFIX . 'order-created',
                'topic'   => 'order.created',
                'api_url' => $odoo_url . '/woo/webhook/order',
            ],
            [
                'name'    => self::WEBHOOK_PREFIX . 'order-updated',
                'topic'   => 'order.updated',
                'api_url' => $odoo_url . '/woo/webhook/order',
            ],
            [
                'name'    => self::WEBHOOK_PREFIX . 'product-updated',
                'topic'   => 'product.updated',
                'api_url' => $odoo_url . '/woo/webhook/product',
            ],
            [
                'name'    => self::WEBHOOK_PREFIX . 'customer-created',
                'topic'   => 'customer.created',
                'api_url' => $odoo_url . '/woo/webhook/customer',
            ],
            [
                'name'    => self::WEBHOOK_PREFIX . 'customer-updated',
                'topic'   => 'customer.updated',
                'api_url' => $odoo_url . '/woo/webhook/customer',
            ],
        ];

        // Remove stale webhooks first to avoid duplicates
        self::unregister_all();

        foreach ($webhooks as $wh_data) {
            $webhook = new WC_Webhook();
            $webhook->set_name($wh_data['name']);
            $webhook->set_topic($wh_data['topic']);
            $webhook->set_delivery_url($wh_data['api_url']);
            $webhook->set_secret(get_option('fusion_woodoo_api_key', wp_generate_password(32)));
            $webhook->set_status('active');
            $webhook->save();
        }
    }

    /**
     * Delete all fusion-woodoo webhooks from WooCommerce.
     */
    public static function unregister_all(): void {
        $data_store = WC_Data_Store::load('webhook');
        $all_ids    = $data_store->get_webhooks_ids('active');

        foreach ($all_ids as $id) {
            $webhook = wc_get_webhook($id);
            if ($webhook && str_starts_with($webhook->get_name(), self::WEBHOOK_PREFIX)) {
                $webhook->delete(true);
            }
        }
    }

    /**
     * Ping the Odoo URL and return whether it is reachable.
     */
    public function check_stale(): bool {
        $odoo_url = get_option('fusion_woodoo_odoo_url', '');
        if (empty($odoo_url)) {
            return false;
        }

        $response = wp_remote_get(rtrim($odoo_url, '/') . '/web/health', [
            'timeout'   => 10,
            'sslverify' => apply_filters('fusion_woodoo_sslverify', true),
        ]);

        return !is_wp_error($response) && wp_remote_retrieve_response_code($response) < 500;
    }

    /**
     * Re-register webhooks when Odoo URL changes (triggered from settings).
     */
    public function maybe_register(): void {
        if (
            isset($_POST[Fusion_WooDoo_Admin_Settings::OPTION_ODOO_URL]) &&
            !empty($_POST[Fusion_WooDoo_Admin_Settings::OPTION_ODOO_URL])
        ) {
            $this->register_webhooks();
        }
    }
}
