<?php 
$gtotal = 0;
$gconverted = 0;
$grate = 0;
?>
<table class="table listTable table-bordered">
    <thead style="position:sticky;top:-1px">
        <tr>
            <th class="text-center">S.N.</th>
            <th class="text-left">Type</th>
            <th class="text-end">Total</th>
            <th class="text-end">Converted</th>
            <th class="text-end">Rate</th>
        </tr>
    </thead>
    <tbody>
        <?php 
            if(!empty($lead_types)) {
                $sn = 1;
                foreach($lead_types as $lead_type) {
                    $total = 0;
                    $converted = 0;
                    $rate = 0.00;
                    if(!empty($lead_data)) {
                        if(!empty($lead_data[$lead_type])) {
                            $total = $lead_data[$lead_type]['Leads'] ?? 0;
                            $converted = $lead_data[$lead_type]['Converted_Leads'] ?? 0;
                        }
                    }
                    $gtotal += $total;
                    $gconverted += $converted;
                    $rate = ($total > 0) ? round(($converted / $total) * 100, 2) : 0.00;
                    $grate += ($gtotal > 0) ? round(($gconverted / $gtotal) * 100, 2) : 0.00;
                    echo "<tr>";
                    echo "<td class='text-center'>" . $sn++ . "</td>";
                    echo "<td class='text-left'>" . htmlspecialchars($lead_type) . "</td>";
                    echo "<td class='text-end'>" . htmlspecialchars($total) . "</td>";
                    echo "<td class='text-end'>" . htmlspecialchars($converted) . "</td>";
                    echo "<td class='text-end'>" . sprintf('%.2f%%', $rate) . "</td>";
                    echo "</tr>";
                }
            } else {
                echo "<tr><td colspan='5'>No data available</td></tr>";
            }
        ?>
    </tbody>
    <?php if(!empty($lead_types)) { ?>
    <tfoot>
        <tr>
            <th colspan="2" class="text-center">Grand Total</th>
            <th class="text-end"><?php echo htmlspecialchars($gtotal); ?></th>
            <th class="text-end"><?php echo htmlspecialchars($gconverted); ?></th>
            <th class="text-end"><?php echo sprintf('%.2f%%', $grate); ?></th>
        </tr>
    </tfoot>
    <?php } ?>
</table>