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

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

// Recupera il valore di idreports dalla query string
$idreports = isset($_GET['idreports']) ? $_GET['idreports'] : 0;

// Query per ottenere i dettagli del report e del prodotto associato
$queryReportDetails = "
    SELECT r.*, p.products_refnumber, p.products_description, p.products_style, p.products_color
    FROM reports r
    LEFT JOIN products p ON r.idproducts = p.idproducts
    WHERE r.idreports = ?";
$stmt = $conn->prepare($queryReportDetails);
$stmt->bind_param("i", $idreports);
$stmt->execute();
$reportDetails = $stmt->get_result()->fetch_assoc();

// Query per ottenere le parti e i risultati del report con il nome dell'analista e delle parti
$queryPartsAndResults = "
SELECT 
    rp.*, 
    a.nameanalysisvoc AS testName, 
    cv.namecompoundsvocabulary AS analytsName, 
    pr.partsDescription,
    pr.partsCode,
    rp.result_UnitofMeasure, 
    rp.result_AnalytsRating AS analytsRating,  -- Renamed the field for clarity
    ap.test_Rating AS analysisRating          -- Rating from analysis_project
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
LEFT JOIN compundsvocabulary cv ON rp.result_AnalytsName = cv.idcompoundsvocabulary
LEFT JOIN parts pr ON rp.idPart = pr.idParts
WHERE rp.idreports = ?
ORDER BY ap.result_TestName, rp.idPart;

";


$stmtParts = $conn->prepare($queryPartsAndResults);
$stmtParts->bind_param("i", $idreports);
$stmtParts->execute();
$partsAndResults = $stmtParts->get_result();

// Query per ottenere i file associati al report
$queryFiles = "
    SELECT original_filename, stored_filename, file_comment, filepath
    FROM report_files
    WHERE uuid = ?
    AND (file_comment = 'report' OR file_comment = 'main_product_image')";
$stmtFiles = $conn->prepare($queryFiles);
$stmtFiles->bind_param("s", $reportDetails['importcode']);
$stmtFiles->execute();
$filesResult = $stmtFiles->get_result();

