<?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 = 'M23N011JX7ZSO'; // Use merchant ID without TEST prefix
$saltKey = 'ZTI5YjIzYzAtZTFhOC00MWNiLTk4YjAtMDdjYzNhYTdhNDk3';
$saltIndex = '1';

function verifyChecksum($response, $saltKey, $saltIndex) {
    $xVerify = $_SERVER['HTTP_X_VERIFY'] ?? '';
    $responseData = json_encode($response);
    $dataToHash = $responseData . '/pg/v1/status' . $saltKey;
    $expectedChecksum = hash('sha256', $dataToHash) . '###' . $saltIndex;
    
    return hash_equals($expectedChecksum, $xVerify);
}

function logWebhookData($data) {
    $logFile = 'phonepe_webhook_log.txt';
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[$timestamp] " . json_encode($data) . "\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
}

function updatePaymentStatus($merchantTxnId, $status, $responseData) {
    // Database connection (adjust according to your database setup)
    $host = 'localhost';
    $dbname = 'your_database_name';
    $username = 'your_username';
    $password = 'your_password';
    
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Update payment status in your database
        $stmt = $pdo->prepare("
            UPDATE payments 
            SET status = ?, 
                phonepe_response = ?, 
                updated_at = NOW() 
            WHERE merchant_transaction_id = ?
        ");
        
        $stmt->execute([
            $status,
            json_encode($responseData),
            $merchantTxnId
        ]);
        
        return true;
    } catch (PDOException $e) {
        error_log("Database error: " . $e->getMessage());
        return false;
    }
}

// Handle POST request (webhook from PhonePe)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $response = json_decode($input, true);
    
    if (!$response) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid JSON data'
        ]);
        exit();
    }
    
    // Log webhook data
    logWebhookData($response);
    
    // Verify checksum
    if (!verifyChecksum($response, $saltKey, $saltIndex)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Checksum verification failed'
        ]);
        exit();
    }
    
    // Extract payment details
    $merchantTxnId = $response['data']['merchantTransactionId'] ?? '';
    $transactionId = $response['data']['transactionId'] ?? '';
    $status = $response['data']['state'] ?? '';
    $amount = $response['data']['amount'] ?? 0;
    $code = $response['code'] ?? '';
    $message = $response['message'] ?? '';
    
    // Update payment status in database
    $updateResult = updatePaymentStatus($merchantTxnId, $status, $response);
    
    // Prepare response
    $webhookResponse = [
        'success' => true,
        'message' => 'Webhook processed successfully',
        'merchantTxnId' => $merchantTxnId,
        'transactionId' => $transactionId,
        'status' => $status,
        'amount' => $amount,
        'code' => $code,
        'message' => $message,
        'database_updated' => $updateResult
    ];
    
    // Log the response
    logWebhookData($webhookResponse);
    
    echo json_encode($webhookResponse);
    
} else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Handle payment verification request
    $merchantTxnId = $_GET['merchantTxnId'] ?? '';
    
    if (empty($merchantTxnId)) {
        echo json_encode([
            'success' => false,
            'message' => 'Merchant transaction ID is required'
        ]);
        exit();
    }
    
    // Check payment status from database
    $host = 'localhost';
    $dbname = 'your_database_name';
    $username = 'your_username';
    $password = 'your_password';
    
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $pdo->prepare("
            SELECT status, phonepe_response, created_at, updated_at 
            FROM payments 
            WHERE merchant_transaction_id = ?
        ");
        
        $stmt->execute([$merchantTxnId]);
        $payment = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($payment) {
            echo json_encode([
                'success' => true,
                'status' => $payment['status'],
                'response' => json_decode($payment['phonepe_response'], true),
                'created_at' => $payment['created_at'],
                'updated_at' => $payment['updated_at']
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Payment not found'
            ]);
        }
        
    } catch (PDOException $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Database error: ' . $e->getMessage()
        ]);
    }
    
} else {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Method not allowed'
    ]);
}
?>
