<?php
/**
 * PhonePe Authentication Service
 * Handles token generation and validation
 */

require_once 'phonepe_config.php';

class PhonePeAuth {
    private $config;
    
    public function __construct() {
        $this->config = new PhonePeConfig();
    }
    
    /**
     * Get authentication token from PhonePe
     */
    public function getAuthToken() {
        try {
            $credentials = PhonePeConfig::getClientCredentials();
            
            $postData = [
                'client_id' => $credentials['client_id'],
                'client_secret' => $credentials['client_secret'],
                'client_version' => $credentials['client_version']
            ];
            
            $url = PhonePeConfig::getBaseUrl() . '/auth/token';
            
            $response = $this->makeHttpRequest($url, 'POST', $postData);
            
            if ($response && isset($response['token'])) {
                return [
                    'success' => true,
                    'token' => $response['token'],
                    'expires_in' => $response['expires_in'] ?? 3600
                ];
            } else {
                return [
                    'success' => false,
                    'error' => 'Failed to get auth token',
                    'response' => $response
                ];
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => 'Exception: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Validate existing token
     */
    public function validateToken($token) {
        try {
            $url = PhonePeConfig::getBaseUrl() . '/auth/validate';
            
            $headers = [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json'
            ];
            
            $response = $this->makeHttpRequest($url, 'GET', null, $headers);
            
            return $response && isset($response['valid']) && $response['valid'];
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * Make HTTP request
     */
    private function makeHttpRequest($url, $method = 'GET', $data = null, $headers = []) {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        }
        
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Accept: application/json'
            ]);
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        
        curl_close($ch);
        
        if ($error) {
            throw new Exception('CURL Error: ' . $error);
        }
        
        if ($httpCode >= 200 && $httpCode < 300) {
            return json_decode($response, true);
        } else {
            throw new Exception('HTTP Error: ' . $httpCode . ' - ' . $response);
        }
    }
}
?>
