<?php
// add-document.php
include('include/headscript.php');

// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
    die("Errore di connessione: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $document_name = $conn->real_escape_string($_POST['document_name']);
    $page_id = isset($_POST['page_id']) ? (int)$_POST['page_id'] : null;
    $idsections = isset($_POST['idsections']) ? (int)$_POST['idsections'] : null;
    $max_documents = isset($_POST['max_documents']) ? (int)$_POST['max_documents'] : 0;
    $is_required = isset($_POST['is_required']) ? (int)$_POST['is_required'] : 0;
    $notes = !empty($_POST['notes']) ? $conn->real_escape_string($_POST['notes']) : null;
    $tags = isset($_POST['tags']) ? $_POST['tags'] : []; // Array di tag selezionati

    // Inserisci il documento
    $stmt = $conn->prepare("INSERT INTO documents (document_name, page_id, idsections, max_documents, is_required, notes) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("siiiss", $document_name, $page_id, $idsections, $max_documents, $is_required, $notes);
    $stmt->execute();
    $document_id = $conn->insert_id;
    $stmt->close();

    // Inserisci i tag nella tabella document_tags
    if (!empty($tags)) {
        $stmt = $conn->prepare("INSERT INTO document_tags (document_id, tag_id) VALUES (?, ?)");
        foreach ($tags as $tag_id) {
            $tag_id = (int)$tag_id;
            $stmt->bind_param("ii", $document_id, $tag_id);
            $stmt->execute();
        }
        $stmt->close();
    }

    header("Location: documents-settings.php?success=1");
    exit();
} else {
    header("Location: documents-settings.php?error=1");
    exit();
}

$conn->close();
