<?php

class GrayquestUtils
{
    /**
     * Fetch EMI amount for a specific tenure from Grayquest API
     *
     * @param float $amount The total payment amount (loan amount)
     * @param string $clientId Grayquest client ID
     * @param string $clientSecret Grayquest client secret
     * @param string $apiKey Grayquest API key (GQ-API-Key)
     * @param string $environment Grayquest environment ('staging' or 'production')
     * @param int $tenure EMI tenure in months (default: 3)
     * @return float|null The EMI amount per month for the specified tenure, or null if the request fails or tenure is not found
     */
    public static function fetchGrayquestEMIAmount($amount, $clientId, $clientSecret, $apiKey, $environment, $tenure = 3)
    {
        $emiPlans = self::fetchGrayquestEMIPlans($amount, $clientId, $clientSecret, $apiKey, $environment);
        if ($emiPlans) {
            foreach ($emiPlans as $plan) {
                if (isset($plan['emi_count']) && $plan['emi_count'] == $tenure && isset($plan['plan_emi_amount'])) {
                    return (float) $plan['plan_emi_amount'];
                }
            }
            // Log if tenure not found
            if (class_exists('Logger')) {
                Logger::error("Grayquest EMI API: Tenure $tenure not found for amount $amount");
            }
        }
        return null;
    }

    /**
     * Fetch all EMI plans from Grayquest API
     *
     * @param float $amount The total payment amount (loan amount)
     * @param string $clientId Grayquest client ID
     * @param string $clientSecret Grayquest client secret
     * @param string $apiKey Grayquest API key (GQ-API-Key)
     * @param string $environment Grayquest environment ('staging' or 'production')
     * @return array|null Array of EMI plans (e.g., [{emi_count: 6, plan_emi_amount: 85834}, ...]), or null if the request fails
     */
    public static function fetchGrayquestEMIPlans($amount, $clientId, $clientSecret, $apiKey, $apiUrl)
    {        
        $url = $apiUrl . '/v1/product/emi-plans?loan_amount=' . urlencode($amount);        
        // Construct Basic Authentication header
        $authString = $clientId . ':' . $clientSecret;
        $authHeader = 'Basic ' . base64_encode($authString);        
        $headers = [
            'Content-Type: application/json',
            'GQ-API-Key: ' . $apiKey,
            'Authorization: ' . $authHeader
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($httpCode === 200 && $response && !$error) {
            $responseData = json_decode($response, true);
            if (json_last_error() === JSON_ERROR_NONE && isset($responseData['success']) && $responseData['success'] && isset($responseData['data']) && is_array($responseData['data'])) {
                return $responseData['data']??'NoData';
            }
        }

        // Log error for debugging
        if (class_exists('Logger')) {
            Logger::error("Grayquest EMI API failed: HTTP $httpCode, Error: $error, Response: " . ($response ?: 'No response'));
        }

        return null;
    }
}

?>