<?php

namespace Phox\core\admin\panel\wdes_options\pages;

use Phox\core\admin\panel\wdes_options\pages\Abstract_Page;
use Phox\core\admin\panel\wdes_options\pages\elements\actions\Fetch_Whmcs_Data;
use Phox\core\admin\panel\wdes_options\pages\elements\actions\Remove_Whmcs_Data;
use Phox\core\admin\panel\wdes_options\pages\elements\Button;
use Phox\core\admin\panel\wdes_options\pages\elements\Text;
use Phox\core\admin\panel\wdes_options\pages\elements\URL;
use Phox\core\admin\panel\wdes_options\pages\elements\Select;
use Phox\core\admin\panel\wdes_options\pages\elements\Radio;
use Phox\core\admin\panel\wdes_options\Panel_Controller;

class Page_Integrations extends Abstract_Page
{

    private mixed $db_data = null;

    /**
     * @inheritDoc
     */
    public function build_pages(): void
    {
        $this->create_google_section();
        $this->create_ai_provider_selection_section();
        $this->create_openai_section();
        $this->create_gemini_section();
        $this->create_godaddy_section();
        $this->create_chat_tawk_section();
        $this->create_chat_intercom_section();
        $this->create_elementor_section();
    }

    private function create_google_section():void
    {
        $section_google = new Sections(
            section_name: esc_html__('Google Maps', 'phox'),
            description: '',
            doc_link: 'https://developers.google.com/maps/documentation/javascript/get-api-key'
        );
        $text_google = new Text(
            id:'google_maps_api_key',
            value: '',
            title: esc_html__('API Key','phox'),
            description: esc_html__('Put the Google Maps API key.', 'phox')
        );
        $this->add_section_collection($section_google, [
            $text_google
        ]);
    }

    private function create_ai_provider_selection_section():void
    {
        $section_ai_provider = new Sections(
            section_name: esc_html__('AI Provider Selection', 'phox'),
            description: '',
            doc_link: ''
        );

        $radio_ai_provider = new Radio(
            id: 'ai_provider',
            value: 'openai',
            title: esc_html__('Select AI Provider', 'phox'),
            description: esc_html__('Choose between OpenAI or Gemini as your AI provider.', 'phox')
        );

        $radio_ai_provider->set_option('OpenAI', 'openai', 'openai-logo');
        $radio_ai_provider->set_option('Gemini', 'gemini', 'gemini-logo');
        $radio_ai_provider->set_option('WHMCS', 'whmcs', 'whmcs-logo');

        $this->add_section_collection($section_ai_provider, [
            $radio_ai_provider
        ]);
    }

    private function create_openai_section():void
    {
        $section_openai = new Sections(
            section_name: esc_html__('OpenAI', 'phox'),
            description: '',
            doc_link: 'https://platform.openai.com/api-keys'
        );

        $text_openai = new Text(
            id:'openai_api_key',
            value: '',
            title: esc_html__('API Key','phox'),
            description: esc_html__('Put the OpenAI API key.', 'phox')
        );

        $select_openai_model = new Select(
            id: 'openai_model',
            value: 'gpt-5.2',
            title: esc_html__('OpenAI Model', 'phox'),
            description: esc_html__('Select the OpenAI model to use.', 'phox')
        );

        // Add OpenAI model options
        $select_openai_model->set_option('GPT-5.2', 'gpt-5.2');
        $select_openai_model->set_option('GPT-5.2 Pro', 'gpt-5.2-pro');
        $select_openai_model->set_option('GPT-5 Mini', 'gpt-5-mini');
        $select_openai_model->set_option('GPT-5 Nano', 'gpt-5-nano');

        $this->add_section_collection($section_openai, [
            $text_openai,
            $select_openai_model
        ]);
    }

