<?php
// Check if the request contains form data
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST) === false) {
    // Handle form data
    $name = $_POST['name'];
    $id_number = $_POST['id_number'];
    $parish = $_POST['parish'];
    $blood_group = $_POST['blood_group'];
    $date_issued = $_POST['date_issued'];
    $image_url = $_POST['image_url'];
    $sign_url = $_POST['sign_url'];
} 

elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the raw JSON data from the request body
    $inputJSON = file_get_contents('php://input');

    // Check if JSON data was received
    if ($inputJSON === false || empty($inputJSON)) {
        http_response_code(400); // Bad Request
        echo json_encode(array('error' => 'No valid input data received'));
        exit;
    }

    // Decode the JSON data
    $data = json_decode($inputJSON, true);

    // Check if the JSON data is valid
    if ($data === null) {
        http_response_code(400); // Bad Request
        echo json_encode(array('error' => 'Invalid JSON data'));
        exit;
    }

    // Extract data from the JSON object
    $name = $data['name'];
    $id_number = $data['id_number'];
    $parish = $data['parish'];
    $blood_group = $data['blood_group'];
    $date_issued = $data['date_issued'];
    $image_url = $data['image_url'];
    $sign_url = $data['sign_url'];
} else {
    http_response_code(400); // Bad Request
    echo json_encode(array('error' => 'Invalid request'));
    exit;
}

    // Fetch image data from URL
    $imageData = file_get_contents($image_url);
    $signatureData = file_get_contents($sign_url);
    if ($imageData === false) {
        // Handle error if unable to fetch image data
        http_response_code(400); // Bad Request
        echo json_encode(array('error' => 'Failed to fetch image from the provided URL'));
        exit;
    }

    // Create image from fetched data
    $image = imagecreatefromstring($imageData);
    $signature = imagecreatefromstring($signatureData);

    // Load your A5-sized background image
    $backgroundImage = imagecreatefrompng('../images/idcard.png');

    // Create an empty image (A5 size: 148mm x 210mm at 300dpi)
    $idCard = imagecreatetruecolor(794, 2245); // A5 size at 300dpi

    // Set background color (optional)
    $backgroundColor = imagecolorallocate($idCard, 255, 255, 255); // White background
    imagefill($idCard, 0, 0, $backgroundColor);

    // Merge the background image with the ID card
    imagecopyresampled($idCard, $backgroundImage, 0, 0, 0, 0, 794, 2245, imagesx($backgroundImage), imagesy($backgroundImage));

    // Overlay text (name, ID number, etc.) on the ID card
    $textColor = imagecolorallocate($idCard, 0, 0, 0); // Black text color

    // Font settings
    $font = './Montserrat-Bold.ttf'; // Replace with your font file
    $fontSize = 25;
    
    // Merge the passport photo onto the ID card
    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);
    $photoWidth = 550; // Adjust the size of the passport photo as needed
    $photoHeight = 500; // Adjust the size of the passport photo as needed
    $photoX = 122; // X-coordinate for the passport photo position
    $photoY = 280; // Y-coordinate for the passport photo position
    imagecopyresampled($idCard, $image, $photoX, $photoY, 0, 0, $photoWidth, $photoHeight, $imageWidth, $imageHeight);


    // Merge the passport photo onto the ID card
    $signatureWidth = imagesx($signature);
    $signatureHeight = imagesy($signature);
    $photosignWidth = 400; // Adjust the size of the passport photo as needed
    $photosignHeight = 200; // Adjust the size of the passport photo as needed
    $photosignX = 200; // X-coordinate for the passport photo position
    $photosignY = 850; // Y-coordinate for the passport photo position
    imagecopyresampled($idCard, $signature, $photosignX, $photosignY, 0, 0, $photosignWidth, $photosignHeight, $signatureWidth, $signatureHeight);
    
    // Example: Write name on ID card
   // $textX = 20;
    $textfontSize = 40;
    $bbox = imagettfbbox($textfontSize, 0, $font, $name);
    $textWidth = $bbox[2] - $bbox[0];
    $textX = (794 - $textWidth) / 2;
    $textY = 850;
    imagettftext($idCard, $textfontSize, 0, $textX, $textY, $textColor, $font, "$name");

    // Example: Write ID number on ID card
    $idTextX = 300;
    $idTextY = 1970; // Adjust Y-coordinate as needed
    imagettftext($idCard, $fontSize, 0, $idTextX, $idTextY, $textColor, $font, "$id_number");
    
    // Example: Write Plan on ID card
    $blood_groupTextX = 300;
    $blood_groupTextY = 1810; // Adjust Y-coordinate as needed
    imagettftext($idCard, $fontSize, 0, $blood_groupTextX, $blood_groupTextY, $textColor, $font, "$blood_group");
    
    // Example: Write Validity on ID card
    $date_issuedTextX = 300;
    $date_issuedTextY = 1885; // Adjust Y-coordinate as needed
    imagettftext($idCard, $fontSize, 0, $date_issuedTextX, $date_issuedTextY, $textColor, $font, "$date_issued");


// Example: Write Client on ID card
    $parishTextX = 125;
    $parishTextY = 1100; // Adjust Y-coordinate as needed
    $parishfontSize = 15;
    imagettftext($idCard, $parishfontSize, 0, $parishTextX, $parishTextY, $textColor, $font, "$parish");


    // Save the generated ID card image to a local folder
    $outputFileName = time() . '.jpg'; // Example file name with timestamp
    $outputFilePath = 'cards/' . $outputFileName;

    imagejpeg($idCard, $outputFilePath); // Save the image as JPEG (you can use PNG if preferred)

    // Free up memory
    imagedestroy($backgroundImage);
    imagedestroy($idCard);
    imagedestroy($image);
    // Return the URL or file path of the saved ID card image in the API response
    $response = array(
        'success' => true,
        'file_url' => "https://visuretech.com/lacmon/admin/" . $outputFilePath // You can return the URL here if your server is publicly accessible
    );

    header('Content-Type: application/json');
    echo json_encode($response);
 
?>
