<?php

session_start();

if (empty($_SESSION['excel_report'])) {
    die('No data to export');
}

$grouped = $_SESSION['excel_report'];

$maxFollowups = 0;
foreach ($grouped as $row) {
    $count = count($row['followups']);
    if ($count > $maxFollowups) {
        $maxFollowups = $count;
    }
}

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=followup_report.xls");

echo "<table border='1'>";

echo "<tr>
        <th>Customer Name</th>
        <th>Mobile No</th>
        <th>Vehicle</th>
        <th>Chassis No</th>";

for ($i = 1; $i <= $maxFollowups; $i++) {
    echo "<th>Followup Date {$i}</th>";
    echo "<th>Service Type {$i}</th>";
    echo "<th>Remark {$i}</th>";
	echo "<th>Detail {$i}</th>";
}

echo "</tr>";


foreach ($grouped as $data) {

    echo "<tr>";
    echo "<td>{$data['customer_name']}</td>";
    echo "<td>{$data['mobile_no']}</td>";
    echo "<td>{$data['registration_no']}</td>";
    echo "<td>{$data['chassis_no']}</td>";

    for ($i = 0; $i < $maxFollowups; $i++) {

        if (isset($data['followups'][$i])) {
            echo "<td>{$data['followups'][$i]['date']}</td>";
            echo "<td>{$data['followups'][$i]['service_type']}</td>";
            echo "<td>{$data['followups'][$i]['remark']}</td>";
			echo "<td>{$data['followups'][$i]['call_detail']}</td>";
        } else {
            echo "<td></td><td></td><td></td>";
        }
    }

    echo "</tr>";
}

echo "</table>";

