<?php
include('../include/headscript.php');

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

// Recupera il nome del fornitore
$supplierName = isset($_GET['supplier']) ? $conn->real_escape_string($_GET['supplier']) : '';

// Verifica che il nome del fornitore sia presente
if (empty($supplierName)) {
    die(json_encode(['error' => 'Supplier name is missing']));
}

// Query per la distribuzione totale delle analisi
$queryDistribution = "
SELECT 
    av.nameanalysisvoc AS analysis_name,
    COUNT(ap.idAnalysis_Project) AS total
FROM products p
JOIN reports r ON p.idproducts = r.idproducts
JOIN parts pt ON r.idreports = pt.idreports
JOIN analysis_project ap ON pt.idParts = ap.idPart
LEFT JOIN analysisvocabulary av ON ap.result_TestName = av.idanalysisvocabulary
WHERE p.namesupplier = '$supplierName' AND av.preferred = 'Y'
GROUP BY av.nameanalysisvoc
ORDER BY total DESC
LIMIT 10;
";

$resultDistribution = $conn->query($queryDistribution);
$analysisDistribution = [];
while ($row = $resultDistribution->fetch_assoc()) {
    $analysisDistribution[] = $row;
}

// Query per la distribuzione delle analisi FAIL
$queryFail = "
SELECT 
    av.nameanalysisvoc AS analysis_name,
    COUNT(*) AS fail
FROM products p
LEFT JOIN reports r ON p.idproducts = r.idproducts
LEFT JOIN parts pt ON r.idreports = pt.idreports
LEFT JOIN analysis_project ap ON pt.idParts = ap.idPart
LEFT JOIN analysisvocabulary av ON ap.result_TestName = av.idanalysisvocabulary
WHERE 
    p.namesupplier = '$supplierName' 
    AND LOWER(ap.test_Rating) IN ('fail', 'f', 'doesn\'t comply')
    AND av.preferred = 'Y'
GROUP BY av.nameanalysisvoc
ORDER BY fail DESC
LIMIT 10;

";

$resultFail = $conn->query($queryFail);
$failDistribution = [];
while ($row = $resultFail->fetch_assoc()) {
    $failDistribution[] = $row;
}

// Restituisci i dati come JSON
header('Content-Type: application/json');
echo json_encode([
    'analysisDistribution' => $analysisDistribution,
    'failDistribution' => $failDistribution
]);
