<?php
$invoices = getInvoices('2024');

$products = array();
foreach ($invoices as $invoice) {
    foreach ($invoice['products'] as $product) {
        $products[] = $product['ecmproduct_id'];
    }
}

$states = getStockStates($products);
$canProceed = [];
$cantProceed = [];
$missingProducts = [];
$msg = [];
foreach ($invoices as $invoice) {
    if ($DEBUG) {
        $msg[] = "Sprawdzam fakture: " . $invoice['document_no'] . "<br>";
    }
    $proceed = true; // hope :)
    foreach ($invoice['products'] as $product) {
        if ($DEBUG) {
            $msg[] = "&nbsp;&nbsp;&nbsp;Sprawdzam produkt: " . $product['code'] . " (Ilość: " . $product['quantity'] . ")<br>";
            $msg[] = "&nbsp;&nbsp;&nbsp;&nbspStan magazynowy: " . $states[$product['ecmproduct_id']] . "<br>";
        }
        if ($states[$product['ecmproduct_id']] < $product['quantity']) {
            if ($DEBUG) {
                $msg[] = "&nbsp;&nbsp;&nbsp;&nbsp<b>Nie ma wystarczającej ilości produktu w magazynie</b><br>";
            }
            if (!isset($missingProducts[$product['code']])) {
                $missingProducts[$product['code']] = array();
                $missingProducts[$product['code']]['id'] = $product['ecmproduct_id'];
                $missingProducts[$product['code']]['code'] = $product['code'];
                $missingProducts[$product['code']]['missing'] = $product['quantity'] - $states[$product['ecmproduct_id']];
            } else {
                $missingProducts[$product['code']]['missing'] += $product['quantity'] - $states[$product['ecmproduct_id']];
            }
            $proceed = false;
            break;
        }
    }
    if ($proceed) {
        $canProceed[] = $invoice;
        foreach ($invoice['products'] as $product) {
            $states[$product['ecmproduct_id']] -= $product['quantity'];
        }
    } else {
        $cantProceed[] = $invoice;
    }
}

// create list of invoice ids from canProceed
$invoiceIds = array();
foreach ($canProceed as $invoice) {
    $invoiceIds[] = $invoice['id'];
}

$sessionId = create_guid();
$_SESSION[$sessionId] = $invoiceIds;

if (count($cantProceed) == 0) {
    echo '<input title="Wystaw WZ" class="button primary" type="button" name="Edit" id="edit_button" value="Wystaw WZ"
    onclick="window.open(\'index.php?module=EcmStockDocOuts&action=EditView&ecommerceWZ=' . $sessionId . '\')">';
} else {
    var_dump($cantProceed);
}
die();

function getInvoices($date)
{
    $db = $GLOBALS['db'];
    $invoices = array();
    // fomat date from d.m.y to mysql format
    $query = "SELECT ip.ecmproduct_id, ip.code, i.document_no, SUM(ip.quantity) AS quantity, i.register_date, i.id
FROM ecommerce_invoices_products AS ip
INNER JOIN ecommerce_invoices AS i ON ip.invoice_id = i.id AND i.register_date LIKE '$date%' AND i.type='normal'
AND i.origin IN ('amazon vat local')
WHERE ip.ecmproduct_id != '' AND ip.ecmproduct_id !='165f364e-9301-25ac-5906-58e38f1de4ca' 
AND i.ecmstockdocout_id IS NULL
GROUP BY i.id, ip.ecmproduct_id
ORDER BY i.register_date;";
    $res = $db->query($query);
    while ($row = $db->fetchByAssoc($res)) {
        if (!isset($invoices[$row['document_no']])) {
            $invoices[$row['document_no']] = array();
            $invoices[$row['document_no']]['document_no'] = $row['document_no'];
            $invoices[$row['document_no']]['register_date'] = $row['register_date'];
            $invoices[$row['document_no']]['id'] = $row['id'];
            $invoices[$row['document_no']]['products'] = array();
            $invoices[$row['document_no']]['products'][] = array(
                'ecmproduct_id' => $row['ecmproduct_id'],
                'code' => $row['code'],
                'quantity' => $row['quantity'],
            );
        } else {
            $invoices[$row['document_no']]['products'][] = array(
                'ecmproduct_id' => $row['ecmproduct_id'],
                'code' => $row['code'],
                'quantity' => $row['quantity'],
            );
        }
    }
    $invoices = array_values($invoices);
    usort($invoices, function ($a, $b) {
        return $a['id'] - $b['id'];
    });
    return $invoices;
}

function getStockStates($products)
{
    $db = $GLOBALS['db'];
    $query = "SELECT s.product_id, s.quantity FROM ecmstockstates AS s WHERE s.stock_id = 'add8ef6f-3d1f-5ccf-c486-64719142f096' AND s.product_id IN ('" . implode('\',\'', $products) . "')";
    $res = $db->query($query);
    $stockStates = array();
    while ($row = $db->fetchByAssoc($res)) {
        $stockStates[$row['product_id']] = isset($row['quantity']) ? intval($row['quantity']) : 0;
    }
    return $stockStates;
}

function getProductsForWZ($invoiceIds)
{
    $db = $GLOBALS['db'];
    $query = "SELECT ip.ecmproduct_id, SUM(ip.quantity) AS quantity, ip.price_netto
FROM ecommerce_invoices_products AS ip
WHERE invoice_id IN ('" . implode('\',\'', $invoiceIds) . "')
AND ip.ecmproduct_id NOT IN ('', '165f364e-9301-25ac-5906-58e38f1de4ca')
GROUP BY ip.ecmproduct_id, ip.price_netto;";
    $res = $db->query($query);
    $products = array();
    while ($row = $db->fetchByAssoc($res)) {
        $products[] = array(
            'ecmproduct_id' => $row['ecmproduct_id'],
            'quantity' => $row['quantity'],
            'price_netto' => $row['price_netto'],
        );
    }
    return $products;
}
