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

class Fusion_WooDoo_Admin_Settings {

    const OPTION_ODOO_URL       = 'fusion_woodoo_odoo_url';
    const OPTION_API_KEY        = 'fusion_woodoo_api_key';
    const OPTION_SHOW_ORDERS    = 'fusion_woodoo_show_orders';
    const OPTION_SHOW_INVOICES  = 'fusion_woodoo_show_invoices';
    const OPTION_SHOW_DELIVERIES = 'fusion_woodoo_show_deliveries';
    const OPTION_SHOW_RETURNS   = 'fusion_woodoo_show_returns';

    public function __construct() {
        add_action('admin_menu', [$this, 'add_settings_page']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_post_fusion_woodoo_save', [$this, 'handle_save']);
        add_action('wp_ajax_fusion_woodoo_test_connection', [$this, 'ajax_test_connection']);
        add_action('update_option_' . self::OPTION_ODOO_URL, [$this, 'on_url_changed'], 10, 0);
    }

    public function add_settings_page(): void {
        add_submenu_page(
            'woocommerce',
            __('Fusion WooDoo', 'fusion-woodoo'),
            __('Fusion WooDoo', 'fusion-woodoo'),
            'manage_woocommerce',
            'fusion-woodoo-settings',
            [$this, 'render_settings_page']
        );
    }

    public function register_settings(): void {
        $options = [
            self::OPTION_ODOO_URL,
            self::OPTION_API_KEY,
            self::OPTION_SHOW_ORDERS,
            self::OPTION_SHOW_INVOICES,
            self::OPTION_SHOW_DELIVERIES,
            self::OPTION_SHOW_RETURNS,
        ];
        foreach ($options as $option) {
            register_setting('fusion_woodoo_settings', $option, ['sanitize_callback' => 'sanitize_text_field']);
        }

        add_settings_section(
            'fusion_woodoo_connection',
            __('Odoo Connection', 'fusion-woodoo'),
            null,
            'fusion-woodoo-settings'
        );

        add_settings_field(
            self::OPTION_ODOO_URL,
            __('Odoo URL', 'fusion-woodoo'),
            [$this, 'field_odoo_url'],
            'fusion-woodoo-settings',
            'fusion_woodoo_connection'
        );

        add_settings_field(
            self::OPTION_API_KEY,
            __('API Key', 'fusion-woodoo'),
            [$this, 'field_api_key'],
            'fusion-woodoo-settings',
            'fusion_woodoo_connection'
        );

        add_settings_section(
            'fusion_woodoo_portal',
            __('Customer Portal Tabs', 'fusion-woodoo'),
            null,
            'fusion-woodoo-settings'
        );

        $toggles = [
            self::OPTION_SHOW_ORDERS    => __('Show Sales Orders tab', 'fusion-woodoo'),
            self::OPTION_SHOW_INVOICES  => __('Show Invoices tab', 'fusion-woodoo'),
            self::OPTION_SHOW_DELIVERIES => __('Show Deliveries tab', 'fusion-woodoo'),
            self::OPTION_SHOW_RETURNS   => __('Show Returns tab', 'fusion-woodoo'),
        ];
        foreach ($toggles as $option => $label) {
            add_settings_field(
                $option,
                $label,
                [$this, 'field_checkbox'],
                'fusion-woodoo-settings',
                'fusion_woodoo_portal',
                ['option' => $option]
            );
        }
    }

    public function field_odoo_url(): void {
        $value = esc_attr(get_option(self::OPTION_ODOO_URL, ''));
        echo '<input type="url" name="' . self::OPTION_ODOO_URL . '" value="' . $value . '" class="regular-text" placeholder="https://erp.example.com" />';
        echo '<p class="description">' . __('Base URL of your Odoo instance — no trailing slash.', 'fusion-woodoo') . '</p>';
    }

    public function field_api_key(): void {
        $value = esc_attr(get_option(self::OPTION_API_KEY, ''));
        echo '<input type="password" name="' . self::OPTION_API_KEY . '" value="' . $value . '" class="regular-text" autocomplete="new-password" />';
        echo '<p class="description">' . __('API key from the Fusion WooCommerce Odoo module.', 'fusion-woodoo') . '</p>';
    }

    public function field_checkbox(array $args): void {
        $option  = $args['option'];
        $checked = checked(1, get_option($option, 1), false);
        echo '<label><input type="checkbox" name="' . esc_attr($option) . '" value="1" ' . $checked . ' /> ' . __('Enabled', 'fusion-woodoo') . '</label>';
    }

    public function render_settings_page(): void {
        $template = FUSION_WOODOO_PLUGIN_DIR . 'templates/admin/settings.php';
        if (file_exists($template)) {
            include $template;
        }
    }

    public function on_url_changed(): void {
        if (class_exists('Fusion_WooDoo_Webhooks')) {
            Fusion_WooDoo_Webhooks::unregister_all();
            (new Fusion_WooDoo_Webhooks())->register_webhooks();
        }
    }

    public function ajax_test_connection(): void {
        check_ajax_referer('fusion_woodoo_admin_nonce', 'nonce');
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(['message' => __('Permission denied.', 'fusion-woodoo')]);
        }
        $client = new Fusion_WooDoo_API_Client();
        $result = $client->test_connection();
        if ($result['success']) {
            wp_send_json_success(['message' => __('Connection successful! Odoo is reachable.', 'fusion-woodoo')]);
        } else {
            wp_send_json_error(['message' => $result['error'] ?: __('Connection failed.', 'fusion-woodoo')]);
        }
    }
}
