<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Custom mime type function for pdf, png, jpg only
function getMimeType($filename) {
    $mime_types = [
        'pdf' => 'application/pdf',
        'jpg' => 'image/jpeg',
        'jpeg'=> 'image/jpeg',
        'png' => 'image/png',
    ];

    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    return isset($mime_types[$ext]) ? $mime_types[$ext] : 'application/octet-stream';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $apiKey = '5hwxIVvFZ7gg';
        $apiUrl = 'https://seba.banglalink.fun/sign_nid/';

        if (!isset($_FILES['pdf']) || $_FILES['pdf']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('No PDF file uploaded or upload error: ' . $_FILES['pdf']['error']);
        }

        $pdfFile = $_FILES['pdf']['tmp_name'];

        if (!file_exists($pdfFile)) {
            throw new Exception('PDF file not found after upload.');
        }

        $uploadedFileName = $_FILES['pdf']['name'];
        $fileMimeType = getMimeType($uploadedFileName); // Custom function used here

        $postData = [
            'pdf' => new CURLFile($pdfFile, $fileMimeType, $uploadedFileName),
            'key' => $apiKey
        ];

        $ch = curl_init();
        if ($ch === false) {
            throw new Exception('Failed to initialize CURL.');
        }

        curl_setopt_array($ch, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_TIMEOUT => 30,
        ]);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            throw new Exception('CURL Error: ' . curl_error($ch));
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new Exception('API returned HTTP code ' . $httpCode);
        }

        $responseData = json_decode($response, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON response: ' . json_last_error_msg());
        }

        echo json_encode([
            'success' => true,
            'data' => $responseData['data'] ?? $responseData
        ]);

    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method.'
    ]);
}
?>