<?php
function bimai_exportEcommerceDate($since)
{
    if (!isset($since)) {
        echo json_encode(array('ok' => false, 'error' => 'Missing since parameter'));
        return false;
    }
    $sinceDate = date('Y-m-d H:i:s', intval($_GET['since']));
    $query = "
    SELECT 
        i.id, 
        i .document_no, 
        i.type, 
        i.register_date,
        i.sell_date,
        i.parent_name,
        i.parent_nip,
        i.parent_address_street,
        i.parent_address_postalcode,
        i.parent_address_city,
        i.parent_address_country,
        i.currency,
        i.total_netto,
        i.total_brutto,
        i.total_vat,
        i.origin
    FROM ecommerce_invoices i
    WHERE
      i.origin = 'allegro' 
      AND YEAR(i.register_date) = 2024
      AND i.register_date > '$sinceDate'
    ORDER BY i.register_date
    LIMIT 0,10000;
";

    $db = $GLOBALS['db'];
    $query = $db->query($query);
    if ($db->last_error != '') {
        echo json_encode(array('ok' => false, 'error' => $db->last_error));
        return false;
    }
    $data = array();
    while ($row = $db->fetchByAssoc($query)) {
        $d = array();
        $d['e5Id'] = $row['id'];
        $d['documentNo'] = $row['document_no'];
        $d['type'] = $row['type'];
        $d['registerDate'] = $row['register_date'];
        $d['sellDate'] = $row['sell_date'];
        $d['clientName'] = $row['parent_name'];
        $d['clientId'] = $row['parent_id'] ?: '';
        $d['clientNip'] = $row['parent_nip'] ?: '';
        $d['clientAddress'] = $row['parent_address_street'] . ", " . $row['parent_address_postalcode'] . " " . $row['parent_address_city'] . " " . $row['parent_address_country'];;
        $d['currency'] = $row['currency'];
        $d['totalNetto'] = $row['total_netto'];
        $d['totalBrutto'] = $row['total_brutto'];
        $d['totalVat'] = $row['total_vat'];
        $d['source'] = $row['origin'];
        $data[] = $d;
    }

    echo json_encode(array('ok' => true, 'dataSize' => count($data), 'data' => $data));
    return true;
}