<?php

header('Content-Type: application/json');

require_once __DIR__ . '/../vendor/autoload.php';

use IyzicoIntegration\IyzicoService;

try {
    $iyzicoService = new IyzicoService();
    $config = require __DIR__ . '/../config/iyzico.php';
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Get callback data from Iyzico
        $callbackData = $_POST;
        
        if (!isset($callbackData['paymentId']) || !isset($callbackData['conversationId'])) {
            throw new Exception('Missing required callback parameters');
        }
        
        // Complete the 3D Secure payment
        $result = $iyzicoService->completeThreedsPayment($callbackData);
        
        if ($result['success']) {
            // Payment successful - redirect to success URL
            $successUrl = $config['success_url'] . '?' . http_build_query([
                'payment_id' => $result['payment_id'],
                'status' => 'success',
                'conversation_id' => $callbackData['conversationId']
            ]);
            
            // Log successful payment (you can store this in database)
            error_log('Payment successful: ' . json_encode($result));
            
            // Return success response for mobile webview
            echo json_encode([
                'success' => true,
                'redirect_url' => $successUrl,
                'payment_data' => $result
            ]);
            
        } else {
            // Payment failed - redirect to failure URL
            $failureUrl = $config['failure_url'] . '?' . http_build_query([
                'error' => $result['error'],
                'error_code' => $result['error_code'],
                'conversation_id' => $callbackData['conversationId']
            ]);
            
            // Log failed payment
            error_log('Payment failed: ' . json_encode($result));
            
            // Return failure response for mobile webview
            echo json_encode([
                'success' => false,
                'redirect_url' => $failureUrl,
                'error' => $result['error'],
                'error_code' => $result['error_code']
            ]);
        }
        
    } else {
        http_response_code(405);
        echo json_encode([
            'success' => false,
            'error' => 'Method not allowed'
        ]);
    }
    
} catch (Exception $e) {
    $config = require __DIR__ . '/../config/iyzico.php';
    $failureUrl = $config['failure_url'] . '?' . http_build_query([
        'error' => $e->getMessage(),
        'error_code' => 'CALLBACK_ERROR'
    ]);
    
    error_log('Callback error: ' . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'redirect_url' => $failureUrl,
        'error' => $e->getMessage()
    ]);
}
