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

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

$limit = isset($_GET['limit']) && is_numeric($_GET['limit']) ? intval($_GET['limit']) : 50;
// Query per ottenere i dati delle sostanze
$query = "
SELECT 
    cv.idcompoundsvocabulary AS substance_id,
    cv.namecompoundsvocabulary AS substance_name, 
    COUNT(CASE WHEN rp.result_AnalytsRating IN ('PASS', 'P', 'Complies') THEN 1 END) AS pass_count,
    COUNT(CASE WHEN rp.result_AnalytsRating IN ('FAIL', 'F', 'Doesn\'t Comply') THEN 1 END) AS fail_count
FROM result_project rp
LEFT JOIN analysis_project ap ON rp.idanalysis_project = ap.idAnalysis_Project
LEFT JOIN compundsvocabulary cv ON rp.result_AnalytsName = cv.idcompoundsvocabulary
WHERE cv.preferred = 'Y'
GROUP BY cv.idcompoundsvocabulary, cv.namecompoundsvocabulary
ORDER BY 
    COUNT(CASE WHEN rp.result_AnalytsRating IN ('PASS', 'P', 'Complies') THEN 1 END) +
    COUNT(CASE WHEN rp.result_AnalytsRating IN ('FAIL', 'F', 'Doesn\'t Comply') THEN 1 END) DESC
LIMIT 200;
";


$result = $conn->query($query);

$tableData = []; // Array per la tabella

while ($row = $result->fetch_assoc()) {
    $substances[] = $row['substance_name'];
    $passCounts[] = $row['pass_count'];
    $failCounts[] = $row['fail_count'];
    $substanceIds[] = $row['substance_id']; // Aggiungi l'ID della sostanza

    // Aggiungi dati al $tableData per la tabella
    $tableData[] = [
        'id' => $row['substance_id'],
        'name' => $row['substance_name'],
        'pass_count' => $row['pass_count'],
        'fail_count' => $row['fail_count'],
        'total' => $row['pass_count'] + $row['fail_count']
    ];
}

$queryDetectable = "
SELECT 
    cv.idcompoundsvocabulary AS substance_id,
    cv.namecompoundsvocabulary AS substance_name,
    cv.cascompoundvocabulary AS cas_number,
    COUNT(*) AS total_results,
    COUNT(CASE WHEN rp.result_Value NOT LIKE '<%' THEN 1 END) AS detectable_count,
    ROUND((COUNT(CASE WHEN rp.result_Value NOT LIKE '<%' THEN 1 END) / COUNT(*)) * 100, 2) AS detectable_percentage
FROM result_project rp
LEFT JOIN analysis_project ap ON rp.idanalysis_project = ap.idAnalysis_Project
LEFT JOIN compundsvocabulary cv ON rp.result_AnalytsName = cv.idcompoundsvocabulary
WHERE cv.preferred = 'Y' AND cv.component_type = 'CH'
GROUP BY cv.idcompoundsvocabulary, cv.namecompoundsvocabulary, cv.cascompoundvocabulary
ORDER BY total_results DESC;
";

$resultDetectable = $conn->query($queryDetectable);

$detectableData = []; // Array per la nuova tabella

while ($row = $resultDetectable->fetch_assoc()) {
    $detectableData[] = [
        'id' => $row['substance_id'],
        'name' => $row['substance_name'],
        'cas_number' => $row['cas_number'], // Aggiunge il CAS number
        'total_results' => $row['total_results'],
        'detectable_count' => $row['detectable_count'],
        'detectable_percentage' => $row['detectable_percentage']
    ];
}


?>

<!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">
    <?php include('../include/seo.php'); ?>

    <link rel="shortcut icon" href="../assets/images/favicon.ico">

    <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">
    <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css" rel="stylesheet">
    <script src="../assets/js/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
