<?php
include "./connection.php";

// Fetch list of courts for the dropdown
$courtListQuery = "SELECT ID, court_name FROM district_courts";
$courtListResult = $conn->query($courtListQuery);
$courts = array();
while ($court = $courtListResult->fetch_assoc()) {
    $courts[] = $court; // Populate court list
}

// Initialize variables for chart data
$dataPoints = array();
$courtName = "All Courts"; // Default to "All Courts" view

// Check if a specific court is selected
if (isset($_GET['court_id']) && $_GET['court_id'] !== "all") {
    $courtId = $_GET['court_id'];

    // Query to get data for the selected court
    $sql = "
        SELECT 
            c.court_name, 
            SUM(p.institution) AS TotalInstitution, 
            SUM(p.disposed) AS TotalDisposed, 
            SUM(p.transfer_out) AS TotalTransferOut, 
            SUM(p.pending) AS TotalPending
        FROM tbl_performance p
        JOIN district_courts c ON p.court_id = c.ID
        WHERE c.ID = $courtId
        GROUP BY c.ID
    ";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $courtName = $row['court_name']; // Set the court name
        $dataPoints[] = array("label" => "Institution", "y" => $row['TotalInstitution']);
        $dataPoints[] = array("label" => "Disposed", "y" => $row['TotalDisposed']);
        $dataPoints[] = array("label" => "Transfer Out", "y" => $row['TotalTransferOut']);
        $dataPoints[] = array("label" => "Pending", "y" => $row['TotalPending']);
    } else {
        $dataPoints = array(
            array("label" => "No Data Available", "y" => 0)
        );
    }
} else {
    // Query to get aggregated totals for all courts
    $sql = "
        SELECT 
            'All Courts' AS court_name, 
            SUM(p.institution) AS TotalInstitution, 
            SUM(p.disposed) AS TotalDisposed, 
            SUM(p.transfer_out) AS TotalTransferOut, 
            SUM(p.pending) AS TotalPending
        FROM tbl_performance p
    ";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $dataPoints[] = array("label" => "Institution", "y" => $row['TotalInstitution']);
        $dataPoints[] = array("label" => "Disposed", "y" => $row['TotalDisposed']);
        $dataPoints[] = array("label" => "Transfer Out", "y" => $row['TotalTransferOut']);
        $dataPoints[] = array("label" => "Pending", "y" => $row['TotalPending']);
    }
}
?>
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function updateChart() {
    // Update the page with the selected court
    const courtId = document.getElementById("courtSelector").value;
    window.location.href = `?court_id=${courtId}`;
}

window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer", {
        animationEnabled: true,
        exportEnabled: true,
        title:{
            text: "<?php echo $courtName; ?> - Performance"
        },
        subtitles: [{
            text: "Institution, Disposed, Transfer Out, and Pending"
        }],
        data: [{
            type: "pie",
            showInLegend: false,
            indexLabelFontSize: 16,
            indexLabel: "{label}: {y}",
            yValueFormatString: "##0",
            dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
        }]
    });
    chart.render();
}
</script>
</head>
<body>
<div style="text-align: center; margin: 20px;">
    <label for="courtSelector">Choose Court:</label>
    <select id="courtSelector" onchange="updateChart()">
        <option value="all">All Courts</option>
        <?php foreach ($courts as $court) { ?>
            <option value="<?php echo $court['ID']; ?>" <?php if (isset($_GET['court_id']) && $_GET['court_id'] == $court['ID']) echo "selected"; ?>>
                <?php echo $court['court_name']; ?>
            </option>
        <?php } ?>
    </select>
</div>
<div id="chartContainer" style="height: 400px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
