<?php
namespace orderflow\Courier;

use orderflow\Core\Base;

class Redx_Api extends Base {
    // API endpoint configuration
    private const API_ENDPOINT = 'https://redx.com.bd/api/redx_se/admin/parcel/customer-success-return-rate';
    private const REQUEST_TIMEOUT = 15;

    /**
     * Get customer delivery history from REDX
     *
     * @param string $phone_number Customer phone number
     * @return array Customer delivery data with success, cancel and total counts or error
     */
    public static function redx_get_customer_history($phone_number) {
        // Initialize default response structure
        $response = [
            'success' => 0,
            'cancel' => 0,
            'total' => 0,
            'error' => false,
            'error_message' => '',
            'error_type' => ''
        ];

        // Normalize and validate phone number
        $phone_number = self::normalize_phone_number($phone_number);
        if (!$phone_number || strlen($phone_number) != 11) {
            $response['error'] = true;
            $response['error_message'] = 'Invalid phone number';
            $response['error_type'] = 'validation';
            return $response;
        }

        // Get access token
        $access_token = get_option('ads_redx_access_token');
        if (!$access_token) {
            $response['error'] = true;
            $response['error_message'] = 'REDX access token not found in options';
            $response['error_type'] = 'authentication';
            return $response;
        }

        // Prepare API request
        $url = self::build_api_url($phone_number);
        $headers = self::get_request_headers($access_token);

        // Execute API request
        $api_response = self::execute_api_request($url, $headers);
        if (isset($api_response['error'])) {
            $response['error'] = true;
            $response['error_message'] = $api_response['error'];

            // Set error type based on status code or error message
            if (isset($api_response['status']) && $api_response['status'] === 401) {
                $response['error_type'] = 'authentication';
            } else {
                $response['error_type'] = 'api_request';
            }
            return $response;
        }

        // Process response data
        return self::process_response_data($api_response, $response);
    }

    /**
     * Build the API URL with phone number parameter
     *
     * @param string $phone_number Normalized phone number
     * @return string Complete API URL
     */
    private static function build_api_url($phone_number) {
        return self::API_ENDPOINT . '?phoneNumber=88' . urlencode($phone_number);
    }

    /**
     * Get request headers for API call
     *
     * @param string $access_token REDX access token
     * @return array Request headers
     */
    private static function get_request_headers($access_token) {
        return [
            'Authorization' => 'Bearer ' . $access_token,
            'User-Agent'    => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
            'Accept'        => 'application/json, text/plain, */*',
            'Content-Type'  => 'application/json',
        ];
    }

    /**
     * Execute the API request and handle response
     *
     * @param string $url API URL
     * @param array $headers Request headers
     * @return array Response data or error
     */
    private static function execute_api_request($url, $headers) {
        $response = wp_remote_get($url, [
            'headers' => $headers,
            'timeout' => self::REQUEST_TIMEOUT,
        ]);

        if (is_wp_error($response)) {
            return ['error' => 'Request failed: ' . $response->get_error_message()];
        }

        $status = wp_remote_retrieve_response_code($response);
        if ($status === 401) {
            return ['error' => 'Access token expired or invalid', 'status' => 401];
        }

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

        if (!$data || !isset($data['data']) || !isset($data['data']['deliveredParcels']) || !isset($data['data']['totalParcels'])) {
            return ['error' => 'Invalid or unexpected response format'];
        }

        return $data;
    }

    /**
     * Process the response data and return formatted result
     *
     * @param array $response_data API response data
     * @param array $response Base response structure
     * @return array Formatted customer delivery data
     */
    private static function process_response_data($response_data, $response) {
        $delivered = (int)($response_data['data']['deliveredParcels'] ?? 0);
        $total     = (int)($response_data['data']['totalParcels'] ?? 0);
        $cancel    = $total - $delivered;

        $response['success'] = $delivered;
        $response['cancel']  = $cancel;
        $response['total']   = $total;

        return $response;
    }
}