<?php
// Fetch machines
$sql = "
    SELECT id, resource_code, machine_type
    FROM station_detail_table
    WHERE machine_type IN (1,2,3,4,5)
    ORDER BY machine_type, resource_code
";

$result = $conn->query($sql);

// Machine type labels
$labels = [
    1 => "VAC",
    2 => "ASSEMBLY",
    3 => "CNC",
    4 => "PU",
    5 => "ASSYPU"
];
?>

<style>
    .button-container {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 20px;
    }

    .machine-btn {
        width: 18%;
        min-width: 150px;
        padding: 12px;
        background: #0066cc;
        color: #fff;
        border: none;
        text-align: center;
        font-size: 16px;
        cursor: pointer;
        border-radius: 6px;
        text-decoration: none;
        box-sizing: border-box;
    }

    .machine-btn:hover {
        background: #004d99;
    }

    .section-title {
        font-size: 20px;
        margin-top: 25px;
        margin-bottom: 10px;
        font-weight: bold;
    }
</style>

<h2>Machine List</h2>

<?php
$current_type = null;

if ($result && $result->num_rows > 0) {

    while ($row = $result->fetch_assoc()) {

        // Start a new section when machine type changes
        if ($current_type !== $row['machine_type']) {

            // Close previous section
            if ($current_type !== null) {
                echo "</div>";
            }

            $current_type = $row['machine_type'];
            $sectionTitle = $labels[$current_type] ?? "UNKNOWN";

            echo "<div class='section-title'>{$sectionTitle} Machines</div>";
            echo "<div class='button-container'>";
        }

        $url = $config->frontEndURL .
            "/machine_tab/index.php?l=2&code=" .
            urlencode($row['resource_code']);

        echo '
            <a class="machine-btn" href="' . $url . '">
                ' . htmlspecialchars($row['resource_code']) . '
            </a>
        ';
    }

    // Close the last machine section
    echo "</div>";

} else {
    echo "<p>No machines found.</p>";
}


echo '<div class="section-title">Replica Machines</div>';
echo '<div class="button-container">';

$replicaUrl = $config->frontEndURL .
    "/machine_tab/index.php?l=2&code=" . urlencode("Replica8");

echo '
    <a class="machine-btn" href="' . $replicaUrl . '">
        Replica 8
    </a>
';

echo '</div>';
?>