<?php
/**
 * PhonePe Order Management
 * Handles order creation and status checking
 */

require_once 'phonepe_config.php';
require_once 'phonepe_auth.php';

class PhonePeOrder {
    private $config;
    private $auth;
    
    public function __construct() {
        $this->config = new PhonePeConfig();
        $this->auth = new PhonePeAuth();
    }
    
    /**
     * Create order in PhonePe
     */
    public function createOrder($orderData) {
        try {
            // Get auth token
            $tokenResponse = $this->auth->getAuthToken();
            
            if (!$tokenResponse['success']) {
                return [
                    'success' => false,
                    'error' => 'Failed to get auth token: ' . $tokenResponse['error']
                ];
            }
            
            $authToken = $tokenResponse['token'];
            
            // Prepare order payload
            $payload = [
                'merchantId' => PhonePeConfig::getMerchantId(),
                'merchantOrderId' => $orderData['orderId'],
                'amount' => $orderData['amount'] * 100, // Amount in paise
                'currency' => 'INR',
                'merchantUserId' => $orderData['userId'],
                'redirectUrl' => PhonePeConfig::REDIRECT_URL,
                'redirectMode' => 'POST',
                'callbackUrl' => PhonePeConfig::CALLBACK_URL,
                'mobileNumber' => $orderData['mobileNumber'] ?? '',
                'email' => $orderData['email'] ?? '',
                'shortName' => 'AstroSidhi',
                'merchantName' => 'AstroSidhi',
                'paymentInstrument' => [
                    'type' => 'PAY_PAGE'
                ]
            ];
            
            $url = PhonePeConfig::getBaseUrl() . '/pg/orders';
            
            $headers = [
                'Authorization: Bearer ' . $authToken,
                'Content-Type: application/json',
                'Accept: application/json'
            ];
            
            $response = $this->makeHttpRequest($url, 'POST', $payload, $headers);
            
            if ($response && isset($response['data'])) {
                return [
                    'success' => true,
                    'orderId' => $response['data']['merchantOrderId'],
                    'token' => $response['data']['token'],
                    'amount' => $orderData['amount'],
                    'merchantId' => PhonePeConfig::getMerchantId(),
                    'response' => $response
                ];
            } else {
                return [
                    'success' => false,
                    'error' => 'Failed to create order',
                    'response' => $response
                ];
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => 'Exception: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Check order status
     */
    public function checkOrderStatus($orderId) {
        try {
            // Get auth token
            $tokenResponse = $this->auth->getAuthToken();
            
            if (!$tokenResponse['success']) {
                return [
                    'success' => false,
                    'error' => 'Failed to get auth token: ' . $tokenResponse['error']
                ];
            }
            
            $authToken = $tokenResponse['token'];
            
            $url = PhonePeConfig::getBaseUrl() . '/pg/orders/' . PhonePeConfig::getMerchantId() . '/' . $orderId;
            
            $headers = [
                'Authorization: Bearer ' . $authToken,
                'Accept: application/json'
            ];
            
            $response = $this->makeHttpRequest($url, 'GET', null, $headers);
            
            if ($response && isset($response['data'])) {
                return [
                    'success' => true,
                    'status' => $response['data']['state'],
                    'orderId' => $orderId,
                    'response' => $response
                ];
            } else {
                return [
                    'success' => false,
                    'error' => 'Failed to check order status',
                    'response' => $response
                ];
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => 'Exception: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * 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);
        }
    }
}
?>
