<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// PhonePe Test Credentials
$merchantId = 'TEST-M23N011JX7ZSO_25092';
$saltKey = 'ZTI5YjIzYzAtZTFhOC00MWNiLTk4YjAtMDdjYzNhYTdhNDk3';
$saltIndex = '1';
$phonePeBaseUrl = 'https://api-preprod.phonepe.com/apis/pg-sandbox';

function generateChecksum($data, $apiEndPoint, $saltKey, $saltIndex) {
    $dataToHash = $data . $apiEndPoint . $saltKey;
    $hash = hash('sha256', $dataToHash);
    return $hash . '###' . $saltIndex;
}

function createPhonePeOrder($amount, $merchantTxnId, $mobileNumber, $redirectUrl) {
    global $merchantId, $saltKey, $saltIndex, $phonePeBaseUrl;
    
    $apiEndPoint = '/pg/v1/pay';
    
    // Create payment request data
    $paymentData = [
        'merchantId' => $merchantId,
        'merchantTransactionId' => $merchantTxnId,
        'merchantUserId' => 'USER_' . $merchantTxnId,
        'amount' => $amount,
        'redirectUrl' => $redirectUrl,
        'redirectMode' => 'POST',
        'callbackUrl' => $redirectUrl,
        'mobileNumber' => $mobileNumber,
        'paymentInstrument' => [
            'type' => 'PAY_PAGE'
        ]
    ];
    
    $data = json_encode($paymentData);
    $checksum = generateChecksum($data, $apiEndPoint, $saltKey, $saltIndex);
    
    // Prepare request payload
    $requestPayload = [
        'request' => base64_encode($data)
    ];
    
    // Make API call to PhonePe
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $phonePeBaseUrl . $apiEndPoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestPayload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'X-VERIFY: ' . $checksum,
        'accept: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return [
            'success' => false,
            'message' => 'cURL Error: ' . $error
        ];
    }
    
    if ($httpCode !== 200) {
        return [
            'success' => false,
            'message' => 'PhonePe API Error: HTTP ' . $httpCode,
            'response' => $response
        ];
    }
    
    $responseData = json_decode($response, true);
    
    if (isset($responseData['success']) && $responseData['success'] === true) {
        $paymentUrl = $responseData['data']['instrumentResponse']['redirectInfo']['url'];
        
        return [
            'success' => true,
            'message' => 'Order created successfully',
            'paymentData' => [
                'body' => base64_encode($data),
                'apiEndPoint' => $apiEndPoint,
                'checksum' => $checksum
            ],
            'paymentUrl' => $paymentUrl,
            'phonepe_response' => $responseData
        ];
    } else {
        return [
            'success' => false,
            'message' => 'PhonePe API Error: ' . ($responseData['message'] ?? 'Unknown error'),
            'phonepe_response' => $responseData
        ];
    }
}

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid JSON input'
        ]);
        exit();
    }
    
    $amount = $input['amount'] ?? 0;
    $merchantTxnId = $input['merchantTxnId'] ?? '';
    $mobileNumber = $input['mobileNumber'] ?? '';
    $redirectUrl = $input['redirectUrl'] ?? 'https://astro.siddharthnahar.in/phonepe_success';
    
    // Validate required fields
    if (empty($amount) || empty($merchantTxnId)) {
        echo json_encode([
            'success' => false,
            'message' => 'Amount and transaction ID are required'
        ]);
        exit();
    }
    
    // Create PhonePe order
    $result = createPhonePeOrder($amount, $merchantTxnId, $mobileNumber, $redirectUrl);
    
    echo json_encode($result);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Only POST method allowed'
    ]);
}
?>
