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

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit();
}

// PhonePe V2 Production Configuration
$merchantId = "M23N011JX7ZSO";
$clientId = "SU2509232050194428161935"; // Your Client ID
$clientSecret = "ac7d0d8f-8bb1-45c4-baab-5f6f5e6ac3a2"; // Your Client Secret
$baseUrl = "https://api.phonepe.com/apis/pg/checkout/v2/sdk/order"; // Production URL

// Get request data
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid JSON data']);
    exit();
}

// Validate required fields
$requiredFields = ['amount', 'merchantUserId'];
foreach ($requiredFields as $field) {
    if (!isset($input[$field])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => "Missing required field: $field"]);
        exit();
    }
}

$amount = intval($input['amount']); // Amount in paise
$merchantUserId = $input['merchantUserId'];
$merchantTransactionId = "TXN_" . time() . "_" . rand(1000, 9999);

// Create payment payload for Order Token API
$payload = [
    "merchantOrderId" => $merchantTransactionId,
    "amount" => $amount,
    "expireAfter" => 1200, // 20 minutes
    "metaInfo" => [
        "udf1" => $merchantUserId,
        "udf2" => "AstroSidhi App",
        "udf3" => "Production Payment"
    ],
    "paymentFlow" => [
        "type" => "PG_CHECKOUT"
    ]
];

// Convert to JSON
$payloadJson = json_encode($payload);

// Prepare headers for PhonePe V2 API
$headers = [
    'Content-Type: application/json',
    'Authorization: O-Bearer ' . $clientSecret,
    'accept: application/json'
];

// Make request to PhonePe
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadJson);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable verbose output for debugging

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

// Debug logging
error_log("PhonePe API Request: " . $payloadJson);
error_log("PhonePe API Headers: " . json_encode($headers));
error_log("PhonePe API Response: " . $response);
error_log("PhonePe API HTTP Code: " . $httpCode);

if ($curlError) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'error' => 'CURL Error: ' . $curlError
    ]);
    exit();
}

if ($httpCode !== 200) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'error' => 'PhonePe API Error: HTTP ' . $httpCode,
        'response' => $response
    ]);
    exit();
}

$phonepeResponse = json_decode($response, true);

if (!$phonepeResponse || !isset($phonepeResponse['orderId']) || !isset($phonepeResponse['token'])) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'error' => 'PhonePe API Error: ' . ($phonepeResponse['message'] ?? 'Invalid response'),
        'response' => $phonepeResponse
    ]);
    exit();
}

// Return success response with order token
echo json_encode([
    'success' => true,
    'orderId' => $phonepeResponse['orderId'],
    'token' => $phonepeResponse['token'],
    'state' => $phonepeResponse['state'],
    'expireAt' => $phonepeResponse['expireAt'],
    'merchantTransactionId' => $merchantTransactionId,
    'amount' => $amount,
    'phonepeResponse' => $phonepeResponse
]);

// Log the transaction
$logData = [
    'timestamp' => date('Y-m-d H:i:s'),
    'merchantTransactionId' => $merchantTransactionId,
    'merchantUserId' => $merchantUserId,
    'amount' => $amount,
    'status' => 'INITIATED',
    'phonepeResponse' => $phonepeResponse
];

file_put_contents('phonepe_transactions.log', json_encode($logData) . "\n", FILE_APPEND | LOCK_EX);
?>
