-- Jam / 50% Full / 100% Full Pie Chart WITH time range support

WITH filtered AS (
    SELECT
        Name,
        Full,
        Half_Full,
        Jam,
        t_stamp,
        ROW_NUMBER() OVER (PARTITION BY Name ORDER BY t_stamp DESC) AS rn
    FROM lane_data
    WHERE t_stamp BETWEEN :startTime AND :endTime
),

latest_records AS (
    SELECT *
    FROM filtered
    WHERE rn = 1
),

totals AS (
    SELECT
        GREATEST(COUNT(*), 22) AS total_lanes,
        SUM(CASE WHEN Jam = 1 THEN 1 ELSE 0 END) AS jammed_count,
        SUM(CASE WHEN Half_Full = 1 THEN 1 ELSE 0 END) AS half_full_count,
        SUM(CASE WHEN Full = 1 THEN 1 ELSE 0 END) AS full_count
    FROM latest_records
)

SELECT
    'Jammed' AS `Status`,
    COALESCE(jammed_count, 0) AS `Count`,
    ROUND(COALESCE(jammed_count, 0) * 100.0 / total_lanes, 2) AS `Percentage (%)`
FROM totals

UNION ALL

SELECT
    '50% Full' AS `Status`,
    COALESCE(half_full_count, 0) AS `Count`,
    ROUND(COALESCE(half_full_count, 0) * 100.0 / total_lanes, 2) AS `Percentage (%)`
FROM totals

UNION ALL

SELECT
    '100% Full' AS `Status`,
    COALESCE(full_count, 0) AS `Count`,
    ROUND(COALESCE(full_count, 0) * 100.0 / total_lanes, 2) AS `Percentage (%)`
FROM totals;
