<?php
include('../include/headscript.php');
include("../class/company.php");

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

// Recupera il valore di reportId dal POST
$reportId = isset($_POST['reportId']) ? $_POST['reportId'] : 0;

// Query per ottenere le analisi associate al report, comprese le parti
$query = "
    SELECT 
    a.nameanalysisvoc AS name, 
    ap.test_Rating AS finalRating
FROM result_project rp
LEFT JOIN analysis_project ap ON rp.idanalysis_project = ap.idAnalysis_Project
LEFT JOIN analysisvocabulary a ON ap.result_TestName = a.idanalysisvocabulary
WHERE rp.idreports = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $reportId);
$stmt->execute();
$result = $stmt->get_result();

// Array per raccogliere le analisi e le relative valutazioni (rating)
$analysis = [];

// Raggruppa le analisi e seleziona il rating più restrittivo
while ($row = $result->fetch_assoc()) {
    $name = $row['name'];
    $rating = strtoupper(trim($row['finalRating'])); // Normalize to uppercase and trim spaces

    // Convert specific terms into normalized ratings
    if ($rating === 'COMPLIES') {
        $rating = 'PASS';
    }

    // Initialize the rating if not set
    if (!isset($analysis[$name])) {
        $analysis[$name] = $rating;
    } else {
        // Apply the most restrictive rating: Fail > Data > N/A > // > Pass
        if ($analysis[$name] != 'FAIL' && ($rating == 'FAIL' || $rating == "DOESN'T COMPLY")) {
            $analysis[$name] = 'FAIL';
        } elseif ($analysis[$name] != 'FAIL' && $analysis[$name] != 'DATA' && $rating == 'DATA') {
            $analysis[$name] = 'DATA';
        } elseif ($analysis[$name] != 'FAIL' && $analysis[$name] != 'DATA' && $analysis[$name] != 'N/A' && $rating == 'N/A') {
            $analysis[$name] = 'N/A';
        } elseif ($analysis[$name] != 'FAIL' && $analysis[$name] != 'DATA' && $analysis[$name] != 'N/A' && $analysis[$name] != '//' && $rating == '//') {
            $analysis[$name] = '//';
        } elseif ($analysis[$name] == 'PASS' && $rating == 'PASS') {
            $analysis[$name] = 'PASS';
        }
    }
}



// Trasforma i dati in un array
$finalAnalysis = [];
foreach ($analysis as $name => $finalRating) {
    $finalAnalysis[] = [
        'name' => $name,
        'finalRating' => $finalRating
    ];
}

// Restituisci i dati come JSON
echo json_encode($finalAnalysis);