    private function create_gemini_section():void
    {
        $section_gemini = new Sections(
            section_name: esc_html__('Gemini', 'phox'),
            description: '',
            doc_link: 'https://ai.google.dev/gemini-api/docs/api-key'
        );

        $text_gemini = new Text(
            id: 'gemini_api_key',
            value: '',
            title: esc_html__('API Key', 'phox'),
            description: esc_html__('Put the Gemini API key.', 'phox')
        );

        $select_gemini_model = new Select(
            id: 'gemini_model',
            value: 'gemini-3-flash-preview',
            title: esc_html__('Gemini Model', 'phox'),
            description: esc_html__('Select the Gemini model to use.', 'phox')
        );

        // Add Gemini model options
        $select_gemini_model->set_option('Gemini 3 Flash Preview', 'gemini-3-flash-preview');
        $select_gemini_model->set_option('Gemini 3 Pro Preview', 'gemini-3-pro-preview');
        $select_gemini_model->set_option('Gemini 2.5 Flash', 'gemini-2.5-flash');
        $select_gemini_model->set_option('Gemini 2.0 Flash Lite', 'gemini-2.0-flash-lite');


        $this->add_section_collection($section_gemini, [
            $text_gemini,
            $select_gemini_model
        ]);
    }

    private function create_godaddy_section():void
    {
        $section_godaddy = new Sections(
            section_name: esc_html__('GoDaddy', 'phox'),
            description: '',
            doc_link: 'elementor-widgets'
        );

        $text_godaddy_key = new Text(
            id:'godaddy_api_key',
            value: '',
            title: esc_html__('API Key','phox'),
            description: esc_html__('Put the GoDaddy API key.', 'phox')
        );

        $text_godaddy_secret = new Text(
            id:'godaddy_api_secret',
            value: '',
            title: esc_html__('API Secret','phox'),
            description: esc_html__('Put the GoDaddy API secret.', 'phox')
        );

        $this->add_section_collection($section_godaddy,[
            $text_godaddy_key,
            $text_godaddy_secret
        ]);
    }

    private function create_elementor_section():void
    {
        $section_elementor = new Sections(
          section_name: esc_html__('WHMCS', 'phox'),
          description: '',
          doc_link: 'how-to-create-api-credentials-in-whmcs'
        );

        $url_whmcs = new URL(
            id:'whmcs_url',
            value: '',
            title: esc_html__('URL','phox'),
            description: esc_html__('Put You WHMCS URL example: https://yourwhmcs.com', 'phox')
        );

        $text_whmcs_id = new Text(
            id:'whmcs_identifier',
            value: '',
            title: esc_html__('API ID','phox'),
            description: esc_html__('Put the API credential identifier.', 'phox')
        );

        $text_whmcs_secret = new Text(
            id:'whmcs_secret',
            value: '',
            title: esc_html__('API Secret','phox'),
            description: esc_html__('Put the API credential secret.', 'phox')
        );

        $button_whmcs_connect = new Button(
            id:'whmcs_connect',
            action: 'fetch_whmcs_data',
            action_class: new Fetch_Whmcs_Data,
            title: esc_html__('Import WHMCS Products.','phox'),
            description: esc_html__('This will import all the products from WHMCS to Elementor.', 'phox')
        );

        $button_whmcs_connect->set_status($this->check_whmcs_connectivity_status());

        $button_whmcs_disconnect = new Button(
            id:'whmcs_disconnect',
            action: 'remove_whmcs_data',
            action_class: new Remove_Whmcs_Data,
            title: esc_html__('Disconnect WHMCS Products.','phox'),
            description: esc_html__('This will remove all the products from Elementor.', 'phox')
        );

        $button_whmcs_disconnect->set_status( ! $this->check_whmcs_connectivity_status());

        $this->add_section_collection($section_elementor, [
            $url_whmcs,
            $text_whmcs_id,
            $text_whmcs_secret,
            $button_whmcs_connect,
            $button_whmcs_disconnect
        ]);
    }

    /**
     * Check if data is fetched it will return true
     *
     * @since 2.3.6
     * @return bool
     */
    private function check_whmcs_connectivity_status():bool
    {
        if (is_null($this->db_data)){
            $this->db_data = Panel_Controller::getInstance()->get_db_source()->get_whmcs_fetched_data();
        }

        return empty($this->db_data);
    }

