<?php
include('../include/headscript.php');
include('../class/company.php'); // Ricorda di includere anche $conn
$conn = new mysqli($servername, $username, $password, $database);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id']);
    $severity = intval($_POST['severity']);
    $is_legal = $_POST['is_legal'] === 'Y' ? 'Y' : 'N';

    // Validazione del valore di severity
    if ($severity < 1 || $severity > 10) {
        echo 'Error: Severity must be between 1 and 10.';
        exit;
    }

    // Verifica se esiste già un record per questa analisi
    $checkQuery = "SELECT COUNT(*) AS count FROM analysis_severity WHERE idanalysisvocabulary = ?";
    $stmt = $conn->prepare($checkQuery);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $exists = $row['count'] > 0;
    $stmt->close();

    if ($exists) {
        // Aggiorna il record esistente
        $updateQuery = "
            UPDATE analysis_severity
            SET severity = ?, is_legal = ?
            WHERE idanalysisvocabulary = ?
        ";
        $stmt = $conn->prepare($updateQuery);
        $stmt->bind_param('isi', $severity, $is_legal, $id);
    } else {
        // Inserisce un nuovo record
        $insertQuery = "
            INSERT INTO analysis_severity (idanalysisvocabulary, severity, is_legal)
            VALUES (?, ?, ?)
        ";
        $stmt = $conn->prepare($insertQuery);
        $stmt->bind_param('iis', $id, $severity, $is_legal);
    }

    if ($stmt->execute()) {
        echo 'success';
    } else {
        echo 'Error: Database error - ' . $stmt->error;
    }
    $stmt->close();
}
