<?php
require_once('../Connections/cmctrfdb.php'); // definisce $servername, $username, $password, $dbname
header('X-Content-Type-Options: nosniff');

function json_out($arr)
{
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($arr);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

// accetto sia POST (AJAX) che GET (link classico)
$idtrf = null;
$field = 'photofilename'; // campo di default per la “foto principale”

if ($method === 'POST') {
    $idtrf = isset($_POST['idtrf']) ? (int)$_POST['idtrf'] : 0;
    if (!empty($_POST['field'])) {
        $field = preg_replace('/[^a-zA-Z0-9_]/', '', $_POST['field']); // sanitize
    }
} else { // GET
    $idtrf = isset($_GET['idtrf']) ? (int)$_GET['idtrf'] : 0;
    if (!empty($_GET['field'])) {
        $field = preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['field']);
    }
}

if ($idtrf <= 0) {
    if ($method === 'POST') json_out(['ok' => false, 'msg' => 'bad id']);
    header("Location: index.php");
    exit;
}

// connessione
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    if ($method === 'POST') json_out(['ok' => false, 'msg' => 'db connect error']);
    die("Connessione al database fallita");
}

// (opzionale) prendo il filename corrente per fare unlink
// NB: solo se il campo è uno dei previsti
$allowedFields = ['photofilename', 'photoone', 'phototwo'];
if (!in_array($field, $allowedFields, true)) {
    $conn->close();
    if ($method === 'POST') json_out(['ok' => false, 'msg' => 'invalid field']);
    header("Location: adddocument.php?idtrf=$idtrf");
    exit;
}

$col = $field; // alias per chiarezza

// recupero valore attuale
$currentFile = null;
$sqlSel = "SELECT `$col` AS f FROM `trf-details` WHERE idtrfdetails = ?";
$stmtSel = $conn->prepare($sqlSel);
$stmtSel->bind_param("i", $idtrf);
$stmtSel->execute();
$stmtSel->bind_result($currentFile);
$stmtSel->fetch();
$stmtSel->close();

// metto a NULL il campo
$sqlUpd = "UPDATE `trf-details` SET `$col` = NULL WHERE idtrfdetails = ?";
$stmtUpd = $conn->prepare($sqlUpd);
$stmtUpd->bind_param("i", $idtrf);
$stmtUpd->execute();
$affected = $stmtUpd->affected_rows;
$stmtUpd->close();

// (opzionale) elimino file fisico se presente
if (!empty($currentFile)) {
    // photofilename e foto addizionali stanno in uploadimages/, le top photo spesso pure
    $path = __DIR__ . "/uploadimages/" . $currentFile;
    if (is_file($path)) {
        @unlink($path);
    }
}

$conn->close();

if ($method === 'POST') {
    json_out(['ok' => ($affected >= 0), 'idtrf' => $idtrf, 'field' => $field]);
}

// GET → redirect alla pagina
header("Location: adddocument.php?idtrf=$idtrf&t=" . time());
exit;
