WITH filtered AS (
    SELECT
        Name,
        Disabled,
        Full,
        Half_Full,
        Jam,
        No_Container,
        Block_Operation,
        t_stamp
    FROM lane_data
    WHERE Name LIKE 'S01%'
),

latest AS (
    SELECT f.*
    FROM filtered f
    INNER JOIN (
        SELECT Name, MAX(t_stamp) AS max_ts
        FROM filtered
        GROUP BY Name
    ) x ON f.Name = x.Name AND f.t_stamp = x.max_ts
),

classified AS (
    SELECT
        CASE
            WHEN Disabled = 1 THEN 'Disabled'
            WHEN Jam = 1 THEN 'Jammed'
            WHEN Block_Operation = 1 THEN 'Blocked by Operation'
            WHEN Full = 1 THEN '100% Full'
            WHEN Half_Full = 1 THEN '50% Full'
            WHEN No_Container = 1 THEN 'No Container'
            ELSE 'Enabled'
        END AS category
    FROM latest
),

totals AS (
    SELECT COUNT(*) AS total_lanes FROM classified
),

all_categories AS (
    SELECT 'Enabled'              AS category UNION ALL
    SELECT 'Disabled'             AS category UNION ALL
    SELECT 'Jammed'               AS category UNION ALL
    SELECT '100% Full'            AS category UNION ALL
    SELECT '50% Full'             AS category UNION ALL
    SELECT 'No Container'         AS category UNION ALL
    SELECT 'Blocked by Operation' AS category
),

agg AS (
    SELECT category, COUNT(*) AS cnt
    FROM classified
    GROUP BY category
)

SELECT
    ac.category AS `Status`,
    COALESCE(a.cnt, 0) AS `Count`,
    CONCAT(
        ROUND(
            COALESCE(a.cnt, 0) * 100.0 / (SELECT total_lanes FROM totals), 1
        ),
        '%'
    ) AS `Percentage (%)`
FROM all_categories ac
LEFT JOIN agg a ON ac.category = a.category
ORDER BY FIELD(
    ac.category,
    'Enabled','Disabled','Jammed','100% Full','50% Full','No Container','Blocked by Operation'
);
