<?php
require('constants.php');

// Disable caching
header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

// Connect to SQLite
$db = new SQLite3($DB_FILE);

// Get the `group_ids` from the GET request (comma-separated)
if (isset($_GET['group_ids'])) {
    $group_ids = explode(',', $_GET['group_ids']); // Split the comma-separated list into an array

    // Sanitize each group_id (trim whitespaces and remove empty entries)
    $group_ids = array_filter(array_map('trim', $group_ids));

    // Prepare placeholders for the SQL query
    $placeholders = implode(',', array_fill(0, count($group_ids), '?'));

    // Prepare the SQL query to fetch entries for all specified group_ids
    $stmt = $db->prepare("SELECT group_id, position, beschreibung, einheit, menge, preis_pro_einheit 
                          FROM entries WHERE group_id IN ($placeholders)
                          ORDER BY group_id, position");
    
    // Bind each group_id to the placeholders
    foreach ($group_ids as $index => $group_id) {
        $stmt->bindValue($index + 1, $group_id, SQLITE3_TEXT);
    }

    $result = $stmt->execute();
    
    $tables = [];  // This will now act as the map 'group_id' => 'table'
    
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $group_id = $row['group_id'];
    
        // If this group_id doesn't have a table yet, initialize it
        if (!isset($tables[$group_id])) {
            $tables[$group_id] = [["Position", "Bezeichnung", "Einheit", "Menge", "Preis"]];
        }
    
        // Prepare each row in the format required
        $position = str_pad($row['position'], 4, '0', STR_PAD_LEFT); // Format position to 4 digits
        $beschreibung = $row['beschreibung'];
        $einheit = $row['einheit'];
        $menge = number_format($row['menge'], 0, '', ''); // Format Menge as an integer
        $preis = number_format($row['preis_pro_einheit'], 3, ',', '.') . '€'; // Format Preis with 3 decimals and currency symbol
    
        // Add this row to the table for the current group_id
        $tables[$group_id][] = [$position, $beschreibung, $einheit, $menge, $preis];
    }

    // If the 'fake' parameter is set, add dummy entries for each group
    if (isset($_GET['fake'])) {
        foreach ($group_ids as $group_id) {
            // If the group_id doesn't have any real data, initialize it
            if (!isset($tables[$group_id])) {
                $tables[$group_id] = [["Position", "Bezeichnung", "Einheit", "Menge", "Preis"]];
            }

            // Append two dummy entries for each group_id
            $tables[$group_id][] = ['0001', 'Dummy Entry 1', 'Stück', '10', '5,000€'];
            $tables[$group_id][] = ['0002', 'Dummy Entry 2', 'Stück', '20', '10,000€'];
        }
    }

    $tabledata = [];
    foreach ($tables as $id => $table) {
	    array_push($tabledata, [
		    'id' => $id,
		    'table' => $table
	    ]);
    }

    // Add the last group to the tables array
        $resjson = [
            'tables' => $tabledata,
            'preText' => "sometext for $current_group_id",
            'postText' => "anotherText for $current_group_id"
        ];

    // Output the JSON response
    echo json_encode($resjson);

} else {
    // Error handling if `group_ids` are not provided
    echo json_encode(['error' => 'Missing group_ids parameter']);
}
?>

