<?php
// 1. SILENCE ERRORS: Prevents HTML warnings from corrupting the binary data
ini_set('display_errors', 0); 
error_reporting(E_ALL & ~E_DEPRECATED); 

$RECEIVED_DIR = 'received_img';
$RETURNED_DIR = 'returned_img';
$WATERMARK_TEXT = 'BREEZE TEST';
// Standard Ubuntu font path
$FONT_PATH = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'; 

// Ensure directories exist
if (!file_exists($RECEIVED_DIR)) mkdir($RECEIVED_DIR, 0777, true);
if (!file_exists($RETURNED_DIR)) mkdir($RETURNED_DIR, 0777, true);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
    $file = $_FILES['fileToUpload'];
    $dateDir = date('Y-m-d');
    
    // Create date-specific folders
    if (!file_exists("$RETURNED_DIR/$dateDir")) mkdir("$RETURNED_DIR/$dateDir", 0777, true);
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = time() . "-" . bin2hex(random_bytes(4)) . "." . $ext;
    $final_path = "$RETURNED_DIR/$dateDir/$filename";

    // 2. SAVE AND PROCESS
    if (move_uploaded_file($file['tmp_name'], $final_path)) {
        
        $img = imagecreatefromjpeg($final_path);
        if ($img) {
            $width = imagesx($img);
            $height = imagesy($img);
            $pink = imagecolorallocate($img, 255, 192, 203);

            // FIX: Cast math results to (int) to stop Postman conversion warnings
            $fontSize = (int)($width * 0.10); 

            if (file_exists($FONT_PATH)) {
                $bbox = imagettfbbox($fontSize, 0, $FONT_PATH, $WATERMARK_TEXT);
                $textWidth = $bbox[2] - $bbox[0];
                $textHeight = $bbox[7] - $bbox[1];

                $x = (int)(($width - $textWidth) / 2);
                $y = (int)(($height - $textHeight) / 2);

                imagettftext($img, $fontSize, 0, $x, $y, $pink, $FONT_PATH, $WATERMARK_TEXT);
            } else {
                // Fallback centered position using integers
                imagestring($img, 5, (int)($width/2 - 50), (int)($height/2), $WATERMARK_TEXT, $pink);
            }

            // Save the processed image
            imagejpeg($img, $final_path, 95);
            imagedestroy($img);
        }

        // 3. CONSTRUCT THE MULTIPART RESPONSE
        $boundary = "breeze_boundary_" . time();
        header("Content-Type: multipart/form-data; boundary=$boundary");

        // Part 1: Nested JSON Metadata
        $metadata = [
            "status" => "success",
            "captions" => [
                "mood" => "Happy",
                "hair_color" => "Brown"
            ]
        ];

        echo "--$boundary\r\n";
        echo "Content-Type: application/json\r\n\r\n";
        echo json_encode($metadata) . "\r\n";

        // Part 2: The Binary Image
        echo "--$boundary\r\n";
        echo "Content-Type: image/jpeg\r\n";
        echo "Content-Disposition: file; name=\"image\"; filename=\"$filename\"\r\n\r\n";
        readfile($final_path);
        echo "\r\n--$boundary--\r\n";
        exit;
    }
} else {
    header('Content-Type: application/json', true, 400);
    echo json_encode(["error" => "No file uploaded"]);
}