</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">
                                    <div class="btn-group float-right">
                                        <ol class="breadcrumb hide-phone p-0 m-0">
                                            <li class="breadcrumb-item"><a href="#">Reportify</a></li>
                                            <li class="breadcrumb-item active">Substance Statistics</li>
                                        </ol>
                                    </div>
                                    <h4 class="page-title">Substance Statistics</h4>
                                </div>
                            </div>
                        </div>
                        <form method="GET" action="">
                            <label for="limit">Show:</label>
                            <select id="limit" name="limit" onchange="this.form.submit()">
                                <option value="10" <?php echo isset($_GET['limit']) && $_GET['limit'] == 10 ? 'selected' : ''; ?>>10</option>
                                <option value="50" <?php echo isset($_GET['limit']) && $_GET['limit'] == 50 ? 'selected' : ''; ?>>50</option>
                                <option value="100" <?php echo isset($_GET['limit']) && $_GET['limit'] == 100 ? 'selected' : ''; ?>>100</option>
                                <option value="200" <?php echo isset($_GET['limit']) && $_GET['limit'] == 200 ? 'selected' : ''; ?>>200</option>
                                <option value="500" <?php echo isset($_GET['limit']) && $_GET['limit'] == 500 ? 'selected' : ''; ?>>500</option>
                            </select>
                            records
                        </form>

                        <!-- Grafico delle sostanze -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="card-title">Substances by Rating</h5>
                                        <div id="substance-chart"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Tabella delle sostanze -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="card-title">Substances Data</h5>
                                        <table id="substances-table" class="display nowrap" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>Substance Name</th>
                                                    <th>Pass Count</th>
                                                    <th>Fail Count</th>
                                                    <th>Total</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($tableData as $data) : ?>
                                                    <tr>
                                                        <td>
                                                            <a href="substance-detail.php?id=<?php echo $data['id']; ?>" style="text-decoration:none;color:#007bff;">
                                                                <?php echo htmlspecialchars($data['name']); ?>
                                                            </a>
                                                        </td>
                                                        <td><?php echo $data['pass_count']; ?></td>
                                                        <td><?php echo $data['fail_count']; ?></td>
                                                        <td><?php echo $data['total']; ?></td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>

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

                        <!-- Tabella dei risultati totali e dei valori detectable -->
                        <!-- Tabella dei risultati totali e dei valori detectable -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="card-title">Chemical Substance Result Summary</h5>
                                        <table id="detectable-table" class="display nowrap" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>Substance Name</th>
                                                    <th>CAS Number</th>
                                                    <th>Total Results</th>
                                                    <th>Detectable Count</th>
                                                    <th>Detectable %</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($detectableData as $data) : ?>
                                                    <tr>
                                                        <td>
                                                            <a href="substance-detail.php?id=<?php echo $data['id']; ?>" style="text-decoration:none;color:#007bff;">
                                                                <?php echo htmlspecialchars($data['name']); ?>
                                                            </a>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($data['cas_number']); ?></td>
                                                        <td><?php echo $data['total_results']; ?></td>
                                                        <td><?php echo $data['detectable_count']; ?></td>
                                                        <td><?php echo $data['detectable_percentage']; ?>%</td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>





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

            <?php include('../include/footer.php'); ?>
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            // Recupera il numero di categorie (sostanze)
            const numberOfCategories = <?php echo count($substances); ?>;

            // Calcola dinamicamente l'altezza del grafico
            const chartHeight = Math.min(Math.max(numberOfCategories * 40, 400), 5000);
            // 40px per categoria, altezza minima 400px, altezza massima 5000px

            const options = {
                series: [{
                        name: 'PASS',
                        data: <?php echo json_encode($passCounts); ?>
                    },
                    {
                        name: 'FAIL',
                        data: <?php echo json_encode($failCounts); ?>
                    }
                ],
                chart: {
                    type: 'bar',
                    height: chartHeight, // Altezza dinamica basata sul numero di categorie
                    stacked: true,
                    horizontal: true
                },
                plotOptions: {
                    bar: {
                        horizontal: true,
                        barHeight: '80%' // Barre più alte
                    }
                },
                xaxis: {
                    categories: <?php echo json_encode($substances); ?>,
                    labels: {
                        style: {
                            fontSize: '12px',
                            fontWeight: 'normal'
                        }
                    },
                    title: {
                        text: 'Number of Ratings',
                        style: {
                            fontSize: '16px',
                            fontWeight: 'bold'
                        }
                    }
                },
                yaxis: {
                    labels: {
                        style: {
                            fontSize: '12px',
                            fontWeight: 'normal',
                            lineHeight: '2.0'
                        },
                        maxWidth: 400 // Larghezza massima per i nomi delle sostanze
                    },
                    title: {
                        text: 'Substances',
                        style: {
                            fontSize: '16px',
                            fontWeight: 'bold'
                        }
                    }
                },
                colors: ['#28a745', '#dc3545'], // Colori delle barre
                title: {
                    text: 'Substances by Rating',
                    align: 'center',
                    style: {
                        fontSize: '20px',
                        fontWeight: 'bold'
                    }
                },
                legend: {
                    position: 'bottom',
                    labels: {
                        style: {
                            fontSize: '14px',
                            fontWeight: 'normal'
                        }
                    }
                }
            };

            const chart = new ApexCharts(document.querySelector("#substance-chart"), options);
            chart.render();


            // DataTables initialization
            $('#substances-table').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    'copy', 'csv', 'excel', 'pdf', 'print'
                ],
                order: [
                    [3, 'desc']
                ], // Ordina per colonna totale
                pageLength: 50
            });
        });
    </script>
    <script>
        $(document).ready(function() {
            $('#detectable-table').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    'copy', 'csv', 'excel', 'pdf', 'print'
                ],
                order: [
                    [2, 'desc']
                ], // Ordina per numero totale di risultati
                pageLength: 50
            });
        });
    </script>
</body>

</html>