<?php
namespace orderflow\Courier;

use orderflow\Core\Base;

class Steadfast_Api extends Base {
    // API endpoint - Updated to match working implementation
    private const API_URL = 'https://portal.packzy.com/api/v1/fraud_check/';
    // Request timeout in seconds - Increased to match working implementation
    private const REQUEST_TIMEOUT = 25;

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

        // Clean phone number by removing non-numeric characters
        $clean_phone = preg_replace('/[^0-9]/', '', $phone_number);

        // Validate phone number after cleaning
        if (empty($clean_phone)) {
            $response['error'] = true;
            $response['error_message'] = 'Invalid phone number';
            $response['error_type'] = 'validation';
            return $response;
        }

        // Make API request
        $url = self::API_URL . $clean_phone;
        $api_response = self::make_api_request($url);

        // Handle response errors
        if (isset($api_response['error'])) {
            $response['error'] = true;
            $response['error_message'] = $api_response['error'];
            $response['error_type'] = 'api_request';
            return $response;
        }

        // Process and return customer data
        return self::process_customer_data($api_response, $response);
    }

    /**
     * Make API request to Steadfast
     *
     * @param string $url Full API URL with phone number
     * @return array Response data or error array
     */
    private static function make_api_request($url) {
        // Get API credentials from WordPress options
        $api_key = get_option('ads_steadfast_api_key', '');
        $secret_key = get_option('ads_steadfast_secret_key', '');

        // Validate API credentials
        if (empty($api_key) || empty($secret_key)) {
            return ['error' => 'API credentials not configured. Please set API Key and Secret Key in settings.'];
        }

        // Make GET request with API authentication headers
        $response = wp_remote_get($url, [
            'timeout' => self::REQUEST_TIMEOUT,
            'headers' => [
                'content-type' => 'application/json',
                'api-key' => $api_key,
                'secret-key' => $secret_key,
            ],
        ]);

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

        // Check HTTP response code
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $body = wp_remote_retrieve_body($response);
            return ['error' => 'API request failed with status code: ' . $response_code];
        }

        // Retrieve and decode response body
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        // Validate response structure
        if (!is_array($data) || !isset($data['total_parcels'])) {
            return ['error' => 'Invalid response or missing data'];
        }

        return $data;
    }

    /**
     * Process customer data from API response
     *
     * @param array $response_data API response data
     * @param array $response Base response structure
     * @return array Formatted customer delivery data
     */
    private static function process_customer_data($response_data, $response) {
        // Extract values with fallback to 0 (matches working implementation)
        $delivered = (int)($response_data['total_delivered'] ?? 0);
        $cancelled = (int)($response_data['total_cancelled'] ?? 0);
        $total = (int)($response_data['total_parcels'] ?? 0);

        // Return formatted data (matches working implementation)
        $response['success'] = $delivered;
        $response['cancel'] = $cancelled;
        $response['total'] = $total;

        return $response;
    }

    /**
     * Calculate success rate percentage
     *
     * @param int $total Total parcels
     * @param int $delivered Total delivered parcels
     * @return string Success rate percentage formatted to 2 decimal places
     */
    public static function calculate_success_rate($total, $delivered) {
        // Calculate percentage with division by zero protection
        return ($total > 0)
            ? round(($delivered / max(1, $total)) * 100, 2) . '%'
            : '00.0%';
    }
}