    private function create_chat_tawk_section():void
    {
        $section_chat = new Sections(
            section_name: esc_html__('tawk.to', 'phox'),
            description: '',
            doc_link: 'chat-platforms-options/#get-tawk-api'
        );

        $section_tawk = new Text(
            id:'platform-api-tawk',
            value: '',
            title: esc_html__('Chat Link','phox'),
            description: esc_html__('Put the chat link example https://tawk.to/chat/apikey/default', 'phox')
        );

        $this->add_section_collection($section_chat, [
            $section_tawk
        ]);
    }

    private function create_chat_intercom_section():void
    {
        $section_chat = new Sections(
            section_name: esc_html__('Intercom', 'phox'),
            description: '',
            doc_link: 'https://developers.intercom.com/building-apps/docs/authentication-types#section-authentication-types'
        );

        $section_intercom = new Text(
            id:'platform-api-intercom',
            value: '',
            title: esc_html__('API Key','phox'),
            description: esc_html__('Put the Intercom API key.', 'phox')
        );


        $this->add_section_collection($section_chat, [

            $section_intercom
        ]);
    }

    public function before_saving(): array
    {
        $credentials = $this->getWhmcsCredentials();
        if (!$this->areCredentialsValid($credentials)) {
            return ['result' => true, 'error' => []];
        }

        // Test GetProducts API endpoint
        $productsResult = $this->makeWhmcsApiCall(
            $credentials,
            'GetProducts'
        );
        if (!$productsResult['success']) {
            return $productsResult['response'];
        }

        // Test DomainWhois API endpoint
        $whoisResult = $this->makeWhmcsApiCall(
            $credentials,
            'DomainWhois',
            [
                'domain' => 'example.com'
            ]
        );
        if (!$whoisResult['success']) {
            return $whoisResult['response'];
        }

        // remove the waring message
        delete_transient('phox_whmcs_api_connected');

        return ['result' => true, 'error' => []];
    }

    private function getWhmcsCredentials(): array
    {
        $credentials = [
            'whmcs_url' => '',
            'whmcs_identifier' => '',
            'whmcs_secret' => ''
        ];

        foreach ($this->elements_registration_list as $element) {
            $id = $element->get_id();
            if (array_key_exists($id, $credentials)) {
                $credentials[$id] = $element->get_prepared_save_values();
            }
        }

        return $credentials;
    }

    private function areCredentialsValid(array $credentials): bool
    {
        return !empty($credentials['whmcs_url'])
            && !empty($credentials['whmcs_identifier'])
            && !empty($credentials['whmcs_secret']);
    }

    private function makeWhmcsApiCall(array $credentials, string $action, array $additionalParams = []): array
    {
        $api_url = esc_url($credentials['whmcs_url'] . '/includes/api.php');
        $baseParams = [
            'action' => $action,
            'identifier' => $credentials['whmcs_identifier'],
            'secret' => $credentials['whmcs_secret'],
            'responsetype' => 'json',
        ];

        // Merge base parameters with additional parameters
        $data = http_build_query(array_merge($baseParams, $additionalParams));


        $request = wp_remote_post($api_url, [
            'timeout' => 30,
            'body' => $data,
        ]);

        if (is_wp_error($request)) {
            return [
                'success' => false,
                'response' => [
                    'result' => false,
                    'error' => ['whmcs_url' => $request->get_error_message()]
                ]
            ];
        }

        $response_code = wp_remote_retrieve_response_code($request);
        $response_body = json_decode(wp_remote_retrieve_body($request), true);

        if (isset($response_body['result']) && $response_body['result'] === 'error') {
            return [
                'success' => false,
                'response' => [
                    'result' => false,
                    'error' => ['whmcs_identifier' => $response_body['message']]
                ]
            ];
        }

        if ($response_code !== 200) {
            return [
                'success' => false,
                'response' => [
                    'result' => false,
                    'error' => ['whmcs_url' => 'Check your url and try again.']
                ]
            ];
        }

        return ['success' => true];
    }


}