<?php

namespace DynamicContentForElementor\AdminPages;

use DynamicContentForElementor\Helper;
class Api
{
    /**
     * @var array<string,mixed>
     */
    private $fields = [];
    /**
     * @var array<string,string>
     */
    private $section_descriptions = [];
    /**
     * @var string
     */
    private $prefix;
    /**
     * @param string $prefix
     */
    public function __construct(string $prefix)
    {
        if (empty($prefix)) {
            throw new \Exception('The prefix cannot be empty');
        }
        $this->prefix = $prefix;
        add_action('admin_init', [$this, 'register_settings']);
    }
    /**
     * @return void
     */
    public function register_settings()
    {
        $this->fields = [
            // Google Maps
            $this->prefix . 'google_maps_api' => ['label' => __('Google Maps JavaScript API Key', 'dynamic-content-for-elementor'), 'type' => 'text', 'section' => $this->prefix . 'section_google_maps'],
            // PayPal
            $this->prefix . 'paypal_api_mode' => ['label' => __('PayPal Mode', 'dynamic-content-for-elementor'), 'type' => 'select', 'options' => ['sandbox' => 'Sandbox', 'live' => 'Live'], 'section' => $this->prefix . 'section_paypal'],
            $this->prefix . 'paypal_api_currency' => ['label' => __('PayPal Currency Code', 'dynamic-content-for-elementor'), 'type' => 'text', 'section' => $this->prefix . 'section_paypal'],
            $this->prefix . 'paypal_sandbox_group' => ['type' => 'group', 'section' => $this->prefix . 'section_paypal', 'label' => __('PayPal Sandbox Credentials', 'dynamic-content-for-elementor'), 'fields' => [$this->prefix . 'paypal_api_client_id_sandbox' => ['label' => __('Sandbox Client ID', 'dynamic-content-for-elementor'), 'type' => 'text'], $this->prefix . 'paypal_api_client_secret_sandbox' => ['label' => __('Sandbox Client Secret', 'dynamic-content-for-elementor'), 'type' => 'password']]],
            $this->prefix . 'paypal_live_group' => ['type' => 'group', 'section' => $this->prefix . 'section_paypal', 'label' => __('PayPal Live Credentials', 'dynamic-content-for-elementor'), 'fields' => [$this->prefix . 'paypal_api_client_id_live' => ['label' => __('Live Client ID', 'dynamic-content-for-elementor'), 'type' => 'text'], $this->prefix . 'paypal_api_client_secret_live' => ['label' => __('Live Client Secret', 'dynamic-content-for-elementor'), 'type' => 'password']]],
            // Stripe
            $this->prefix . 'stripe_api_mode' => ['label' => __('Stripe Mode', 'dynamic-content-for-elementor'), 'type' => 'select', 'options' => ['test' => 'Test', 'live' => 'Live'], 'section' => $this->prefix . 'section_stripe'],
            $this->prefix . 'stripe_test_group' => ['type' => 'group', 'section' => $this->prefix . 'section_stripe', 'label' => __('Stripe Test Keys', 'dynamic-content-for-elementor'), 'fields' => [$this->prefix . 'stripe_api_publishable_key_test' => ['label' => __('Test Publishable Key', 'dynamic-content-for-elementor'), 'type' => 'text'], $this->prefix . 'stripe_api_secret_key_test' => ['label' => __('Test Secret Key', 'dynamic-content-for-elementor'), 'type' => 'password']]],
            $this->prefix . 'stripe_live_group' => ['type' => 'group', 'section' => $this->prefix . 'section_stripe', 'label' => __('Stripe Live Keys', 'dynamic-content-for-elementor'), 'fields' => [$this->prefix . 'stripe_api_publishable_key_live' => ['label' => __('Live Publishable Key', 'dynamic-content-for-elementor'), 'type' => 'text'], $this->prefix . 'stripe_api_secret_key_live' => ['label' => __('Live Secret Key', 'dynamic-content-for-elementor'), 'type' => 'password']]],
            // Coinmarketcap
            $this->prefix . 'coinmarketcap_key' => ['label' => __('Coinmarketcap API Key', 'dynamic-content-for-elementor'), 'type' => 'text', 'section' => $this->prefix . 'section_coinmarketcap'],
        ];
        if (Helper::is_acf_active() || Helper::is_acfpro_active()) {
            $this->fields[$this->prefix . 'google_maps_api_acf'] = ['label' => __('Set this API also in ACF Configuration', 'dynamic-content-for-elementor'), 'type' => 'checkbox', 'section' => $this->prefix . 'section_google_maps'];
        }
        $this->section_descriptions = [$this->prefix . 'section_google_maps' => __('Enter your Google Maps API key to enable map features.', 'dynamic-content-for-elementor'), $this->prefix . 'section_paypal' => __('Configure your PayPal credentials for handling payments.', 'dynamic-content-for-elementor'), $this->prefix . 'section_stripe' => __('Set your Stripe keys for secure online payments.', 'dynamic-content-for-elementor'), $this->prefix . 'section_coinmarketcap' => __('Provide your Coinmarketcap API key to fetch cryptocurrency data.', 'dynamic-content-for-elementor')];
        // Register settings
        foreach ($this->fields as $option_name => $field_args) {
            if (isset($field_args['type']) && $field_args['type'] === 'group') {
                foreach ($field_args['fields'] as $sub_option_name => $sub_field_args) {
                    register_setting($this->prefix . 'apis', $sub_option_name, [$this, 'sanitize_field']);
                }
            } else {
                register_setting($this->prefix . 'apis', $option_name, [$this, 'sanitize_field']);
            }
        }
        // Sections
        add_settings_section($this->prefix . 'section_google_maps', 'Google Maps', [$this, 'section_callback'], $this->prefix . 'apis');
        add_settings_section($this->prefix . 'section_paypal', 'PayPal', [$this, 'section_callback'], $this->prefix . 'apis');
        add_settings_section($this->prefix . 'section_stripe', 'Stripe', [$this, 'section_callback'], $this->prefix . 'apis');
        add_settings_section($this->prefix . 'section_coinmarketcap', 'Coinmarketcap', [$this, 'section_callback'], $this->prefix . 'apis');
        // Fields
        foreach ($this->fields as $option_name => $field_args) {
            add_settings_field($option_name, isset($field_args['label']) ? $field_args['label'] : '', [$this, 'field_callback'], $this->prefix . 'apis', $field_args['section'], ['option_name' => $option_name, 'type' => isset($field_args['type']) ? $field_args['type'] : 'text', 'options' => isset($field_args['options']) ? $field_args['options'] : [], 'fields' => isset($field_args['fields']) ? $field_args['fields'] : []]);
        }
    }
    /**
     * @param array<string,mixed> $args
     * @return void
     */
    public function section_callback($args)
    {
        echo '<hr>';
        if (isset($this->section_descriptions[$args['id']])) {
            echo '<p class="description">' . esc_html($this->section_descriptions[$args['id']]) . '</p>';
        }
    }
    /**
     * @param string|bool $input
     * @return string|bool
     */
    public function sanitize_field($input)
    {
        return \is_string($input) ? sanitize_text_field($input) : $input;
    }
    /**
     * @param array<string,mixed> $args
     * @return void
     */
    public function field_callback($args)
    {
        $option_name = $args['option_name'];
        $type = $args['type'];
        $options = $args['options'];
        $fields = $args['fields'];
        if ($type === 'group') {
            echo '<div style="display:flex; gap:20px; align-items:center;">';
            foreach ($fields as $sub_option_name => $sub_field_args) {
                $sub_type = $sub_field_args['type'];
                $sub_value = get_option($sub_option_name, '');
                echo '<div>';
                if (isset($sub_field_args['label']) && $sub_field_args['label']) {
                    echo '<label style="display:block;" for="' . esc_attr($sub_option_name) . '">' . esc_html($sub_field_args['label']) . '</label>';
                }
                $this->print_input_field($sub_option_name, $sub_type, $sub_value);
                echo '</div>';
            }
            echo '</div>';
        } else {
            $value = get_option($option_name, '');
            $this->print_input_field($option_name, $type, $value, $options);
        }
    }
    /**
     * @param string $name
     * @param string $type
     * @param string $value
     * @param array<string,mixed> $options
     * @return void
     */
    private function print_input_field($name, $type, $value, $options = [])
    {
        $style = 'style="max-width:400px;width:100%;"';
        switch ($type) {
            case 'text':
                echo '<input class="' . $this->prefix . 'apis" type="text" name="' . esc_attr($name) . '" value="' . esc_attr($value) . '" autocomplete="off" ' . $style . '>';
                break;
            case 'password':
                echo '<input class="' . $this->prefix . 'apis" type="password" name="' . esc_attr($name) . '" value="' . esc_attr($value) . '" autocomplete="off" ' . $style . '>';
                break;
            case 'checkbox':
                echo '<input class="' . $this->prefix . 'apis" type="checkbox" name="' . esc_attr($name) . '" ' . checked($value, 'on', \false) . '>';
                break;
            case 'select':
                echo '<select class="' . $this->prefix . 'apis" name="' . esc_attr($name) . '" ' . $style . '>';
                foreach ($options as $option_key => $label) {
                    echo '<option value="' . esc_attr($option_key) . '" ' . selected($value, $option_key, \false) . '>' . esc_html($label) . '</option>';
                }
                echo '</select>';
                break;
        }
    }
    /**
     * @return void
     */
    public function display_form()
    {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        ?>
		<div class="wrap">
			<h1><?php 
        echo esc_html(get_admin_page_title());
        ?></h1>
			<form action="options.php" method="post" autocomplete="off">
				<?php 
        settings_fields($this->prefix . 'apis');
        do_settings_sections($this->prefix . 'apis');
        submit_button(__('Save Integrations', 'dynamic-content-for-elementor'));
        ?>
			</form>
		</div>
		<?php 
    }
}
