<?php

header('Content-Type: application/json');

require_once('../Connections/cmctrfdb.php');

require_once('../webassist/mysqli/rsobj.php');



$conn = new mysqli($servername, $username, $password, $dbname);



$response = ['success' => false, 'message' => ''];



// Inizia l'output buffering per catturare eventuali output indesiderati

ob_start();



if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    if (!empty($_FILES['file']) && isset($_POST['idtrf'])) {

        $file = $_FILES['file'];

        $idtrf = $_POST['idtrf']; // Ottieni idtrf dal POST

        $uploadDir = 'uploadimages/';

        $allowedExtensions = ['jpg', 'jpeg', 'png'];



        $filename = $file['name'];

        $tempname = $file['tmp_name'];

        $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));



        if (!in_array($filetype, $allowedExtensions)) {

            $response['message'] = 'Invalid file type';

            echo json_encode($response);

            // Pulisci e termina l'output buffering

            ob_end_clean();

            exit;

        }



        $newFilename = time() . '-' . strtolower($filename);

        $uploadFile = $uploadDir . basename($newFilename);



        if (move_uploaded_file($tempname, $uploadFile)) {

            // Inserisci il record nel database

            $stmt = $conn->prepare("INSERT INTO additionalphotos (idtrf, filenameadditionalphotos) VALUES (?, ?)");

            if ($stmt === false) {

                $response['message'] = 'Database prepare failed: ' . $conn->error;

                echo json_encode($response);

                // Pulisci e termina l'output buffering

                ob_end_clean();

                exit;

            }

            $stmt->bind_param("is", $idtrf, $newFilename);



            if ($stmt->execute()) {

                $response['success'] = true;

                $response['filename'] = $newFilename;

            } else {

                $response['message'] = 'Database insertion failed: ' . $stmt->error;

            }

            $stmt->close();

        } else {

            $response['message'] = 'File upload failed';

        }

    } else {

        $response['message'] = 'No file uploaded or idtrf missing';

    }

} else {

    $response['message'] = 'Invalid request method';

}



// Cattura tutto l'output aggiuntivo

$output = ob_get_clean();

if (!empty($output)) {

    error_log("Unexpected output detected: " . $output);

    echo json_encode(['success' => false, 'message' => 'Unexpected output detected', 'output' => $output]);

    exit;

}



echo json_encode($response);



$conn->close();