$files = [];
while ($fileRow = $filesResult->fetch_assoc()) {
    $files[$fileRow['file_comment']] = $fileRow;
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title>Report Details</title>

    <!-- Altri riferimenti al CSS e JS -->
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="../assets/css/icons.css" rel="stylesheet" type="text/css">
    <link href="../assets/css/style.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">
    <script src="../assets/js/jquery.min.js"></script>
    <link rel="stylesheet" href="../assets/plugins/select2/select2.min.css">
    <script src="../assets/plugins/select2/select2.min.js"></script>
    <style>
        .section-separator {
            background-color: #f1f3f5;
            font-weight: bold;
            padding: 10px;
            margin-top: 20px;
            border-top: 3px solid #6c757d;
        }

        .table-part {
            margin-top: 10px;
            border: 2px solid #dee2e6;
        }

        .rating-pass {
            background-color: #28a745;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.9rem;
        }

        .rating-fail {
            background-color: #dc3545;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.9rem;
        }

        .rating-ambiguous {
            background-color: #ffc107;
            color: black;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.9rem;
        }

        .report-header {
            background-color: #e9ecef;
            padding: 15px;
            border-radius: 5px;
        }

        .report-header h5 {
            margin-bottom: 10px;
        }

        .report-details-table {
            width: 100%;
        }

        .report-details-table td {
            padding: 5px;
        }

        .table-filter {
            margin-bottom: 20px;
        }

        .fixed-width-analyts {
            width: 40%;
            /* Modifica questo valore per adattare la larghezza */
        }

        .fixed-width-value {
            width: 30%;
            /* Modifica questo valore per adattare la larghezza */
        }

        .fixed-width-rating {
            width: 30%;
            /* Modifica questo valore per adattare la larghezza */
        }
    </style>
</head>

<body class="fixed-left">

    <div id="wrapper">
        <?php include('../include/navigationbar.php'); ?>
        <div class="content-page">
            <div class="content">
                <?php include('../include/topbar.php'); ?>
                <div class="page-content-wrapper">
                    <div class="container-fluid">

                        <div class="row">
                            <div class="col-sm-12">
                                <div class="page-title-box">
                                    <h4 class="page-title">Report Details</h4>
                                </div>
                            </div>
                        </div>

                        <!-- Dati del Report e del Prodotto -->
                        <div class="row">
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="report-header">
                                            <h5>Report: <?php echo $reportDetails['reportsNumberLab']; ?></h5>
                                            <table class="report-details-table">
                                                <tr>
                                                    <td><strong>Report Date:</strong></td>
                                                    <td><?php echo $reportDetails['reportDateIn']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Product Ref:</strong></td>
                                                    <td><?php echo $reportDetails['products_refnumber']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Product Description:</strong></td>
                                                    <td><?php echo $reportDetails['products_description']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Style:</strong></td>
                                                    <td><?php echo $reportDetails['products_style']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Color:</strong></td>
                                                    <td><?php echo $reportDetails['products_color']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>PDF Report:</strong></td>
                                                    <td>
                                                        <?php if (isset($files['report'])): ?>
                                                            <a href="<?php echo htmlspecialchars('../report_files/' . $files['report']['stored_filename']); ?>" target="_blank">
                                                                <i class="bx bxs-file-pdf" style="font-size: 24px; color: #d9534f;"></i> View Report
                                                            </a>
                                                        <?php else: ?>
                                                            <span>No PDF available</span>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Product Image:</strong></td>
                                                    <td>
                                                        <?php if (isset($files['main_product_image'])): ?>
                                                            <a href="<?php echo htmlspecialchars('../report_files/' . $files['main_product_image']['stored_filename']); ?>"
                                                                target="_blank" onclick="openModal(event, this); return false;">
                                                                <img src="<?php echo htmlspecialchars('../report_files/' . $files['main_product_image']['stored_filename']); ?>"
                                                                    alt="Product Image" style="max-width: 150px; max-height: 150px;">
                                                            </a>
                                                        <?php else: ?>
                                                            <span>No image available</span>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>

                                                <!-- Modal container for enlarged image -->

                                                <div id="imageModal" style="display:none; position:fixed; z-index:1000; left:0; top:0; width:100%; height:100%; background-color:rgba(0, 0, 0, 0.8); justify-content:center; align-items:center;" onclick="closeModal(event)">
                                                    <img id="modalImage" style="max-width:90%; max-height:90%;">
                                                </div>



                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <script>
                            function openModal(event, link) {
                                event.preventDefault();
                                var modal = document.getElementById('imageModal');
                                var modalImage = document.getElementById('modalImage');
                                modalImage.src = link.href;
                                modal.style.display = 'flex';
                            }

                            function closeModal(event) {
                                var modal = document.getElementById('imageModal');
                                // Chiudi il modal solo se il clic è al di fuori dell'immagine
                                if (event.target.id === 'imageModal') {
                                    modal.style.display = 'none';
                                }
                            }
                        </script>

                        <?php
                        // Query per ottenere i file aggiuntivi non etichettati come 'report' o 'main_product_image'
                        $queryAdditionalFiles = "SELECT * FROM report_files WHERE uuid = ? AND file_comment NOT IN ('report', 'main_product_image')";
                        $stmtAdditionalFiles = $conn->prepare($queryAdditionalFiles);
                        $stmtAdditionalFiles->bind_param("s", $reportDetails['importcode']);
                        $stmtAdditionalFiles->execute();
                        $additionalFiles = $stmtAdditionalFiles->get_result();
                        ?>

                        <?php if ($additionalFiles->num_rows > 0): ?>
                            <div class="card mt-4">
                                <div class="card-body">
                                    <h5 class="header-title pb-3 mt-0">Additional Files</h5>
                                    <!-- Button to toggle collapsible area -->
                                    <button class="btn btn-primary mb-3" type="button" data-toggle="collapse" data-target="#additionalFilesSection">
                                        Show/Hide Additional Files
                                    </button>
                                    <!-- Collapsible area for additional files -->
                                    <div id="additionalFilesSection" class="collapse">
                                        <table class="table table-bordered">
                                            <thead class="thead-light">
                                                <tr>
                                                    <th>File Preview</th>
                                                    <th>Comment</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($file = $additionalFiles->fetch_assoc()): ?>
                                                    <?php
                                                    $filePath = "../report_files/" . $file['stored_filename'];
                                                    $isImage = preg_match('/\.(jpg|jpeg|png|gif)$/i', $file['stored_filename']);
                                                    $isPDF = preg_match('/\.pdf$/i', $file['stored_filename']);
                                                    ?>
                                                    <tr>
                                                        <td>
                                                            <?php if ($isImage): ?>
                                                                <!-- Thumbnail with click to enlarge -->
                                                                <a href="<?php echo htmlspecialchars($filePath); ?>" onclick="openModal(event, this)">
                                                                    <img src="<?php echo htmlspecialchars($filePath); ?>" alt="Additional File" style="width:50px; height:auto;">
                                                                </a>
                                                            <?php elseif ($isPDF): ?>
                                                                <!-- PDF icon with link -->
                                                                <a href="<?php echo htmlspecialchars($filePath); ?>" target="_blank">
                                                                    <i class="fas fa-file-pdf" style="font-size: 24px; color: #d9534f;"></i>
                                                                </a>
                                                            <?php else: ?>
                                                                <!-- Generic file icon with link -->
                                                                <a href="<?php echo htmlspecialchars($filePath); ?>" target="_blank">
                                                                    <i class="fas fa-file-alt" style="font-size: 24px; color: #5a5a5a;"></i>
                                                                </a>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($file['file_comment'], ENT_QUOTES, 'UTF-8'); ?></td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>



                        <!-- Filtri -->
                        <!-- Aggiungi questo filtro sopra la tabella -->
                        <div class="row table-filter">
                            <div class="col-md-4">
                                <input type="text" id="searchTestName" class="form-control" placeholder="Search by Test Name">
                            </div>
                            <div class="col-md-4">
                                <input type="text" id="searchPart" class="form-control" placeholder="Search by Part">
                            </div>
                            <div class="col-md-4">
                                <select id="searchRating" class="form-control">
                                    <option value="">All Ratings</option>
                                    <option value="pass" class="rating-pass">Pass</option>
                                    <option value="fail" class="rating-fail">Fail</option>
                                    <option value="ambiguous" class="rating-ambiguous">N/A or Ambiguous</option>
                                </select>
                            </div>
                        </div>


                        <!-- Tabella con Parti e Risultati -->
                        <div class="row">
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="header-title pb-3 mt-0">Parts and Results</h5>
                                        <div class="table-responsive">
                                            <?php
                                            $currentTestName = '';  // Variabile per tracciare l'analisi corrente
                                            $currentPart = '';      // Variabile per tracciare la parte corrente

                                            while ($row = $partsAndResults->fetch_assoc()) {
                                                //print_r($row);
                                                // Se il nome dell'analisi cambia, crea una nuova sezione per l'analisi
                                                if ($currentTestName != $row['testName']) {
                                                    if ($currentTestName != '') {
                                                        echo '</tbody></table>'; // Chiude la tabella precedente se esiste
                                                    }

                                                    // Stampa il titolo dell'analisi
                                                    $currentTestName = $row['testName'];
                                                    $currentTestRating = $row['analysisRating'];

                                                    $testRatingClass = '';
                                                    if (strtolower($currentTestRating) === 'pass' || strtolower($currentTestRating) === 'complies' || strtolower($currentTestRating) === 'p') {
                                                        $testRatingClass = 'rating-pass';
                                                    } elseif (strtolower($currentTestRating) === 'fail' || strtolower($currentTestRating) === "doesn't comply" || strtolower($currentTestRating) === 'f') {
                                                        $testRatingClass = 'rating-fail';
                                                    } else {
                                                        $testRatingClass = 'rating-ambiguous';
                                                    }

                                                    echo '<div class="section-separator">Analysis: ' . $currentTestName . ' <span class="badge ' . $testRatingClass . '">' . htmlspecialchars($currentTestRating, ENT_QUOTES, 'UTF-8') . '</span></div>';

                                                    // Reset della parte corrente
                                                    $currentPart = '';
                                                }

                                                // Se la parte cambia, crea una nuova sezione per la parte
                                                if ($currentPart != $row['partsDescription']) {
                                                    if ($currentPart != '') {
                                                        echo '</tbody></table>'; // Chiude la tabella della parte precedente
                                                    }

                                                    // Stampa il titolo della parte
                                                    $currentPart = $row['partsDescription'] ?? 'Unknown Part';
                                                    echo '<h6>Part: ' . (!empty($row['partsDescription']) ? $currentPart : 'Part Not Specified') . '</h6>';

                                                    // Apri una nuova tabella per la parte
                                                    echo '<table class="table table-bordered table-part">
                    <thead>
                        <tr>
                            <th class="fixed-width-analyts">Components/Analyts Name</th>
                            <th class="fixed-width-value">Result Value</th>
                            <th class="fixed-width-rating">Rating</th>
                        </tr>
                    </thead>
                    <tbody>';
                                                }

                                                // Classificazione del rating
                                                $ratingClass = '';
                                                if (strtoupper($row['analytsRating']) == 'FAIL' || strtoupper($row['analytsRating']) == "DOESN'T COMPLY" || strtoupper($row['analytsRating']) == "F") {
                                                    $ratingClass = 'rating-fail';
                                                } elseif (strtoupper($row['analytsRating']) == 'PASS' || strtoupper($row['analytsRating']) == 'COMPLIES' || strtoupper($row['analytsRating']) == 'P') {
                                                    $ratingClass = 'rating-pass';
                                                } else {
                                                    $ratingClass = 'rating-ambiguous';
                                                }

                                                // Stampa i dettagli dell'analita
                                                echo '<tr>';
                                                echo '<td>' . (!empty($row['analytsName']) ? $row['analytsName'] . ' (CAS: ' . $row['cas'] . ')' : '&nbsp;') . '</td>';
                                                echo '<td>' . (!empty($row['result_Value']) ? htmlspecialchars($row['result_Value'], ENT_QUOTES, 'UTF-8') : '&nbsp;');

                                                // Aggiungi l'unità di misura se presente
                                                if (!empty($row['result_UnitofMeasure'])) {
                                                    echo ' ' . htmlspecialchars($row['result_UnitofMeasure'], ENT_QUOTES, 'UTF-8'); // Aggiunge l'unità di misura accanto al valore
                                                }

                                                echo '</td>';
                                                echo '<td class="' . $ratingClass . '">' . (!empty($row['analytsRating']) ? htmlspecialchars($row['analytsRating'], ENT_QUOTES, 'UTF-8') : '&nbsp;') . '</td>';
                                                echo '</tr>';
                                            }

                                            // Chiude l'ultima tabella se esiste
                                            if ($currentTestName != '') {
                                                echo '</tbody></table>';
                                            }
                                            ?>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>

                    </div><!-- container -->
                </div><!-- Page content Wrapper -->
            </div><!-- content -->
            <?php include('../include/footer.php'); ?>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            // Filtro per Test Name
            $('#searchTestName').on('keyup', function() {
                var value = $(this).val().toLowerCase();
                $('.section-separator').each(function() {
                    var section = $(this);
                    if (section.text().toLowerCase().includes(value)) {
                        section.show();
                        section.nextUntil('.section-separator').show();
                    } else {
                        section.hide();
                        section.nextUntil('.section-separator').hide();
                    }
                });
            });

            // Filtro per Part Name
            $('#searchPart').on('keyup', function() {
                var value = $(this).val().toLowerCase();

                // Filtra le parti
                $('h6').each(function() {
                    var part = $(this);
                    var partTable = part.next('table');

                    if (part.text().toLowerCase().includes(value)) {
                        part.show();
                        partTable.show();
                    } else {
                        part.hide();
                        partTable.hide();
                    }
                });

                // Dopo aver filtrato le parti, verifica se l'analisi ha parti visibili
                $('.section-separator').each(function() {
                    var analysisTitle = $(this); // Il titolo dell'analisi
                    var hasVisibleParts = analysisTitle.nextUntil('.section-separator', 'h6:visible').length > 0; // Verifica se ci sono parti visibili

                    if (!hasVisibleParts) {
                        analysisTitle.hide(); // Nasconde l'intestazione dell'analisi se nessuna parte è visibile
                    } else {
                        analysisTitle.show(); // Mostra l'intestazione dell'analisi se almeno una parte è visibile
                    }
                });
            });


            // Filtro per Rating
            $('#searchRating').on('change', function() {
                var selectedRating = $(this).val().toLowerCase(); // Prende il rating selezionato

                $('table.table-part').each(function() {
                    var table = $(this);
                    var visibleRows = 0;

                    // Controlla ogni riga della tabella
                    table.find('tbody tr').each(function() {
                        var ratingCell = $(this).find('td:last-child'); // L'ultima cella è quella del rating
                        var ratingText = ratingCell.text().trim().toLowerCase();

                        // Mostra/nasconde la riga in base al filtro di rating
                        if (selectedRating === '' ||
                            (selectedRating === 'pass' && (ratingText === 'pass' || ratingText === 'complies' || ratingText === 'p')) ||
                            (selectedRating === 'fail' && (ratingText === 'fail' || ratingText === "doesn't comply" || ratingText === "f")) ||
                            (selectedRating === 'ambiguous' && (ratingText === 'n/a' || ratingText === 'data' || ratingText === '//' || ratingText === ''))) {
                            $(this).show();
                            visibleRows++;
                        } else {
                            $(this).hide();
                        }
                    });

                    // Nascondi l'intera tabella e il titolo della parte se non ci sono righe visibili
                    if (visibleRows === 0) {
                        table.hide(); // Nasconde la tabella
                        table.prev('h6').hide(); // Nasconde il titolo della parte
                        table.prevAll('.section-separator:first').hide(); // Nasconde il titolo dell'analisi
                    } else {
                        table.show(); // Mostra la tabella se ci sono righe visibili
                        table.prev('h6').show(); // Mostra il titolo della parte
                        table.prevAll('.section-separator:first').show(); // Mostra il titolo dell'analisi
                    }
                });

                // Controlla se ci sono sezioni dell'analisi senza parti visibili
                $('.section-separator').each(function() {
                    var section = $(this);
                    var hasVisibleParts = section.nextUntil('.section-separator', 'h6:visible').length > 0; // Verifica se ci sono parti visibili

                    if (!hasVisibleParts) {
                        section.hide(); // Nasconde l'intestazione dell'analisi se non ci sono parti visibili
                    } else {
                        section.show(); // Mostra l'intestazione dell'analisi se ci sono parti visibili
                    }
                });
            });
        });
    </script>
    <!-- plugin JS  -->
    <script src="../assets/js/popper.min.js"></script>
    <script src="../assets/js/bootstrap.min.js"></script>
    <script src="../assets/js/modernizr.min.js"></script>
    <script src="../assets/js/detect.js"></script>
    <script src="../assets/js/fastclick.js"></script>
    <script src="../assets/js/jquery.slimscroll.js"></script>
    <script src="../assets/js/jquery.blockUI.js"></script>
    <script src="../assets/js/waves.js"></script>
    <script src="../assets/js/jquery.nicescroll.js"></script>
    <script src="../assets/js/jquery.scrollTo.min.js"></script>
    <script src="../assets/js/common_helper.js"></script>

    <script src="../assets/plugins/chart.js/chart.min.js"></script>
    <script src="../assets/pages/dashboard.js"></script>

    <!-- App js -->
    <script src="../assets/js/app.js"></script>
    <script src="../assets/plugins/alertify/js/alertify.js"></script>

    <script>
        $(document).ready(function() {
            // Filtro per Test Name
            $('#searchTestName').on('keyup', function() {
                var value = $(this).val().toLowerCase();
                $('.section-separator').each(function() {
                    var section = $(this);
                    if (section.text().toLowerCase().includes(value)) {
                        section.show();
                        section.nextUntil('.section-separator').show();
                    } else {
                        section.hide();
                        section.nextUntil('.section-separator').hide();
                    }
                });
            });

            // Filtro per Part Name
            $('#searchPart').on('keyup', function() {
                var value = $(this).val().toLowerCase();
                $('h6').each(function() {
                    var part = $(this);
                    if (part.text().toLowerCase().includes(value)) {
                        part.show();
                        part.next('table').show();
                    } else {
                        part.hide();
                        part.next('table').hide();
                    }
                });
            });

            // Filtro per Rating
            $('#searchRating').on('change', function() {
                var selectedRating = $(this).val().toLowerCase(); // Prende il rating selezionato
                $('table.table-part tbody tr').each(function() {
                    var ratingCell = $(this).find('td:last-child'); // L'ultima cella dovrebbe essere quella del rating
                    var ratingText = ratingCell.text().trim().toLowerCase();

                    // Se l'utente non seleziona alcun valore (tutti i rating) o il rating corrisponde
                    if (selectedRating === '' ||
                        (selectedRating === 'pass' && (ratingText === 'pass' || ratingText === 'complies' || ratingText === 'p')) ||
                        (selectedRating === 'fail' && (ratingText === 'fail' || ratingText === "doesn't comply" || ratingText === "f")) ||
                        (selectedRating === 'ambiguous' && (ratingText === 'n/a' || ratingText === 'data' || ratingText === '//' || ratingText === ''))) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });
        });
    </script>

</body>

</html>