<?php

include('../../Connections/repnew.php');

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

// Controlla la connessione
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Ottieni il products_refnumber dal parametro GET (es: ?refnumber=PRD12345)
$products_refnumber = "M1367";

// Esegui la query per ottenere i dati per un solo prodotto
$sql = "SELECT 
    p.idproducts, 
    p.products_refnumber, 
    p.products_description, 
    p.products_style, 
    p.products_styledescription, 
    p.products_sku, 
    p.products_color, 
    p.products_season, 
    p.products_market, 
    p.products_order, 
    p.product_buyer, 
    p.product_claimedfiber, 
    p.products_fibercontentresult, 
    p.dateprod, 
    p.namesupplier, 
    p.agerange, 
    p.products_billto, 
    p.products_billtocde, 
    p.products_codeanddesc, 
    p.products_division, 
    p.products_phase, 
    p.timestampinsert, 
    p.products_country, 
    p.products_region,

    r.idreports, 
    r.reportsNumberLab, 
    r.reportDateIn, 
    r.reportsDateOut, 
    r.reportsDateDue, 
    r.reportsRating, 
    r.reportsRating2, 
    r.pdffilename, 
    r.reports_LabName, 
    r.reports_testype, 
    r.reports_invoicenumber, 
    r.reports_invoiceamount, 
    r.reports_invoiceadate,

    pt.idParts, 
    pt.partsCode, 
    pt.partsDescription, 
    pt.partsColor, 
    pt.partsMaterial,

    a.idAnalysis_Project, 
    av.nameanalysisvoc,  -- Nome dell'analisi
    a.test_Rating, 
    a.test_Rating2, 
    a.requirements, 
    a.reference, 
    a.analysisgroupcode,

    rs.idResult_Project, 
    cv.namecompoundsvocabulary,  -- Nome del composto
    rs.result_AnalytsRating, 
    rs.result_Value, 
    rs.result_Comment, 
    rs.result_Rating, 
    rs.result_UnitofMeasure, 
    rs.cas, 
    rs.requirements AS result_requirements, 
    rs.reference AS result_reference

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 a ON pt.idParts = a.idPart
LEFT JOIN 
    analysisvocabulary av ON a.result_TestName = av.idanalysisvocabulary  -- Left Join con analysisvocabulary
LEFT JOIN 
    result_project rs ON a.idAnalysis_Project = rs.idanalysis_project
LEFT JOIN 
    compundsvocabulary cv ON rs.result_AnalytsName = cv.idcompoundsvocabulary  -- Left Join con compundsvocabulary
WHERE 
    p.products_refnumber = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $products_refnumber);  // Associa il parametro
$stmt->execute();
$result = $stmt->get_result();

// Inizializza la struttura del JSON
$data = array(
    'key' => '30b2ab1800e8ae6c3b6f107a904ebefa',  // Chiave unica
    'secret_key' => '4b372825fde4271a2268cd7927f43c18',
    'reflab' => 'J90138',
    'product' => array()
);

$reports = array();

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Se il prodotto non è stato ancora inserito, aggiungilo
        if (empty($data['product'])) {
            $data['product'] = array(
                'products_refnumber' => $row['products_refnumber'],
                'products_description' => $row['products_description'],
                'products_style' => $row['products_style'],
                'products_styledescription' => $row['products_styledescription'],
                'products_sku' => $row['products_sku'],
                'products_color' => $row['products_color'],
                'products_season' => $row['products_season'],
                'products_market' => $row['products_market'],
                'products_order' => $row['products_order'],
                'product_buyer' => $row['product_buyer'],
                'product_claimedfiber' => $row['product_claimedfiber'],
                'products_fibercontentresult' => $row['products_fibercontentresult'],
                'dateprod' => $row['dateprod'],
                'namesupplier' => $row['namesupplier'],
                'agerange' => $row['agerange'],
                'products_billto' => $row['products_billto'],
                'products_billtocde' => $row['products_billtocde'],
                'products_codeanddesc' => $row['products_codeanddesc'],
                'products_division' => $row['products_division'],
                'products_phase' => $row['products_phase'],
                'timestampinsert' => $row['timestampinsert'],
                'products_country' => $row['products_country'],
                'products_region' => $row['products_region'],
                'reports' => array()
            );
        }

        // Controlla se il report è già presente
        if (!isset($reports[$row['idreports']])) {
            $reports[$row['idreports']] = array(
                'reportsNumberLab' => $row['reportsNumberLab'],
                'reportDateIn' => $row['reportDateIn'],
                'reportsDateOut' => $row['reportsDateOut'],
                'reportsDateDue' => $row['reportsDateDue'],
                'reportsRating' => $row['reportsRating'],
                'reportsRating2' => $row['reportsRating2'],
                'pdffilename' => $row['pdffilename'],
                'reports_LabName' => $row['reports_LabName'],
                'reports_testype' => $row['reports_testype'],
                'reports_invoicenumber' => $row['reports_invoicenumber'],
                'reports_invoiceamount' => $row['reports_invoiceamount'],
                'reports_invoiceadate' => $row['reports_invoiceadate'],
                'parts' => array()
            );
        }

        // Controlla se la parte è già presente per il report
        if (!isset($reports[$row['idreports']]['parts'][$row['idParts']])) {
            $reports[$row['idreports']]['parts'][$row['idParts']] = array(
                'partsCode' => $row['partsCode'],
                'partsDescription' => $row['partsDescription'],
                'partsColor' => $row['partsColor'],
                'partsMaterial' => $row['partsMaterial'],
                'analyses' => array()
            );
        }

        // Controlla se l'analisi è già presente per la parte
        if (!isset($reports[$row['idreports']]['parts'][$row['idParts']]['analyses'][$row['idAnalysis_Project']])) {
            $reports[$row['idreports']]['parts'][$row['idParts']]['analyses'][$row['idAnalysis_Project']] = array(
                'result_TestName' => $row['nameanalysisvoc'],  // Nome dell'analisi
                'test_Rating' => $row['test_Rating'],
                'test_Rating2' => $row['test_Rating2'],
                'requirements' => $row['requirements'],
                'reference' => $row['reference'],
                'analysisgroupcode' => $row['analysisgroupcode'],
                'results' => array()
            );
        }

        // Aggiungi i risultati all'analisi
        $result_data = array(
            'result_AnalytsName' => $row['namecompoundsvocabulary'],  // Nome del composto
            'result_AnalytsRating' => $row['result_AnalytsRating'],
            'result_Value' => $row['result_Value'],
            'result_Comment' => $row['result_Comment'],
            'result_Rating' => $row['result_Rating'],
            'result_UnitofMeasure' => $row['result_UnitofMeasure'],
            'cas' => $row['cas'],
            'requirements' => $row['result_requirements'],
            'reference' => $row['result_reference']
        );

        $reports[$row['idreports']]['parts'][$row['idParts']]['analyses'][$row['idAnalysis_Project']]['results'][] = $result_data;
    }

    // Aggiungi i report finali al prodotto
    foreach ($reports as $report) {
        $data['product']['reports'][] = $report;
    }
}

// Converti in JSON
echo json_encode($data, JSON_PRETTY_PRINT);

// Chiudi la connessione
$conn->close();
