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

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

// Calcolo rating dei fornitori con dettagli
$query = "
INSERT INTO supplier_ratings (
    name, 
    total_products, 
    total_analyses, 
    pass_analyses, 
    fail_analyses, 
    data_analyses, 
    rating, 
    calculation_date
)
SELECT 
    p.namesupplier AS name,
    COUNT(DISTINCT p.idproducts) AS total_products,
    COUNT(ap.idAnalysis_Project) AS total_analyses,
    SUM(CASE 
        WHEN LOWER(ap.test_Rating) IN ('pass', 'p', 'comply', 'complies') THEN 1 
        ELSE 0 
    END) AS pass_analyses,
    SUM(CASE 
        WHEN LOWER(ap.test_Rating) IN ('fail', 'f', 'doesn\'t comply') THEN 1 
        ELSE 0 
    END) AS fail_analyses,
    SUM(CASE 
        WHEN LOWER(ap.test_Rating) NOT IN ('pass', 'p', 'comply', 'complies', 'fail', 'f', 'doesn\'t comply') THEN 1 
        ELSE 0 
    END) AS data_analyses,
    CASE 
        WHEN SUM(CASE WHEN LOWER(ap.test_Rating) IN ('fail', 'f', 'doesn\'t comply') THEN 1 ELSE 0 END) = 0
            AND SUM(CASE WHEN LOWER(ap.test_Rating) NOT IN ('pass', 'p', 'comply', 'complies', 'fail', 'f', 'doesn\'t comply') THEN 1 ELSE 0 END) = 0
        THEN 100
        ELSE GREATEST(0, 100 - (
            SUM(
                CASE 
                    WHEN LOWER(ap.test_Rating) IN ('fail', 'f', 'doesn\'t comply') THEN 
                        POWER(COALESCE(asv.severity, 1), 2) * 
                        CASE WHEN COALESCE(asv.is_legal, 'N') = 'Y' THEN 2.0 ELSE 1.0 END
                    ELSE 0
                END
            ) / NULLIF(COUNT(ap.idAnalysis_Project), 0) * 100 * 
            (1 + 2 * (SUM(CASE WHEN LOWER(ap.test_Rating) IN ('fail', 'f', 'doesn\'t comply') THEN 1 ELSE 0 END) / NULLIF(COUNT(ap.idAnalysis_Project), 0)))
            + SUM(CASE 
                WHEN LOWER(ap.test_Rating) NOT IN ('pass', 'p', 'comply', 'complies', 'fail', 'f', 'doesn\'t comply') THEN 0.3 
                ELSE 0 
            END)
        ))
    END AS rating,
    NOW() AS calculation_date
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 analysis_severity asv ON ap.idAnalysis = asv.idanalysisvocabulary
GROUP BY p.namesupplier
ON DUPLICATE KEY UPDATE
    total_products = VALUES(total_products),
    total_analyses = VALUES(total_analyses),
    pass_analyses = VALUES(pass_analyses),
    fail_analyses = VALUES(fail_analyses),
    data_analyses = VALUES(data_analyses),
    rating = VALUES(rating),
    calculation_date = VALUES(calculation_date);
";

if ($conn->query($query) === TRUE) {
    echo json_encode(['message' => 'Ratings calculated successfully!']);
} else {
    echo json_encode([
        'message' => $conn->error,
        'exception' => 'mysqli_sql_exception',
        'file' => __FILE__,
        'line' => __LINE__
    ]);
}

$conn->close();
