<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit; // Prevent direct access to the file.
}

// Check if the class already exists to avoid redeclaration.
if (!class_exists('IAFWZCAI_PRODUCT')) {
    class IAFWZCAI_PRODUCT
    {
        private $refresh_token;
        private $access_token;
        private $data_center;
        private $account_id;
        public function __construct($account_details = [], $access_token = null)
        {
            $this->refresh_token = $account_details['refresh_token'] ?? null;
            $this->data_center = $account_details['data_center'] ?? null;
            $this->account_id = $account_details['account_id'] ?? null;
            $this->access_token = $access_token;
        }
        // Function to get access token using refresh token
        private function get_access_token()
        {
            $url = "https://accounts.zoho." . $this->data_center . "/oauth/v2/token";
            $body = [
                'refresh_token' => $this->refresh_token,
                'client_id' => "1000.R6NADONBVTIS0VZSZ0DE5MNO3DEV7T",
                'client_secret' => "52f6c37069fd0db03ed6025766e968214d35bffbe5",
                'grant_type' => 'refresh_token'
            ];

            $response = wp_remote_post($url, [
                'body' => $body,
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'timeout' => 60
            ]);

            if (is_wp_error($response)) {
                return false;
            }

            $response_body = wp_remote_retrieve_body($response);
            $data = json_decode($response_body, true);

            if (isset($data['access_token'])) {
                // Corrected account_id reference and updating the access token
                IAFWZCAI_Util::updateAccessToken($this->account_id, $data['access_token']);
                $this->access_token = $data['access_token']; // Update the current access token
                return true;
            }

            return false;
        }
        // Function to get all mailing lists
        public function get_campaign_lists($retry = true)
        {
            // Construct API URL properly
            $url = add_query_arg([
                'resfmt' => 'JSON' // Ensure JSON response format
            ], "https://campaigns.zoho." . esc_attr($this->data_center) . "/api/v1.1/getmailinglists");

            // Send API request
            $response = wp_remote_get($url, [
                'headers' => [
                    'Authorization' => 'Zoho-oauthtoken ' . esc_attr($this->access_token),
                    'Content-Type'  => 'application/json'
                ],
                'timeout' => 60
            ]);

            // Check for network-related errors
            if (is_wp_error($response)) {
                return ['error' => "Connection failed: Please verify your internet connection, or the Zoho server may not be responding right now. Try again, and if the issue continues, contact support"];
            }

            // Retrieve response status and body
            $status_code = wp_remote_retrieve_response_code($response);
            $body = json_decode(wp_remote_retrieve_body($response), true);
            // Handle authentication failure (401 Unauthorized)
            if (isset($body['Code']) && $body['Code'] == 1007) {
                if ($retry && $this->get_access_token()) {
                    return $this->get_campaign_lists(false);
                }
                return ['error' => 'Authentication failed. Your session may have expired or your token may be invalid. Please reauthenticate and try again.'];
            }

            // Return the mailing lists
            return $body["list_of_details"];
        }

        // Function to get all mailing lists
        public function get_all_fields($retry = true)
        {
            //https://campaigns.zoho.in/api/v1.1/contact/allfields?type=json
            // Construct API URL properly
            $url = add_query_arg([
                'type' => 'JSON' // Ensure JSON response format
            ], "https://campaigns.zoho." . esc_attr($this->data_center) . "/api/v1.1/contact/allfields");

            // Send API request
            $response = wp_remote_get($url, [
                'headers' => [
                    'Authorization' => 'Zoho-oauthtoken ' . esc_attr($this->access_token),
                    'Content-Type'  => 'application/json'
                ],
                'timeout' => 60
            ]);

            // Check for network-related errors
            if (is_wp_error($response)) {
                return ['error' => "Connection failed: Please verify your internet connection, or the Zoho server may not be responding right now. Try again, and if the issue continues, contact support"];
            }

            // Retrieve response status and body
            $status_code = wp_remote_retrieve_response_code($response);
            $body = json_decode(wp_remote_retrieve_body($response), true);

            // Handle authentication failure (401 Unauthorized)
            if (isset($body['Code']) && $body['Code'] == 1007) {
                if ($retry && $this->get_access_token()) {
                    return $this->get_campaign_lists(false);
                }
                return ['error' => 'Authentication failed. Your session may have expired or your token may be invalid. Please reauthenticate and try again.'];
            }

            // Return the mailing lists
            return $body["response"]["fieldnames"]["fieldname"];
        }

        public function add_contact($record_data, $list_key, $retry = true)
        {
            try {
                // Prepare request URL with query parameters
                $url = add_query_arg([
                    'resfmt'      => 'JSON', // Ensure JSON response format
                    'listkey'     => esc_attr($list_key), // Use dynamic list key
                    'contactinfo' => wp_json_encode($record_data) // Properly encode contact info
                ], "https://campaigns.zoho." . esc_attr($this->data_center) . "/api/v1.1/json/listsubscribe");
                // API Request
                $response = wp_remote_get($url, [
                    'headers' => [
                        'Authorization' => 'Zoho-oauthtoken ' . esc_attr($this->access_token),
                        'Content-Type'  => 'application/json'
                    ],
                    'timeout' => 60
                ]);

                // Check for HTTP response errors
                if (is_wp_error($response)) {
                    return $this->create_error_response('NETWORK_ISSUE');
                }

                // Retrieve response data
                $status_code = wp_remote_retrieve_response_code($response);
                $body = json_decode(wp_remote_retrieve_body($response), true);
                // Ensure the body is valid and has required keys
                if (!is_array($body)) {
                    return $this->create_error_response('INVALID_RESPONSE');
                }
                // Handle authentication failure (401 Unauthorized)
                if (isset($body['Code']) && $body['Code'] == 1007) {
                    if ($retry && $this->get_access_token()) {
                        return $this->add_contact($record_data, false);
                    }
                    return $this->create_error_response('AUTHENTICATION_FAILURE', $body);
                }
                if (isset($body['status']) && $body['status'] !== 'success') {
                    return $this->create_error_response('RECORD_FAILED', $body);
                }
                // Return API response
                return $body;
            } catch (Throwable $e) {
                return $this->create_error_response('UNEXPECTED_ERROR');
            }
        }

        /**
         * Helper function to create a standardized error response.
         */
        private function create_error_response($error_code, $body)
        {
            return [
                'status' => 'error',
                'category' => $error_code,
                'body' => $body
            ];
        }
    }
}
