<?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');

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

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

use IyzicoIntegration\IyzicoService;

try {
    $iyzicoService = new IyzicoService();
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            throw new Exception('Invalid JSON data');
        }
        
        // Validate payment data
        $validation = $iyzicoService->validatePaymentData($input);
        if (!$validation['valid']) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $validation['error']
            ]);
            exit();
        }
        
        // Initialize 3D Secure payment
        $result = $iyzicoService->initializeThreedsPayment($input);
        
        if ($result['success']) {
            echo json_encode([
                'success' => true,
                'redirect_url' => $result['redirect_url'],
                'payment_id' => $result['payment_id'],
                'conversation_id' => $result['conversation_id']
            ]);
        } else {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                '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) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
