<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $apiKey = 'APi-GJLRFRVn9yMX';
    $apiUrl = 'https://make.fastseba.digital/sign/signtonid.php';
    $domain = $_SERVER['HTTP_HOST'];

    if (isset($_FILES['pdf']) && $_FILES['pdf']['error'] === UPLOAD_ERR_OK) {
        $pdfFile = $_FILES['pdf']['tmp_name'];
        $pdfName = $_FILES['pdf']['name'];

        $postData = [
            'key' => $apiKey,
            'domain' => $domain,
            'pdf' => curl_file_create($pdfFile, 'application/pdf', $pdfName)
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Origin: ']);

        $response = curl_exec($ch);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($curlError) {
            echo json_encode(['status' => 'error', 'message' => 'cURL error: ' . $curlError]);
            exit;
        }

        $data = json_decode($response, true);

        if (!$data) {
            echo json_encode(['status' => 'error', 'message' => 'Failed to decode JSON response.']);
            exit;
        }

        if ($data['success'] === true) {
            $imagePath = 'photo/';
            $images = $data['data']['images'] ?? [];

            foreach ($images as $index => $imageUrl) {
                $imageName = 'img_' . uniqid() . '.' . pathinfo($imageUrl, PATHINFO_EXTENSION);
                $imageFile = $imagePath . $imageName;

                $imageData = @file_get_contents($imageUrl);
                if ($imageData !== false) {
                    file_put_contents($imageFile, $imageData);
                    $data['data']['images'][$index] = $imageFile;
                }
            }

            echo json_encode([
                'status' => 'success',
                'data' => $data['data']
            ]);
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => $data['message'] ?? 'Unknown API error.'
            ]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No file uploaded or upload error.']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>