<?php
include 'include/headscript.php';
include('languages/' . $_SESSION['langselect'] . '/tdgen.php');

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connessione al database fallita: " . $conn->connect_error);
}

// Raccogli i dati dal form
$companyName = $_POST['companyname'] ?? '';
$address = $_POST['address'] ?? '';
$city = $_POST['city'] ?? '';
$cap = $_POST['cap'] ?? '';
$country = $_POST['country'] ?? '';
$telephone = $_POST['telephone'] ?? '';
$email = $_POST['email'] ?? '';
$fax = $_POST['fax'] ?? '';
$contactName = $_POST['contactname'] ?? '';
$manufacturerMark = $_POST['manufacturermark'] ?? '';
$idtd = $_POST['idtd'] ?? '';
$idcompany = $_POST['idcompany'] ?? ''; // Assicurati che sia valorizzato

// Prepara la query con placeholder
$stmt = $conn->prepare("INSERT INTO contacts_td (companyName, address, city, cap, country, telephone, email, fax, contactName, manufacturerMark, idtd, companyid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

// Verifica che la preparazione sia andata a buon fine
if (!$stmt) {
    die("Errore nella preparazione della query: " . $conn->error);
}

// Associa i parametri (tutti stringhe 's')
$stmt->bind_param("sssssssssssi", $companyName, $address, $city, $cap, $country, $telephone, $email, $fax, $contactName, $manufacturerMark, $idtd, $idcompany);

// Esegui la query
if ($stmt->execute()) {
    echo "<script>
        var idtd = " . json_encode($idtd) . ";
        var parentUrl = window.opener.location.href;
        if (parentUrl.includes('?')) {
            parentUrl += '&idtd=' + idtd;
        } else {
            parentUrl += '?idtd=' + idtd;
        }
        window.opener.location.href = parentUrl;
        window.close();
    </script>";
} else {
    echo "Errore durante l'inserimento: " . $stmt->error;
}

$stmt->close();
$conn->close();
