<?php
require('constants.php');
$db = new SQLite3($DB_FILE);

// Fetch all entries, grouped by group_id
$results = $db->query('SELECT group_id, position, beschreibung, einheit, menge, preis_pro_einheit, gesamtpreis FROM entries ORDER BY group_id');

$current_group = null;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Entries List</title>
    <script>
        // Function to post a message to the parent window
        function sendPostMessage(groupId) {
            const messageData = {
                command: "createRegieleistung",
                data: {
                    regieId: groupId
                }
            };

            window.parent.postMessage(messageData, "*");
        }
    </script>
</head>
<body>
    <h1>Entries List</h1>
    <a href="form.php">Create New Entry</a>
    
    <table border="1" cellpadding="10" cellspacing="0">
        <tr>
            <th>Position</th>
            <th>Beschreibung</th>
            <th>Einheit</th>
            <th>Menge</th>
            <th>Preis pro Einheit</th>
            <th>Gesamtpreis</th>
            <th>Actions</th>
        </tr>

        <?php while ($row = $results->fetchArray()): ?>
            <?php if ($current_group !== $row['group_id']): ?>
                <!-- New group section -->
                <tr>
		    <td colspan="7" style="background-color: #ddd;">
			<div> <strong>Group: <?php echo htmlspecialchars($row['group_id']); ?></strong>
                    	<div><a href="javascript:void(0);" onclick="sendPostMessage('<?php echo $row['group_id']; ?>');">Choose and Back</a></div>
                    </td>
                </tr>
                <?php $current_group = $row['group_id']; ?>
            <?php endif; ?>

            <tr>
                <td><?php echo htmlspecialchars($row['position']); ?></td>
                <td><?php echo htmlspecialchars($row['beschreibung']); ?></td>
                <td><?php echo htmlspecialchars($row['einheit']); ?></td>
                <td><?php echo htmlspecialchars($row['menge']); ?></td>
                <td><?php echo htmlspecialchars($row['preis_pro_einheit']); ?></td>
                <td><?php echo htmlspecialchars($row['gesamtpreis']); ?></td>
                <td>
                    <a href="form.php?id=<?php echo $row['id']; ?>">Edit</a>
                    <a href="delete.php?id=<?php echo $row['id']; ?>" onclick="return confirm('Are you sure?')">Delete</a>
                </td>
            </tr>
        <?php endwhile; ?>
    </table>
</body>
</html>

