<?php 
    include "../db/headerApi.php";
    include "../db/connection_main.php";

    $qr = json_decode($_POST["QR"]);
    $newid = explode("|", $qr);
    $file1 = null;
    $file2 = null;

    if (!empty($qr)) {
        foreach ($_FILES['ATTACH1']['tmp_name'] as $k => $v) {
            $path1 = $_FILES['ATTACH1']['name'][$k];
            $ext1 = pathinfo($path1, PATHINFO_EXTENSION);
            $filename1 = $newid[0]."_1.".$ext1;
            $targetPath1 = "../../webfiles/shopfloor/receiving/".$filename1;

            $uploadSuccess = false;
            if (in_array($ext1, ['jpg', 'jpeg', 'png'])) {
                // Process and compress image directly from temp folder to target path
                $uploadSuccess = compressAndSaveImage($_FILES['ATTACH1']["tmp_name"][$k], $targetPath1, $ext1);
            } else {
                // Fallback for PDFs or other documents
                $uploadSuccess = move_uploaded_file($_FILES['ATTACH1']["tmp_name"][$k], $targetPath1);
            }

            if ($uploadSuccess) {
                $file1 = $filename1;

                $sql = "UPDATE YTYCUSTOM.XX_YTY_INCOMING_OUTGOING_INSPECTION_TBL
                           SET ATTACHMENT1 = :ATTACHMENT1
                         WHERE ID = :INSP_ID";
               
                $sqlarr = oci_parse($dbcon , $sql);
                oci_bind_by_name($sqlarr, ':ATTACHMENT1', $file1);
                oci_bind_by_name($sqlarr, ':INSP_ID', $newid[0]);
                $r = oci_execute($sqlarr, OCI_NO_AUTO_COMMIT);
        
                if (!$r) {
                    $e = oci_error($sqlarr);
                    $errorMsg = json_encode($e['message']);
                    goto finalStep;
                }

            } else {
                $errorMsg = "Failed to upload Attachment1";
                goto finalStep;
            }
        }

        foreach ($_FILES['ATTACH2']['tmp_name'] as $k => $v) {
            $path2 = $_FILES['ATTACH2']['name'][$k];
            $ext2 = pathinfo($path2, PATHINFO_EXTENSION);
            $filename2 = $newid[0]."_2.".$ext2;
            $targetPath2 = "../../webfiles/shopfloor/receiving/".$filename2;

            $uploadSuccess = false;
            if (in_array($ext2, ['jpg', 'jpeg', 'png'])) {
                // Process and compress image directly from temp folder to target path
                $uploadSuccess = compressAndSaveImage($_FILES['ATTACH2']["tmp_name"][$k], $targetPath2, $ext2);
            } else {
                // Fallback for PDFs or other documents
                $uploadSuccess = move_uploaded_file($_FILES['ATTACH2']["tmp_name"][$k], $targetPath2);
            }

            if ($uploadSuccess) {
                $file2 = $filename2;

                $sql = "UPDATE YTYCUSTOM.XX_YTY_INCOMING_OUTGOING_INSPECTION_TBL
                           SET ATTACHMENT2 = :ATTACHMENT2
                         WHERE ID = :INSP_ID";
               
                $sqlarr = oci_parse($dbcon , $sql);
                oci_bind_by_name($sqlarr, ':ATTACHMENT2', $file2);
                oci_bind_by_name($sqlarr, ':INSP_ID', $newid[0]);
                $r = oci_execute($sqlarr, OCI_NO_AUTO_COMMIT);
        
                if (!$r) {
                    $e = oci_error($sqlarr);
                    $errorMsg = json_encode($e['message']);
                    goto finalStep;
                }
            } else {
                $errorMsg = "Failed to upload Attachment2";
                goto finalStep;
            }
        }
        
    } else {
        $errorMsg = "Data not found";
    }

    function compressAndSaveImage($source, $destination, $extension) {
        // 1. Get original image sizes
        list($width, $height) = getimagesize($source);
        if (!$width || !$height) return false;

        // 2. Set an optional maximum boundary dimension (e.g., 2000px) 
        // This stops massive mobile photos from consuming too much database storage or RAM
        $maxDimension = 2000;
        if ($width > $maxDimension || $height > $maxDimension) {
            $ratio = min($maxDimension / $width, $maxDimension / $height);
            $newWidth = round($width * $ratio);
            $newHeight = round($height * $ratio);
        } else {
            $newWidth = $width;
            $newHeight = $height;
        }

        // 3. Prepare canvas
        $virtualImage = imagecreatetruecolor($newWidth, $newHeight);

        // 4. Load original image by type
        if ($extension === 'png') {
            $sourceImage = imagecreatefrompng($source);
            imagealphablending($virtualImage, false);
            imagesavealpha($virtualImage, true);
        } else {
            $sourceImage = imagecreatefromjpeg($source);
        }

        if (!$sourceImage) return false;

        // 5. Resize original into canvas
        imagecopyresampled($virtualImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

        // 6. Save back to disk with compression parameters
        if ($extension === 'png') {
            $success = imagepng($virtualImage, $destination, 6); // Scale 0-9 (6 is standard compression)
        } else {
            $success = imagejpeg($virtualImage, $destination, 75); // Quality 0-100 (75 drastically drops file size beautifully)
        }

        // 7. Clean up RAM allocation
        imagedestroy($virtualImage);
        imagedestroy($sourceImage);

        return $success;
    }

finalStep:
    $result = [];
    if ($errorMsg == "") {
        oci_commit($dbcon);
        $result[] = [
            "message" => "Success",
            "id" => $newid[0]
        ];
    } else {
        oci_rollback($dbcon);
        $result[] = [
            "message" => $errorMsg,
            "id" => ""
        ];
    }
    print json_encode($result);
?>